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 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumArrayLenItCounts,
143           "Number of trip counts computed with array length");
144 STATISTIC(NumTripCountsComputed,
145           "Number of loops with predictable loop counts");
146 STATISTIC(NumTripCountsNotComputed,
147           "Number of loops without predictable loop counts");
148 STATISTIC(NumBruteForceTripCountsComputed,
149           "Number of loops with trip counts computed by force");
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
160 static cl::opt<bool> VerifySCEV(
161     "verify-scev", cl::Hidden,
162     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 static cl::opt<bool> VerifySCEVStrict(
164     "verify-scev-strict", cl::Hidden,
165     cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool>
167     VerifySCEVMap("verify-scev-maps", cl::Hidden,
168                   cl::desc("Verify no dangling value in ScalarEvolution's "
169                            "ExprValueMap (slow)"));
170 
171 static cl::opt<bool> VerifyIR(
172     "scev-verify-ir", cl::Hidden,
173     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
174     cl::init(false));
175 
176 static cl::opt<unsigned> MulOpsInlineThreshold(
177     "scev-mulops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
179     cl::init(32));
180 
181 static cl::opt<unsigned> AddOpsInlineThreshold(
182     "scev-addops-inline-threshold", cl::Hidden,
183     cl::desc("Threshold for inlining addition operands into a SCEV"),
184     cl::init(500));
185 
186 static cl::opt<unsigned> MaxSCEVCompareDepth(
187     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
189     cl::init(32));
190 
191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
192     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
194     cl::init(2));
195 
196 static cl::opt<unsigned> MaxValueCompareDepth(
197     "scalar-evolution-max-value-compare-depth", cl::Hidden,
198     cl::desc("Maximum depth of recursive value complexity comparisons"),
199     cl::init(2));
200 
201 static cl::opt<unsigned>
202     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
203                   cl::desc("Maximum depth of recursive arithmetics"),
204                   cl::init(32));
205 
206 static cl::opt<unsigned> MaxConstantEvolvingDepth(
207     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
208     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
209 
210 static cl::opt<unsigned>
211     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
212                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
213                  cl::init(8));
214 
215 static cl::opt<unsigned>
216     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
217                   cl::desc("Max coefficients in AddRec during evolving"),
218                   cl::init(8));
219 
220 static cl::opt<unsigned>
221     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
222                   cl::desc("Size of the expression which is considered huge"),
223                   cl::init(4096));
224 
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227     cl::Hidden, cl::init(true),
228     cl::desc("When printing analysis, include information on every instruction"));
229 
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232     cl::init(false),
233     cl::desc("Use more powerful methods of sharpening expression ranges. May "
234              "be costly in terms of compile time"));
235 
236 //===----------------------------------------------------------------------===//
237 //                           SCEV class definitions
238 //===----------------------------------------------------------------------===//
239 
240 //===----------------------------------------------------------------------===//
241 // Implementation of the SCEV class.
242 //
243 
244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
245 LLVM_DUMP_METHOD void SCEV::dump() const {
246   print(dbgs());
247   dbgs() << '\n';
248 }
249 #endif
250 
251 void SCEV::print(raw_ostream &OS) const {
252   switch (getSCEVType()) {
253   case scConstant:
254     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
255     return;
256   case scPtrToInt: {
257     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
258     const SCEV *Op = PtrToInt->getOperand();
259     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
260        << *PtrToInt->getType() << ")";
261     return;
262   }
263   case scTruncate: {
264     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
265     const SCEV *Op = Trunc->getOperand();
266     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
267        << *Trunc->getType() << ")";
268     return;
269   }
270   case scZeroExtend: {
271     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
272     const SCEV *Op = ZExt->getOperand();
273     OS << "(zext " << *Op->getType() << " " << *Op << " to "
274        << *ZExt->getType() << ")";
275     return;
276   }
277   case scSignExtend: {
278     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
279     const SCEV *Op = SExt->getOperand();
280     OS << "(sext " << *Op->getType() << " " << *Op << " to "
281        << *SExt->getType() << ")";
282     return;
283   }
284   case scAddRecExpr: {
285     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
286     OS << "{" << *AR->getOperand(0);
287     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
288       OS << ",+," << *AR->getOperand(i);
289     OS << "}<";
290     if (AR->hasNoUnsignedWrap())
291       OS << "nuw><";
292     if (AR->hasNoSignedWrap())
293       OS << "nsw><";
294     if (AR->hasNoSelfWrap() &&
295         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
296       OS << "nw><";
297     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
298     OS << ">";
299     return;
300   }
301   case scAddExpr:
302   case scMulExpr:
303   case scUMaxExpr:
304   case scSMaxExpr:
305   case scUMinExpr:
306   case scSMinExpr: {
307     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
308     const char *OpStr = nullptr;
309     switch (NAry->getSCEVType()) {
310     case scAddExpr: OpStr = " + "; break;
311     case scMulExpr: OpStr = " * "; break;
312     case scUMaxExpr: OpStr = " umax "; break;
313     case scSMaxExpr: OpStr = " smax "; break;
314     case scUMinExpr:
315       OpStr = " umin ";
316       break;
317     case scSMinExpr:
318       OpStr = " smin ";
319       break;
320     default:
321       llvm_unreachable("There are no other nary expression types.");
322     }
323     OS << "(";
324     ListSeparator LS(OpStr);
325     for (const SCEV *Op : NAry->operands())
326       OS << LS << *Op;
327     OS << ")";
328     switch (NAry->getSCEVType()) {
329     case scAddExpr:
330     case scMulExpr:
331       if (NAry->hasNoUnsignedWrap())
332         OS << "<nuw>";
333       if (NAry->hasNoSignedWrap())
334         OS << "<nsw>";
335       break;
336     default:
337       // Nothing to print for other nary expressions.
338       break;
339     }
340     return;
341   }
342   case scUDivExpr: {
343     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
344     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
345     return;
346   }
347   case scUnknown: {
348     const SCEVUnknown *U = cast<SCEVUnknown>(this);
349     Type *AllocTy;
350     if (U->isSizeOf(AllocTy)) {
351       OS << "sizeof(" << *AllocTy << ")";
352       return;
353     }
354     if (U->isAlignOf(AllocTy)) {
355       OS << "alignof(" << *AllocTy << ")";
356       return;
357     }
358 
359     Type *CTy;
360     Constant *FieldNo;
361     if (U->isOffsetOf(CTy, FieldNo)) {
362       OS << "offsetof(" << *CTy << ", ";
363       FieldNo->printAsOperand(OS, false);
364       OS << ")";
365       return;
366     }
367 
368     // Otherwise just print it normally.
369     U->getValue()->printAsOperand(OS, false);
370     return;
371   }
372   case scCouldNotCompute:
373     OS << "***COULDNOTCOMPUTE***";
374     return;
375   }
376   llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 Type *SCEV::getType() const {
380   switch (getSCEVType()) {
381   case scConstant:
382     return cast<SCEVConstant>(this)->getType();
383   case scPtrToInt:
384   case scTruncate:
385   case scZeroExtend:
386   case scSignExtend:
387     return cast<SCEVCastExpr>(this)->getType();
388   case scAddRecExpr:
389   case scMulExpr:
390   case scUMaxExpr:
391   case scSMaxExpr:
392   case scUMinExpr:
393   case scSMinExpr:
394     return cast<SCEVNAryExpr>(this)->getType();
395   case scAddExpr:
396     return cast<SCEVAddExpr>(this)->getType();
397   case scUDivExpr:
398     return cast<SCEVUDivExpr>(this)->getType();
399   case scUnknown:
400     return cast<SCEVUnknown>(this)->getType();
401   case scCouldNotCompute:
402     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
403   }
404   llvm_unreachable("Unknown SCEV kind!");
405 }
406 
407 bool SCEV::isZero() const {
408   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
409     return SC->getValue()->isZero();
410   return false;
411 }
412 
413 bool SCEV::isOne() const {
414   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
415     return SC->getValue()->isOne();
416   return false;
417 }
418 
419 bool SCEV::isAllOnesValue() const {
420   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
421     return SC->getValue()->isMinusOne();
422   return false;
423 }
424 
425 bool SCEV::isNonConstantNegative() const {
426   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
427   if (!Mul) return false;
428 
429   // If there is a constant factor, it will be first.
430   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
431   if (!SC) return false;
432 
433   // Return true if the value is negative, this matches things like (-42 * V).
434   return SC->getAPInt().isNegative();
435 }
436 
437 SCEVCouldNotCompute::SCEVCouldNotCompute() :
438   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
439 
440 bool SCEVCouldNotCompute::classof(const SCEV *S) {
441   return S->getSCEVType() == scCouldNotCompute;
442 }
443 
444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
445   FoldingSetNodeID ID;
446   ID.AddInteger(scConstant);
447   ID.AddPointer(V);
448   void *IP = nullptr;
449   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
450   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
451   UniqueSCEVs.InsertNode(S, IP);
452   return S;
453 }
454 
455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
456   return getConstant(ConstantInt::get(getContext(), Val));
457 }
458 
459 const SCEV *
460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
461   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
462   return getConstant(ConstantInt::get(ITy, V, isSigned));
463 }
464 
465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
466                            const SCEV *op, Type *ty)
467     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
468   Operands[0] = op;
469 }
470 
471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
472                                    Type *ITy)
473     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
474   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
475          "Must be a non-bit-width-changing pointer-to-integer cast!");
476 }
477 
478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
479                                            SCEVTypes SCEVTy, const SCEV *op,
480                                            Type *ty)
481     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
482 
483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
484                                    Type *ty)
485     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
486   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
487          "Cannot truncate non-integer value!");
488 }
489 
490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
491                                        const SCEV *op, Type *ty)
492     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
493   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
494          "Cannot zero extend non-integer value!");
495 }
496 
497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
498                                        const SCEV *op, Type *ty)
499     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
500   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
501          "Cannot sign extend non-integer value!");
502 }
503 
504 void SCEVUnknown::deleted() {
505   // Clear this SCEVUnknown from various maps.
506   SE->forgetMemoizedResults(this);
507 
508   // Remove this SCEVUnknown from the uniquing map.
509   SE->UniqueSCEVs.RemoveNode(this);
510 
511   // Release the value.
512   setValPtr(nullptr);
513 }
514 
515 void SCEVUnknown::allUsesReplacedWith(Value *New) {
516   // Remove this SCEVUnknown from the uniquing map.
517   SE->UniqueSCEVs.RemoveNode(this);
518 
519   // Update this SCEVUnknown to point to the new value. This is needed
520   // because there may still be outstanding SCEVs which still point to
521   // this SCEVUnknown.
522   setValPtr(New);
523 }
524 
525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
526   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527     if (VCE->getOpcode() == Instruction::PtrToInt)
528       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529         if (CE->getOpcode() == Instruction::GetElementPtr &&
530             CE->getOperand(0)->isNullValue() &&
531             CE->getNumOperands() == 2)
532           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
533             if (CI->isOne()) {
534               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
535                                  ->getElementType();
536               return true;
537             }
538 
539   return false;
540 }
541 
542 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
543   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
544     if (VCE->getOpcode() == Instruction::PtrToInt)
545       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
546         if (CE->getOpcode() == Instruction::GetElementPtr &&
547             CE->getOperand(0)->isNullValue()) {
548           Type *Ty =
549             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
550           if (StructType *STy = dyn_cast<StructType>(Ty))
551             if (!STy->isPacked() &&
552                 CE->getNumOperands() == 3 &&
553                 CE->getOperand(1)->isNullValue()) {
554               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
555                 if (CI->isOne() &&
556                     STy->getNumElements() == 2 &&
557                     STy->getElementType(0)->isIntegerTy(1)) {
558                   AllocTy = STy->getElementType(1);
559                   return true;
560                 }
561             }
562         }
563 
564   return false;
565 }
566 
567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
568   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
569     if (VCE->getOpcode() == Instruction::PtrToInt)
570       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
571         if (CE->getOpcode() == Instruction::GetElementPtr &&
572             CE->getNumOperands() == 3 &&
573             CE->getOperand(0)->isNullValue() &&
574             CE->getOperand(1)->isNullValue()) {
575           Type *Ty =
576             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
577           // Ignore vector types here so that ScalarEvolutionExpander doesn't
578           // emit getelementptrs that index into vectors.
579           if (Ty->isStructTy() || Ty->isArrayTy()) {
580             CTy = Ty;
581             FieldNo = CE->getOperand(2);
582             return true;
583           }
584         }
585 
586   return false;
587 }
588 
589 //===----------------------------------------------------------------------===//
590 //                               SCEV Utilities
591 //===----------------------------------------------------------------------===//
592 
593 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
594 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
595 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
596 /// have been previously deemed to be "equally complex" by this routine.  It is
597 /// intended to avoid exponential time complexity in cases like:
598 ///
599 ///   %a = f(%x, %y)
600 ///   %b = f(%a, %a)
601 ///   %c = f(%b, %b)
602 ///
603 ///   %d = f(%x, %y)
604 ///   %e = f(%d, %d)
605 ///   %f = f(%e, %e)
606 ///
607 ///   CompareValueComplexity(%f, %c)
608 ///
609 /// Since we do not continue running this routine on expression trees once we
610 /// have seen unequal values, there is no need to track them in the cache.
611 static int
612 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
613                        const LoopInfo *const LI, Value *LV, Value *RV,
614                        unsigned Depth) {
615   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
616     return 0;
617 
618   // Order pointer values after integer values. This helps SCEVExpander form
619   // GEPs.
620   bool LIsPointer = LV->getType()->isPointerTy(),
621        RIsPointer = RV->getType()->isPointerTy();
622   if (LIsPointer != RIsPointer)
623     return (int)LIsPointer - (int)RIsPointer;
624 
625   // Compare getValueID values.
626   unsigned LID = LV->getValueID(), RID = RV->getValueID();
627   if (LID != RID)
628     return (int)LID - (int)RID;
629 
630   // Sort arguments by their position.
631   if (const auto *LA = dyn_cast<Argument>(LV)) {
632     const auto *RA = cast<Argument>(RV);
633     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
634     return (int)LArgNo - (int)RArgNo;
635   }
636 
637   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
638     const auto *RGV = cast<GlobalValue>(RV);
639 
640     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
641       auto LT = GV->getLinkage();
642       return !(GlobalValue::isPrivateLinkage(LT) ||
643                GlobalValue::isInternalLinkage(LT));
644     };
645 
646     // Use the names to distinguish the two values, but only if the
647     // names are semantically important.
648     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
649       return LGV->getName().compare(RGV->getName());
650   }
651 
652   // For instructions, compare their loop depth, and their operand count.  This
653   // is pretty loose.
654   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
655     const auto *RInst = cast<Instruction>(RV);
656 
657     // Compare loop depths.
658     const BasicBlock *LParent = LInst->getParent(),
659                      *RParent = RInst->getParent();
660     if (LParent != RParent) {
661       unsigned LDepth = LI->getLoopDepth(LParent),
662                RDepth = LI->getLoopDepth(RParent);
663       if (LDepth != RDepth)
664         return (int)LDepth - (int)RDepth;
665     }
666 
667     // Compare the number of operands.
668     unsigned LNumOps = LInst->getNumOperands(),
669              RNumOps = RInst->getNumOperands();
670     if (LNumOps != RNumOps)
671       return (int)LNumOps - (int)RNumOps;
672 
673     for (unsigned Idx : seq(0u, LNumOps)) {
674       int Result =
675           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
676                                  RInst->getOperand(Idx), Depth + 1);
677       if (Result != 0)
678         return Result;
679     }
680   }
681 
682   EqCacheValue.unionSets(LV, RV);
683   return 0;
684 }
685 
686 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
687 // than RHS, respectively. A three-way result allows recursive comparisons to be
688 // more efficient.
689 // If the max analysis depth was reached, return None, assuming we do not know
690 // if they are equivalent for sure.
691 static Optional<int>
692 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693                       EquivalenceClasses<const Value *> &EqCacheValue,
694                       const LoopInfo *const LI, const SCEV *LHS,
695                       const SCEV *RHS, 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 (EqCacheSCEV.isEquivalent(LHS, RHS))
706     return 0;
707 
708   if (Depth > MaxSCEVCompareDepth)
709     return None;
710 
711   // Aside from the getSCEVType() ordering, the particular ordering
712   // isn't very important except that it's beneficial to be consistent,
713   // so that (a + b) and (b + a) don't end up as different expressions.
714   switch (LType) {
715   case scUnknown: {
716     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
717     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
718 
719     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
720                                    RU->getValue(), Depth + 1);
721     if (X == 0)
722       EqCacheSCEV.unionSets(LHS, RHS);
723     return X;
724   }
725 
726   case scConstant: {
727     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
728     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
729 
730     // Compare constant values.
731     const APInt &LA = LC->getAPInt();
732     const APInt &RA = RC->getAPInt();
733     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
734     if (LBitWidth != RBitWidth)
735       return (int)LBitWidth - (int)RBitWidth;
736     return LA.ult(RA) ? -1 : 1;
737   }
738 
739   case scAddRecExpr: {
740     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
741     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
742 
743     // There is always a dominance between two recs that are used by one SCEV,
744     // so we can safely sort recs by loop header dominance. We require such
745     // order in getAddExpr.
746     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
747     if (LLoop != RLoop) {
748       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
749       assert(LHead != RHead && "Two loops share the same header?");
750       if (DT.dominates(LHead, RHead))
751         return 1;
752       else
753         assert(DT.dominates(RHead, LHead) &&
754                "No dominance between recurrences used by one SCEV?");
755       return -1;
756     }
757 
758     // Addrec complexity grows with operand count.
759     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
760     if (LNumOps != RNumOps)
761       return (int)LNumOps - (int)RNumOps;
762 
763     // Lexicographically compare.
764     for (unsigned i = 0; i != LNumOps; ++i) {
765       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
766                                      LA->getOperand(i), RA->getOperand(i), DT,
767                                      Depth + 1);
768       if (X != 0)
769         return X;
770     }
771     EqCacheSCEV.unionSets(LHS, RHS);
772     return 0;
773   }
774 
775   case scAddExpr:
776   case scMulExpr:
777   case scSMaxExpr:
778   case scUMaxExpr:
779   case scSMinExpr:
780   case scUMinExpr: {
781     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
782     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
783 
784     // Lexicographically compare n-ary expressions.
785     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
786     if (LNumOps != RNumOps)
787       return (int)LNumOps - (int)RNumOps;
788 
789     for (unsigned i = 0; i != LNumOps; ++i) {
790       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
791                                      LC->getOperand(i), RC->getOperand(i), DT,
792                                      Depth + 1);
793       if (X != 0)
794         return X;
795     }
796     EqCacheSCEV.unionSets(LHS, RHS);
797     return 0;
798   }
799 
800   case scUDivExpr: {
801     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
802     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
803 
804     // Lexicographically compare udiv expressions.
805     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
806                                    RC->getLHS(), DT, Depth + 1);
807     if (X != 0)
808       return X;
809     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
810                               RC->getRHS(), DT, Depth + 1);
811     if (X == 0)
812       EqCacheSCEV.unionSets(LHS, RHS);
813     return X;
814   }
815 
816   case scPtrToInt:
817   case scTruncate:
818   case scZeroExtend:
819   case scSignExtend: {
820     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
821     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
822 
823     // Compare cast expressions by operand.
824     auto X =
825         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
826                               RC->getOperand(), DT, Depth + 1);
827     if (X == 0)
828       EqCacheSCEV.unionSets(LHS, RHS);
829     return X;
830   }
831 
832   case scCouldNotCompute:
833     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
834   }
835   llvm_unreachable("Unknown SCEV kind!");
836 }
837 
838 /// Given a list of SCEV objects, order them by their complexity, and group
839 /// objects of the same complexity together by value.  When this routine is
840 /// finished, we know that any duplicates in the vector are consecutive and that
841 /// complexity is monotonically increasing.
842 ///
843 /// Note that we go take special precautions to ensure that we get deterministic
844 /// results from this routine.  In other words, we don't want the results of
845 /// this to depend on where the addresses of various SCEV objects happened to
846 /// land in memory.
847 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
848                               LoopInfo *LI, DominatorTree &DT) {
849   if (Ops.size() < 2) return;  // Noop
850 
851   EquivalenceClasses<const SCEV *> EqCacheSCEV;
852   EquivalenceClasses<const Value *> EqCacheValue;
853 
854   // Whether LHS has provably less complexity than RHS.
855   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
856     auto Complexity =
857         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
858     return Complexity && *Complexity < 0;
859   };
860   if (Ops.size() == 2) {
861     // This is the common case, which also happens to be trivially simple.
862     // Special case it.
863     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
864     if (IsLessComplex(RHS, LHS))
865       std::swap(LHS, RHS);
866     return;
867   }
868 
869   // Do the rough sort by complexity.
870   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
871     return IsLessComplex(LHS, RHS);
872   });
873 
874   // Now that we are sorted by complexity, group elements of the same
875   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
876   // be extremely short in practice.  Note that we take this approach because we
877   // do not want to depend on the addresses of the objects we are grouping.
878   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
879     const SCEV *S = Ops[i];
880     unsigned Complexity = S->getSCEVType();
881 
882     // If there are any objects of the same complexity and same value as this
883     // one, group them.
884     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
885       if (Ops[j] == S) { // Found a duplicate.
886         // Move it to immediately after i'th element.
887         std::swap(Ops[i+1], Ops[j]);
888         ++i;   // no need to rescan it.
889         if (i == e-2) return;  // Done!
890       }
891     }
892   }
893 }
894 
895 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
896 /// least HugeExprThreshold nodes).
897 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
898   return any_of(Ops, [](const SCEV *S) {
899     return S->getExpressionSize() >= HugeExprThreshold;
900   });
901 }
902 
903 //===----------------------------------------------------------------------===//
904 //                      Simple SCEV method implementations
905 //===----------------------------------------------------------------------===//
906 
907 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
908 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
909                                        ScalarEvolution &SE,
910                                        Type *ResultTy) {
911   // Handle the simplest case efficiently.
912   if (K == 1)
913     return SE.getTruncateOrZeroExtend(It, ResultTy);
914 
915   // We are using the following formula for BC(It, K):
916   //
917   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
918   //
919   // Suppose, W is the bitwidth of the return value.  We must be prepared for
920   // overflow.  Hence, we must assure that the result of our computation is
921   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
922   // safe in modular arithmetic.
923   //
924   // However, this code doesn't use exactly that formula; the formula it uses
925   // is something like the following, where T is the number of factors of 2 in
926   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
927   // exponentiation:
928   //
929   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
930   //
931   // This formula is trivially equivalent to the previous formula.  However,
932   // this formula can be implemented much more efficiently.  The trick is that
933   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
934   // arithmetic.  To do exact division in modular arithmetic, all we have
935   // to do is multiply by the inverse.  Therefore, this step can be done at
936   // width W.
937   //
938   // The next issue is how to safely do the division by 2^T.  The way this
939   // is done is by doing the multiplication step at a width of at least W + T
940   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
941   // when we perform the division by 2^T (which is equivalent to a right shift
942   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
943   // truncated out after the division by 2^T.
944   //
945   // In comparison to just directly using the first formula, this technique
946   // is much more efficient; using the first formula requires W * K bits,
947   // but this formula less than W + K bits. Also, the first formula requires
948   // a division step, whereas this formula only requires multiplies and shifts.
949   //
950   // It doesn't matter whether the subtraction step is done in the calculation
951   // width or the input iteration count's width; if the subtraction overflows,
952   // the result must be zero anyway.  We prefer here to do it in the width of
953   // the induction variable because it helps a lot for certain cases; CodeGen
954   // isn't smart enough to ignore the overflow, which leads to much less
955   // efficient code if the width of the subtraction is wider than the native
956   // register width.
957   //
958   // (It's possible to not widen at all by pulling out factors of 2 before
959   // the multiplication; for example, K=2 can be calculated as
960   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
961   // extra arithmetic, so it's not an obvious win, and it gets
962   // much more complicated for K > 3.)
963 
964   // Protection from insane SCEVs; this bound is conservative,
965   // but it probably doesn't matter.
966   if (K > 1000)
967     return SE.getCouldNotCompute();
968 
969   unsigned W = SE.getTypeSizeInBits(ResultTy);
970 
971   // Calculate K! / 2^T and T; we divide out the factors of two before
972   // multiplying for calculating K! / 2^T to avoid overflow.
973   // Other overflow doesn't matter because we only care about the bottom
974   // W bits of the result.
975   APInt OddFactorial(W, 1);
976   unsigned T = 1;
977   for (unsigned i = 3; i <= K; ++i) {
978     APInt Mult(W, i);
979     unsigned TwoFactors = Mult.countTrailingZeros();
980     T += TwoFactors;
981     Mult.lshrInPlace(TwoFactors);
982     OddFactorial *= Mult;
983   }
984 
985   // We need at least W + T bits for the multiplication step
986   unsigned CalculationBits = W + T;
987 
988   // Calculate 2^T, at width T+W.
989   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
990 
991   // Calculate the multiplicative inverse of K! / 2^T;
992   // this multiplication factor will perform the exact division by
993   // K! / 2^T.
994   APInt Mod = APInt::getSignedMinValue(W+1);
995   APInt MultiplyFactor = OddFactorial.zext(W+1);
996   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
997   MultiplyFactor = MultiplyFactor.trunc(W);
998 
999   // Calculate the product, at width T+W
1000   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1001                                                       CalculationBits);
1002   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1003   for (unsigned i = 1; i != K; ++i) {
1004     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1005     Dividend = SE.getMulExpr(Dividend,
1006                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1007   }
1008 
1009   // Divide by 2^T
1010   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1011 
1012   // Truncate the result, and divide by K! / 2^T.
1013 
1014   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1015                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1016 }
1017 
1018 /// Return the value of this chain of recurrences at the specified iteration
1019 /// number.  We can evaluate this recurrence by multiplying each element in the
1020 /// chain by the binomial coefficient corresponding to it.  In other words, we
1021 /// can evaluate {A,+,B,+,C,+,D} as:
1022 ///
1023 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1024 ///
1025 /// where BC(It, k) stands for binomial coefficient.
1026 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1027                                                 ScalarEvolution &SE) const {
1028   const SCEV *Result = getStart();
1029   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1030     // The computation is correct in the face of overflow provided that the
1031     // multiplication is performed _after_ the evaluation of the binomial
1032     // coefficient.
1033     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1034     if (isa<SCEVCouldNotCompute>(Coeff))
1035       return Coeff;
1036 
1037     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1038   }
1039   return Result;
1040 }
1041 
1042 //===----------------------------------------------------------------------===//
1043 //                    SCEV Expression folder implementations
1044 //===----------------------------------------------------------------------===//
1045 
1046 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1047                                                      unsigned Depth) {
1048   assert(Depth <= 1 &&
1049          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1050 
1051   // We could be called with an integer-typed operands during SCEV rewrites.
1052   // Since the operand is an integer already, just perform zext/trunc/self cast.
1053   if (!Op->getType()->isPointerTy())
1054     return Op;
1055 
1056   assert(!getDataLayout().isNonIntegralPointerType(Op->getType()) &&
1057          "Source pointer type must be integral for ptrtoint!");
1058 
1059   // What would be an ID for such a SCEV cast expression?
1060   FoldingSetNodeID ID;
1061   ID.AddInteger(scPtrToInt);
1062   ID.AddPointer(Op);
1063 
1064   void *IP = nullptr;
1065 
1066   // Is there already an expression for such a cast?
1067   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1068     return S;
1069 
1070   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1071 
1072   // We can only model ptrtoint if SCEV's effective (integer) type
1073   // is sufficiently wide to represent all possible pointer values.
1074   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1075       getDataLayout().getTypeSizeInBits(IntPtrTy))
1076     return getCouldNotCompute();
1077 
1078   // If not, is this expression something we can't reduce any further?
1079   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1080     // Perform some basic constant folding. If the operand of the ptr2int cast
1081     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1082     // left as-is), but produce a zero constant.
1083     // NOTE: We could handle a more general case, but lack motivational cases.
1084     if (isa<ConstantPointerNull>(U->getValue()))
1085       return getZero(IntPtrTy);
1086 
1087     // Create an explicit cast node.
1088     // We can reuse the existing insert position since if we get here,
1089     // we won't have made any changes which would invalidate it.
1090     SCEV *S = new (SCEVAllocator)
1091         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1092     UniqueSCEVs.InsertNode(S, IP);
1093     addToLoopUseLists(S);
1094     return S;
1095   }
1096 
1097   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1098                        "non-SCEVUnknown's.");
1099 
1100   // Otherwise, we've got some expression that is more complex than just a
1101   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1102   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1103   // only, and the expressions must otherwise be integer-typed.
1104   // So sink the cast down to the SCEVUnknown's.
1105 
1106   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1107   /// which computes a pointer-typed value, and rewrites the whole expression
1108   /// tree so that *all* the computations are done on integers, and the only
1109   /// pointer-typed operands in the expression are SCEVUnknown.
1110   class SCEVPtrToIntSinkingRewriter
1111       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1112     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1113 
1114   public:
1115     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1116 
1117     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1118       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1119       return Rewriter.visit(Scev);
1120     }
1121 
1122     const SCEV *visit(const SCEV *S) {
1123       Type *STy = S->getType();
1124       // If the expression is not pointer-typed, just keep it as-is.
1125       if (!STy->isPointerTy())
1126         return S;
1127       // Else, recursively sink the cast down into it.
1128       return Base::visit(S);
1129     }
1130 
1131     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1132       SmallVector<const SCEV *, 2> Operands;
1133       bool Changed = false;
1134       for (auto *Op : Expr->operands()) {
1135         Operands.push_back(visit(Op));
1136         Changed |= Op != Operands.back();
1137       }
1138       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1139     }
1140 
1141     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1142       SmallVector<const SCEV *, 2> Operands;
1143       bool Changed = false;
1144       for (auto *Op : Expr->operands()) {
1145         Operands.push_back(visit(Op));
1146         Changed |= Op != Operands.back();
1147       }
1148       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1149     }
1150 
1151     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1152       assert(Expr->getType()->isPointerTy() &&
1153              "Should only reach pointer-typed SCEVUnknown's.");
1154       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1155     }
1156   };
1157 
1158   // And actually perform the cast sinking.
1159   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1160   assert(IntOp->getType()->isIntegerTy() &&
1161          "We must have succeeded in sinking the cast, "
1162          "and ending up with an integer-typed expression!");
1163   return IntOp;
1164 }
1165 
1166 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1167   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1168 
1169   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1170   if (isa<SCEVCouldNotCompute>(IntOp))
1171     return IntOp;
1172 
1173   return getTruncateOrZeroExtend(IntOp, Ty);
1174 }
1175 
1176 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1177                                              unsigned Depth) {
1178   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1179          "This is not a truncating conversion!");
1180   assert(isSCEVable(Ty) &&
1181          "This is not a conversion to a SCEVable type!");
1182   Ty = getEffectiveSCEVType(Ty);
1183 
1184   FoldingSetNodeID ID;
1185   ID.AddInteger(scTruncate);
1186   ID.AddPointer(Op);
1187   ID.AddPointer(Ty);
1188   void *IP = nullptr;
1189   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1190 
1191   // Fold if the operand is constant.
1192   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1193     return getConstant(
1194       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1195 
1196   // trunc(trunc(x)) --> trunc(x)
1197   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1198     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1199 
1200   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1201   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1202     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1203 
1204   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1205   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1206     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1207 
1208   if (Depth > MaxCastDepth) {
1209     SCEV *S =
1210         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1211     UniqueSCEVs.InsertNode(S, IP);
1212     addToLoopUseLists(S);
1213     return S;
1214   }
1215 
1216   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1217   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1218   // if after transforming we have at most one truncate, not counting truncates
1219   // that replace other casts.
1220   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1221     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1222     SmallVector<const SCEV *, 4> Operands;
1223     unsigned numTruncs = 0;
1224     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1225          ++i) {
1226       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1227       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1228           isa<SCEVTruncateExpr>(S))
1229         numTruncs++;
1230       Operands.push_back(S);
1231     }
1232     if (numTruncs < 2) {
1233       if (isa<SCEVAddExpr>(Op))
1234         return getAddExpr(Operands);
1235       else if (isa<SCEVMulExpr>(Op))
1236         return getMulExpr(Operands);
1237       else
1238         llvm_unreachable("Unexpected SCEV type for Op.");
1239     }
1240     // Although we checked in the beginning that ID is not in the cache, it is
1241     // possible that during recursion and different modification ID was inserted
1242     // into the cache. So if we find it, just return it.
1243     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1244       return S;
1245   }
1246 
1247   // If the input value is a chrec scev, truncate the chrec's operands.
1248   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1249     SmallVector<const SCEV *, 4> Operands;
1250     for (const SCEV *Op : AddRec->operands())
1251       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1252     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1253   }
1254 
1255   // Return zero if truncating to known zeros.
1256   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1257   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1258     return getZero(Ty);
1259 
1260   // The cast wasn't folded; create an explicit cast node. We can reuse
1261   // the existing insert position since if we get here, we won't have
1262   // made any changes which would invalidate it.
1263   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1264                                                  Op, Ty);
1265   UniqueSCEVs.InsertNode(S, IP);
1266   addToLoopUseLists(S);
1267   return S;
1268 }
1269 
1270 // Get the limit of a recurrence such that incrementing by Step cannot cause
1271 // signed overflow as long as the value of the recurrence within the
1272 // loop does not exceed this limit before incrementing.
1273 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1274                                                  ICmpInst::Predicate *Pred,
1275                                                  ScalarEvolution *SE) {
1276   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1277   if (SE->isKnownPositive(Step)) {
1278     *Pred = ICmpInst::ICMP_SLT;
1279     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1280                            SE->getSignedRangeMax(Step));
1281   }
1282   if (SE->isKnownNegative(Step)) {
1283     *Pred = ICmpInst::ICMP_SGT;
1284     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1285                            SE->getSignedRangeMin(Step));
1286   }
1287   return nullptr;
1288 }
1289 
1290 // Get the limit of a recurrence such that incrementing by Step cannot cause
1291 // unsigned overflow as long as the value of the recurrence within the loop does
1292 // not exceed this limit before incrementing.
1293 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1294                                                    ICmpInst::Predicate *Pred,
1295                                                    ScalarEvolution *SE) {
1296   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1297   *Pred = ICmpInst::ICMP_ULT;
1298 
1299   return SE->getConstant(APInt::getMinValue(BitWidth) -
1300                          SE->getUnsignedRangeMax(Step));
1301 }
1302 
1303 namespace {
1304 
1305 struct ExtendOpTraitsBase {
1306   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1307                                                           unsigned);
1308 };
1309 
1310 // Used to make code generic over signed and unsigned overflow.
1311 template <typename ExtendOp> struct ExtendOpTraits {
1312   // Members present:
1313   //
1314   // static const SCEV::NoWrapFlags WrapType;
1315   //
1316   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1317   //
1318   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1319   //                                           ICmpInst::Predicate *Pred,
1320   //                                           ScalarEvolution *SE);
1321 };
1322 
1323 template <>
1324 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1325   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1326 
1327   static const GetExtendExprTy GetExtendExpr;
1328 
1329   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1330                                              ICmpInst::Predicate *Pred,
1331                                              ScalarEvolution *SE) {
1332     return getSignedOverflowLimitForStep(Step, Pred, SE);
1333   }
1334 };
1335 
1336 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1337     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1338 
1339 template <>
1340 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1341   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1342 
1343   static const GetExtendExprTy GetExtendExpr;
1344 
1345   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1346                                              ICmpInst::Predicate *Pred,
1347                                              ScalarEvolution *SE) {
1348     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1349   }
1350 };
1351 
1352 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1353     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1354 
1355 } // end anonymous namespace
1356 
1357 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1358 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1359 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1360 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1361 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1362 // expression "Step + sext/zext(PreIncAR)" is congruent with
1363 // "sext/zext(PostIncAR)"
1364 template <typename ExtendOpTy>
1365 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1366                                         ScalarEvolution *SE, unsigned Depth) {
1367   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1368   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1369 
1370   const Loop *L = AR->getLoop();
1371   const SCEV *Start = AR->getStart();
1372   const SCEV *Step = AR->getStepRecurrence(*SE);
1373 
1374   // Check for a simple looking step prior to loop entry.
1375   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1376   if (!SA)
1377     return nullptr;
1378 
1379   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1380   // subtraction is expensive. For this purpose, perform a quick and dirty
1381   // difference, by checking for Step in the operand list.
1382   SmallVector<const SCEV *, 4> DiffOps;
1383   for (const SCEV *Op : SA->operands())
1384     if (Op != Step)
1385       DiffOps.push_back(Op);
1386 
1387   if (DiffOps.size() == SA->getNumOperands())
1388     return nullptr;
1389 
1390   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1391   // `Step`:
1392 
1393   // 1. NSW/NUW flags on the step increment.
1394   auto PreStartFlags =
1395     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1396   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1397   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1398       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1399 
1400   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1401   // "S+X does not sign/unsign-overflow".
1402   //
1403 
1404   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1405   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1406       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1407     return PreStart;
1408 
1409   // 2. Direct overflow check on the step operation's expression.
1410   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1411   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1412   const SCEV *OperandExtendedStart =
1413       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1414                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1415   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1416     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1417       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1418       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1419       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1420       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1421     }
1422     return PreStart;
1423   }
1424 
1425   // 3. Loop precondition.
1426   ICmpInst::Predicate Pred;
1427   const SCEV *OverflowLimit =
1428       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1429 
1430   if (OverflowLimit &&
1431       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1432     return PreStart;
1433 
1434   return nullptr;
1435 }
1436 
1437 // Get the normalized zero or sign extended expression for this AddRec's Start.
1438 template <typename ExtendOpTy>
1439 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1440                                         ScalarEvolution *SE,
1441                                         unsigned Depth) {
1442   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1443 
1444   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1445   if (!PreStart)
1446     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1447 
1448   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1449                                              Depth),
1450                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1451 }
1452 
1453 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1454 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1455 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1456 //
1457 // Formally:
1458 //
1459 //     {S,+,X} == {S-T,+,X} + T
1460 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1461 //
1462 // If ({S-T,+,X} + T) does not overflow  ... (1)
1463 //
1464 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1465 //
1466 // If {S-T,+,X} does not overflow  ... (2)
1467 //
1468 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1469 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1470 //
1471 // If (S-T)+T does not overflow  ... (3)
1472 //
1473 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1474 //      == {Ext(S),+,Ext(X)} == LHS
1475 //
1476 // Thus, if (1), (2) and (3) are true for some T, then
1477 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1478 //
1479 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1480 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1481 // to check for (1) and (2).
1482 //
1483 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1484 // is `Delta` (defined below).
1485 template <typename ExtendOpTy>
1486 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1487                                                 const SCEV *Step,
1488                                                 const Loop *L) {
1489   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1490 
1491   // We restrict `Start` to a constant to prevent SCEV from spending too much
1492   // time here.  It is correct (but more expensive) to continue with a
1493   // non-constant `Start` and do a general SCEV subtraction to compute
1494   // `PreStart` below.
1495   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1496   if (!StartC)
1497     return false;
1498 
1499   APInt StartAI = StartC->getAPInt();
1500 
1501   for (unsigned Delta : {-2, -1, 1, 2}) {
1502     const SCEV *PreStart = getConstant(StartAI - Delta);
1503 
1504     FoldingSetNodeID ID;
1505     ID.AddInteger(scAddRecExpr);
1506     ID.AddPointer(PreStart);
1507     ID.AddPointer(Step);
1508     ID.AddPointer(L);
1509     void *IP = nullptr;
1510     const auto *PreAR =
1511       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1512 
1513     // Give up if we don't already have the add recurrence we need because
1514     // actually constructing an add recurrence is relatively expensive.
1515     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1516       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1517       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1518       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1519           DeltaS, &Pred, this);
1520       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1521         return true;
1522     }
1523   }
1524 
1525   return false;
1526 }
1527 
1528 // Finds an integer D for an expression (C + x + y + ...) such that the top
1529 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1530 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1531 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1532 // the (C + x + y + ...) expression is \p WholeAddExpr.
1533 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1534                                             const SCEVConstant *ConstantTerm,
1535                                             const SCEVAddExpr *WholeAddExpr) {
1536   const APInt &C = ConstantTerm->getAPInt();
1537   const unsigned BitWidth = C.getBitWidth();
1538   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1539   uint32_t TZ = BitWidth;
1540   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1541     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1542   if (TZ) {
1543     // Set D to be as many least significant bits of C as possible while still
1544     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1545     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1546   }
1547   return APInt(BitWidth, 0);
1548 }
1549 
1550 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1551 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1552 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1553 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1554 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1555                                             const APInt &ConstantStart,
1556                                             const SCEV *Step) {
1557   const unsigned BitWidth = ConstantStart.getBitWidth();
1558   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1559   if (TZ)
1560     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1561                          : ConstantStart;
1562   return APInt(BitWidth, 0);
1563 }
1564 
1565 const SCEV *
1566 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1567   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1568          "This is not an extending conversion!");
1569   assert(isSCEVable(Ty) &&
1570          "This is not a conversion to a SCEVable type!");
1571   Ty = getEffectiveSCEVType(Ty);
1572 
1573   // Fold if the operand is constant.
1574   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1575     return getConstant(
1576       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1577 
1578   // zext(zext(x)) --> zext(x)
1579   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1580     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1581 
1582   // Before doing any expensive analysis, check to see if we've already
1583   // computed a SCEV for this Op and Ty.
1584   FoldingSetNodeID ID;
1585   ID.AddInteger(scZeroExtend);
1586   ID.AddPointer(Op);
1587   ID.AddPointer(Ty);
1588   void *IP = nullptr;
1589   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1590   if (Depth > MaxCastDepth) {
1591     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1592                                                      Op, Ty);
1593     UniqueSCEVs.InsertNode(S, IP);
1594     addToLoopUseLists(S);
1595     return S;
1596   }
1597 
1598   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1599   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1600     // It's possible the bits taken off by the truncate were all zero bits. If
1601     // so, we should be able to simplify this further.
1602     const SCEV *X = ST->getOperand();
1603     ConstantRange CR = getUnsignedRange(X);
1604     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1605     unsigned NewBits = getTypeSizeInBits(Ty);
1606     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1607             CR.zextOrTrunc(NewBits)))
1608       return getTruncateOrZeroExtend(X, Ty, Depth);
1609   }
1610 
1611   // If the input value is a chrec scev, and we can prove that the value
1612   // did not overflow the old, smaller, value, we can zero extend all of the
1613   // operands (often constants).  This allows analysis of something like
1614   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1615   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1616     if (AR->isAffine()) {
1617       const SCEV *Start = AR->getStart();
1618       const SCEV *Step = AR->getStepRecurrence(*this);
1619       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1620       const Loop *L = AR->getLoop();
1621 
1622       if (!AR->hasNoUnsignedWrap()) {
1623         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1624         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1625       }
1626 
1627       // If we have special knowledge that this addrec won't overflow,
1628       // we don't need to do any further analysis.
1629       if (AR->hasNoUnsignedWrap())
1630         return getAddRecExpr(
1631             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1632             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1633 
1634       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1635       // Note that this serves two purposes: It filters out loops that are
1636       // simply not analyzable, and it covers the case where this code is
1637       // being called from within backedge-taken count analysis, such that
1638       // attempting to ask for the backedge-taken count would likely result
1639       // in infinite recursion. In the later case, the analysis code will
1640       // cope with a conservative value, and it will take care to purge
1641       // that value once it has finished.
1642       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1643       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1644         // Manually compute the final value for AR, checking for overflow.
1645 
1646         // Check whether the backedge-taken count can be losslessly casted to
1647         // the addrec's type. The count is always unsigned.
1648         const SCEV *CastedMaxBECount =
1649             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1650         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1651             CastedMaxBECount, MaxBECount->getType(), Depth);
1652         if (MaxBECount == RecastedMaxBECount) {
1653           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1654           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1655           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1656                                         SCEV::FlagAnyWrap, Depth + 1);
1657           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1658                                                           SCEV::FlagAnyWrap,
1659                                                           Depth + 1),
1660                                                WideTy, Depth + 1);
1661           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1662           const SCEV *WideMaxBECount =
1663             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1664           const SCEV *OperandExtendedAdd =
1665             getAddExpr(WideStart,
1666                        getMulExpr(WideMaxBECount,
1667                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1668                                   SCEV::FlagAnyWrap, Depth + 1),
1669                        SCEV::FlagAnyWrap, Depth + 1);
1670           if (ZAdd == OperandExtendedAdd) {
1671             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1672             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1673             // Return the expression with the addrec on the outside.
1674             return getAddRecExpr(
1675                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1676                                                          Depth + 1),
1677                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1678                 AR->getNoWrapFlags());
1679           }
1680           // Similar to above, only this time treat the step value as signed.
1681           // This covers loops that count down.
1682           OperandExtendedAdd =
1683             getAddExpr(WideStart,
1684                        getMulExpr(WideMaxBECount,
1685                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1686                                   SCEV::FlagAnyWrap, Depth + 1),
1687                        SCEV::FlagAnyWrap, Depth + 1);
1688           if (ZAdd == OperandExtendedAdd) {
1689             // Cache knowledge of AR NW, which is propagated to this AddRec.
1690             // Negative step causes unsigned wrap, but it still can't self-wrap.
1691             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1692             // Return the expression with the addrec on the outside.
1693             return getAddRecExpr(
1694                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1695                                                          Depth + 1),
1696                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1697                 AR->getNoWrapFlags());
1698           }
1699         }
1700       }
1701 
1702       // Normally, in the cases we can prove no-overflow via a
1703       // backedge guarding condition, we can also compute a backedge
1704       // taken count for the loop.  The exceptions are assumptions and
1705       // guards present in the loop -- SCEV is not great at exploiting
1706       // these to compute max backedge taken counts, but can still use
1707       // these to prove lack of overflow.  Use this fact to avoid
1708       // doing extra work that may not pay off.
1709       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1710           !AC.assumptions().empty()) {
1711 
1712         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1713         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1714         if (AR->hasNoUnsignedWrap()) {
1715           // Same as nuw case above - duplicated here to avoid a compile time
1716           // issue.  It's not clear that the order of checks does matter, but
1717           // it's one of two issue possible causes for a change which was
1718           // reverted.  Be conservative for the moment.
1719           return getAddRecExpr(
1720                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1721                                                          Depth + 1),
1722                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1723                 AR->getNoWrapFlags());
1724         }
1725 
1726         // For a negative step, we can extend the operands iff doing so only
1727         // traverses values in the range zext([0,UINT_MAX]).
1728         if (isKnownNegative(Step)) {
1729           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1730                                       getSignedRangeMin(Step));
1731           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1732               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1733             // Cache knowledge of AR NW, which is propagated to this
1734             // AddRec.  Negative step causes unsigned wrap, but it
1735             // still can't self-wrap.
1736             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1737             // Return the expression with the addrec on the outside.
1738             return getAddRecExpr(
1739                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1740                                                          Depth + 1),
1741                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1742                 AR->getNoWrapFlags());
1743           }
1744         }
1745       }
1746 
1747       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1748       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1749       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1750       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1751         const APInt &C = SC->getAPInt();
1752         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1753         if (D != 0) {
1754           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1755           const SCEV *SResidual =
1756               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1757           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1758           return getAddExpr(SZExtD, SZExtR,
1759                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1760                             Depth + 1);
1761         }
1762       }
1763 
1764       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1765         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1766         return getAddRecExpr(
1767             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1768             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1769       }
1770     }
1771 
1772   // zext(A % B) --> zext(A) % zext(B)
1773   {
1774     const SCEV *LHS;
1775     const SCEV *RHS;
1776     if (matchURem(Op, LHS, RHS))
1777       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1778                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1779   }
1780 
1781   // zext(A / B) --> zext(A) / zext(B).
1782   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1783     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1784                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1785 
1786   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1787     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1788     if (SA->hasNoUnsignedWrap()) {
1789       // If the addition does not unsign overflow then we can, by definition,
1790       // commute the zero extension with the addition operation.
1791       SmallVector<const SCEV *, 4> Ops;
1792       for (const auto *Op : SA->operands())
1793         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1794       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1795     }
1796 
1797     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1798     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1799     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1800     //
1801     // Often address arithmetics contain expressions like
1802     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1803     // This transformation is useful while proving that such expressions are
1804     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1805     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1806       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1807       if (D != 0) {
1808         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1809         const SCEV *SResidual =
1810             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1811         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1812         return getAddExpr(SZExtD, SZExtR,
1813                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1814                           Depth + 1);
1815       }
1816     }
1817   }
1818 
1819   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1820     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1821     if (SM->hasNoUnsignedWrap()) {
1822       // If the multiply does not unsign overflow then we can, by definition,
1823       // commute the zero extension with the multiply operation.
1824       SmallVector<const SCEV *, 4> Ops;
1825       for (const auto *Op : SM->operands())
1826         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1827       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1828     }
1829 
1830     // zext(2^K * (trunc X to iN)) to iM ->
1831     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1832     //
1833     // Proof:
1834     //
1835     //     zext(2^K * (trunc X to iN)) to iM
1836     //   = zext((trunc X to iN) << K) to iM
1837     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1838     //     (because shl removes the top K bits)
1839     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1840     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1841     //
1842     if (SM->getNumOperands() == 2)
1843       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1844         if (MulLHS->getAPInt().isPowerOf2())
1845           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1846             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1847                                MulLHS->getAPInt().logBase2();
1848             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1849             return getMulExpr(
1850                 getZeroExtendExpr(MulLHS, Ty),
1851                 getZeroExtendExpr(
1852                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1853                 SCEV::FlagNUW, Depth + 1);
1854           }
1855   }
1856 
1857   // The cast wasn't folded; create an explicit cast node.
1858   // Recompute the insert position, as it may have been invalidated.
1859   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1860   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1861                                                    Op, Ty);
1862   UniqueSCEVs.InsertNode(S, IP);
1863   addToLoopUseLists(S);
1864   return S;
1865 }
1866 
1867 const SCEV *
1868 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1869   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1870          "This is not an extending conversion!");
1871   assert(isSCEVable(Ty) &&
1872          "This is not a conversion to a SCEVable type!");
1873   Ty = getEffectiveSCEVType(Ty);
1874 
1875   // Fold if the operand is constant.
1876   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1877     return getConstant(
1878       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1879 
1880   // sext(sext(x)) --> sext(x)
1881   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1882     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1883 
1884   // sext(zext(x)) --> zext(x)
1885   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1886     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1887 
1888   // Before doing any expensive analysis, check to see if we've already
1889   // computed a SCEV for this Op and Ty.
1890   FoldingSetNodeID ID;
1891   ID.AddInteger(scSignExtend);
1892   ID.AddPointer(Op);
1893   ID.AddPointer(Ty);
1894   void *IP = nullptr;
1895   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1896   // Limit recursion depth.
1897   if (Depth > MaxCastDepth) {
1898     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1899                                                      Op, Ty);
1900     UniqueSCEVs.InsertNode(S, IP);
1901     addToLoopUseLists(S);
1902     return S;
1903   }
1904 
1905   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1906   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1907     // It's possible the bits taken off by the truncate were all sign bits. If
1908     // so, we should be able to simplify this further.
1909     const SCEV *X = ST->getOperand();
1910     ConstantRange CR = getSignedRange(X);
1911     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1912     unsigned NewBits = getTypeSizeInBits(Ty);
1913     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1914             CR.sextOrTrunc(NewBits)))
1915       return getTruncateOrSignExtend(X, Ty, Depth);
1916   }
1917 
1918   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1919     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1920     if (SA->hasNoSignedWrap()) {
1921       // If the addition does not sign overflow then we can, by definition,
1922       // commute the sign extension with the addition operation.
1923       SmallVector<const SCEV *, 4> Ops;
1924       for (const auto *Op : SA->operands())
1925         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1926       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1927     }
1928 
1929     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1930     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1931     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1932     //
1933     // For instance, this will bring two seemingly different expressions:
1934     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1935     //         sext(6 + 20 * %x + 24 * %y)
1936     // to the same form:
1937     //     2 + sext(4 + 20 * %x + 24 * %y)
1938     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1939       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1940       if (D != 0) {
1941         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1942         const SCEV *SResidual =
1943             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1944         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1945         return getAddExpr(SSExtD, SSExtR,
1946                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1947                           Depth + 1);
1948       }
1949     }
1950   }
1951   // If the input value is a chrec scev, and we can prove that the value
1952   // did not overflow the old, smaller, value, we can sign extend all of the
1953   // operands (often constants).  This allows analysis of something like
1954   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1955   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1956     if (AR->isAffine()) {
1957       const SCEV *Start = AR->getStart();
1958       const SCEV *Step = AR->getStepRecurrence(*this);
1959       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1960       const Loop *L = AR->getLoop();
1961 
1962       if (!AR->hasNoSignedWrap()) {
1963         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1964         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1965       }
1966 
1967       // If we have special knowledge that this addrec won't overflow,
1968       // we don't need to do any further analysis.
1969       if (AR->hasNoSignedWrap())
1970         return getAddRecExpr(
1971             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1972             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1973 
1974       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1975       // Note that this serves two purposes: It filters out loops that are
1976       // simply not analyzable, and it covers the case where this code is
1977       // being called from within backedge-taken count analysis, such that
1978       // attempting to ask for the backedge-taken count would likely result
1979       // in infinite recursion. In the later case, the analysis code will
1980       // cope with a conservative value, and it will take care to purge
1981       // that value once it has finished.
1982       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1983       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1984         // Manually compute the final value for AR, checking for
1985         // overflow.
1986 
1987         // Check whether the backedge-taken count can be losslessly casted to
1988         // the addrec's type. The count is always unsigned.
1989         const SCEV *CastedMaxBECount =
1990             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1991         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1992             CastedMaxBECount, MaxBECount->getType(), Depth);
1993         if (MaxBECount == RecastedMaxBECount) {
1994           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1995           // Check whether Start+Step*MaxBECount has no signed overflow.
1996           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1997                                         SCEV::FlagAnyWrap, Depth + 1);
1998           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1999                                                           SCEV::FlagAnyWrap,
2000                                                           Depth + 1),
2001                                                WideTy, Depth + 1);
2002           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2003           const SCEV *WideMaxBECount =
2004             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2005           const SCEV *OperandExtendedAdd =
2006             getAddExpr(WideStart,
2007                        getMulExpr(WideMaxBECount,
2008                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2009                                   SCEV::FlagAnyWrap, Depth + 1),
2010                        SCEV::FlagAnyWrap, Depth + 1);
2011           if (SAdd == OperandExtendedAdd) {
2012             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2013             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2014             // Return the expression with the addrec on the outside.
2015             return getAddRecExpr(
2016                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2017                                                          Depth + 1),
2018                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2019                 AR->getNoWrapFlags());
2020           }
2021           // Similar to above, only this time treat the step value as unsigned.
2022           // This covers loops that count up with an unsigned step.
2023           OperandExtendedAdd =
2024             getAddExpr(WideStart,
2025                        getMulExpr(WideMaxBECount,
2026                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2027                                   SCEV::FlagAnyWrap, Depth + 1),
2028                        SCEV::FlagAnyWrap, Depth + 1);
2029           if (SAdd == OperandExtendedAdd) {
2030             // If AR wraps around then
2031             //
2032             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2033             // => SAdd != OperandExtendedAdd
2034             //
2035             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2036             // (SAdd == OperandExtendedAdd => AR is NW)
2037 
2038             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2039 
2040             // Return the expression with the addrec on the outside.
2041             return getAddRecExpr(
2042                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2043                                                          Depth + 1),
2044                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2045                 AR->getNoWrapFlags());
2046           }
2047         }
2048       }
2049 
2050       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2051       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2052       if (AR->hasNoSignedWrap()) {
2053         // Same as nsw case above - duplicated here to avoid a compile time
2054         // issue.  It's not clear that the order of checks does matter, but
2055         // it's one of two issue possible causes for a change which was
2056         // reverted.  Be conservative for the moment.
2057         return getAddRecExpr(
2058             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2059             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2060       }
2061 
2062       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2063       // if D + (C - D + Step * n) could be proven to not signed wrap
2064       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2065       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2066         const APInt &C = SC->getAPInt();
2067         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2068         if (D != 0) {
2069           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2070           const SCEV *SResidual =
2071               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2072           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2073           return getAddExpr(SSExtD, SSExtR,
2074                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2075                             Depth + 1);
2076         }
2077       }
2078 
2079       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2080         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2081         return getAddRecExpr(
2082             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2083             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2084       }
2085     }
2086 
2087   // If the input value is provably positive and we could not simplify
2088   // away the sext build a zext instead.
2089   if (isKnownNonNegative(Op))
2090     return getZeroExtendExpr(Op, Ty, Depth + 1);
2091 
2092   // The cast wasn't folded; create an explicit cast node.
2093   // Recompute the insert position, as it may have been invalidated.
2094   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2095   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2096                                                    Op, Ty);
2097   UniqueSCEVs.InsertNode(S, IP);
2098   addToLoopUseLists(S);
2099   return S;
2100 }
2101 
2102 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2103 /// unspecified bits out to the given type.
2104 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2105                                               Type *Ty) {
2106   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2107          "This is not an extending conversion!");
2108   assert(isSCEVable(Ty) &&
2109          "This is not a conversion to a SCEVable type!");
2110   Ty = getEffectiveSCEVType(Ty);
2111 
2112   // Sign-extend negative constants.
2113   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2114     if (SC->getAPInt().isNegative())
2115       return getSignExtendExpr(Op, Ty);
2116 
2117   // Peel off a truncate cast.
2118   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2119     const SCEV *NewOp = T->getOperand();
2120     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2121       return getAnyExtendExpr(NewOp, Ty);
2122     return getTruncateOrNoop(NewOp, Ty);
2123   }
2124 
2125   // Next try a zext cast. If the cast is folded, use it.
2126   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2127   if (!isa<SCEVZeroExtendExpr>(ZExt))
2128     return ZExt;
2129 
2130   // Next try a sext cast. If the cast is folded, use it.
2131   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2132   if (!isa<SCEVSignExtendExpr>(SExt))
2133     return SExt;
2134 
2135   // Force the cast to be folded into the operands of an addrec.
2136   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2137     SmallVector<const SCEV *, 4> Ops;
2138     for (const SCEV *Op : AR->operands())
2139       Ops.push_back(getAnyExtendExpr(Op, Ty));
2140     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2141   }
2142 
2143   // If the expression is obviously signed, use the sext cast value.
2144   if (isa<SCEVSMaxExpr>(Op))
2145     return SExt;
2146 
2147   // Absent any other information, use the zext cast value.
2148   return ZExt;
2149 }
2150 
2151 /// Process the given Ops list, which is a list of operands to be added under
2152 /// the given scale, update the given map. This is a helper function for
2153 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2154 /// that would form an add expression like this:
2155 ///
2156 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2157 ///
2158 /// where A and B are constants, update the map with these values:
2159 ///
2160 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2161 ///
2162 /// and add 13 + A*B*29 to AccumulatedConstant.
2163 /// This will allow getAddRecExpr to produce this:
2164 ///
2165 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2166 ///
2167 /// This form often exposes folding opportunities that are hidden in
2168 /// the original operand list.
2169 ///
2170 /// Return true iff it appears that any interesting folding opportunities
2171 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2172 /// the common case where no interesting opportunities are present, and
2173 /// is also used as a check to avoid infinite recursion.
2174 static bool
2175 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2176                              SmallVectorImpl<const SCEV *> &NewOps,
2177                              APInt &AccumulatedConstant,
2178                              const SCEV *const *Ops, size_t NumOperands,
2179                              const APInt &Scale,
2180                              ScalarEvolution &SE) {
2181   bool Interesting = false;
2182 
2183   // Iterate over the add operands. They are sorted, with constants first.
2184   unsigned i = 0;
2185   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2186     ++i;
2187     // Pull a buried constant out to the outside.
2188     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2189       Interesting = true;
2190     AccumulatedConstant += Scale * C->getAPInt();
2191   }
2192 
2193   // Next comes everything else. We're especially interested in multiplies
2194   // here, but they're in the middle, so just visit the rest with one loop.
2195   for (; i != NumOperands; ++i) {
2196     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2197     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2198       APInt NewScale =
2199           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2200       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2201         // A multiplication of a constant with another add; recurse.
2202         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2203         Interesting |=
2204           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2205                                        Add->op_begin(), Add->getNumOperands(),
2206                                        NewScale, SE);
2207       } else {
2208         // A multiplication of a constant with some other value. Update
2209         // the map.
2210         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2211         const SCEV *Key = SE.getMulExpr(MulOps);
2212         auto Pair = M.insert({Key, NewScale});
2213         if (Pair.second) {
2214           NewOps.push_back(Pair.first->first);
2215         } else {
2216           Pair.first->second += NewScale;
2217           // The map already had an entry for this value, which may indicate
2218           // a folding opportunity.
2219           Interesting = true;
2220         }
2221       }
2222     } else {
2223       // An ordinary operand. Update the map.
2224       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2225           M.insert({Ops[i], Scale});
2226       if (Pair.second) {
2227         NewOps.push_back(Pair.first->first);
2228       } else {
2229         Pair.first->second += Scale;
2230         // The map already had an entry for this value, which may indicate
2231         // a folding opportunity.
2232         Interesting = true;
2233       }
2234     }
2235   }
2236 
2237   return Interesting;
2238 }
2239 
2240 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2241 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2242 // can't-overflow flags for the operation if possible.
2243 static SCEV::NoWrapFlags
2244 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2245                       const ArrayRef<const SCEV *> Ops,
2246                       SCEV::NoWrapFlags Flags) {
2247   using namespace std::placeholders;
2248 
2249   using OBO = OverflowingBinaryOperator;
2250 
2251   bool CanAnalyze =
2252       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2253   (void)CanAnalyze;
2254   assert(CanAnalyze && "don't call from other places!");
2255 
2256   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2257   SCEV::NoWrapFlags SignOrUnsignWrap =
2258       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2259 
2260   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2261   auto IsKnownNonNegative = [&](const SCEV *S) {
2262     return SE->isKnownNonNegative(S);
2263   };
2264 
2265   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2266     Flags =
2267         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2268 
2269   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2270 
2271   if (SignOrUnsignWrap != SignOrUnsignMask &&
2272       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2273       isa<SCEVConstant>(Ops[0])) {
2274 
2275     auto Opcode = [&] {
2276       switch (Type) {
2277       case scAddExpr:
2278         return Instruction::Add;
2279       case scMulExpr:
2280         return Instruction::Mul;
2281       default:
2282         llvm_unreachable("Unexpected SCEV op.");
2283       }
2284     }();
2285 
2286     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2287 
2288     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2289     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2290       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2291           Opcode, C, OBO::NoSignedWrap);
2292       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2293         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2294     }
2295 
2296     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2297     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2298       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2299           Opcode, C, OBO::NoUnsignedWrap);
2300       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2301         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2302     }
2303   }
2304 
2305   return Flags;
2306 }
2307 
2308 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2309   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2310 }
2311 
2312 /// Get a canonical add expression, or something simpler if possible.
2313 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2314                                         SCEV::NoWrapFlags OrigFlags,
2315                                         unsigned Depth) {
2316   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2317          "only nuw or nsw allowed");
2318   assert(!Ops.empty() && "Cannot get empty add!");
2319   if (Ops.size() == 1) return Ops[0];
2320 #ifndef NDEBUG
2321   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2322   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2323     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2324            "SCEVAddExpr operand types don't match!");
2325 #endif
2326 
2327   // Sort by complexity, this groups all similar expression types together.
2328   GroupByComplexity(Ops, &LI, DT);
2329 
2330   // If there are any constants, fold them together.
2331   unsigned Idx = 0;
2332   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2333     ++Idx;
2334     assert(Idx < Ops.size());
2335     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2336       // We found two constants, fold them together!
2337       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2338       if (Ops.size() == 2) return Ops[0];
2339       Ops.erase(Ops.begin()+1);  // Erase the folded element
2340       LHSC = cast<SCEVConstant>(Ops[0]);
2341     }
2342 
2343     // If we are left with a constant zero being added, strip it off.
2344     if (LHSC->getValue()->isZero()) {
2345       Ops.erase(Ops.begin());
2346       --Idx;
2347     }
2348 
2349     if (Ops.size() == 1) return Ops[0];
2350   }
2351 
2352   // Delay expensive flag strengthening until necessary.
2353   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2354     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2355   };
2356 
2357   // Limit recursion calls depth.
2358   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2359     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2360 
2361   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2362     // Don't strengthen flags if we have no new information.
2363     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2364     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2365       Add->setNoWrapFlags(ComputeFlags(Ops));
2366     return S;
2367   }
2368 
2369   // Okay, check to see if the same value occurs in the operand list more than
2370   // once.  If so, merge them together into an multiply expression.  Since we
2371   // sorted the list, these values are required to be adjacent.
2372   Type *Ty = Ops[0]->getType();
2373   bool FoundMatch = false;
2374   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2375     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2376       // Scan ahead to count how many equal operands there are.
2377       unsigned Count = 2;
2378       while (i+Count != e && Ops[i+Count] == Ops[i])
2379         ++Count;
2380       // Merge the values into a multiply.
2381       const SCEV *Scale = getConstant(Ty, Count);
2382       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2383       if (Ops.size() == Count)
2384         return Mul;
2385       Ops[i] = Mul;
2386       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2387       --i; e -= Count - 1;
2388       FoundMatch = true;
2389     }
2390   if (FoundMatch)
2391     return getAddExpr(Ops, OrigFlags, Depth + 1);
2392 
2393   // Check for truncates. If all the operands are truncated from the same
2394   // type, see if factoring out the truncate would permit the result to be
2395   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2396   // if the contents of the resulting outer trunc fold to something simple.
2397   auto FindTruncSrcType = [&]() -> Type * {
2398     // We're ultimately looking to fold an addrec of truncs and muls of only
2399     // constants and truncs, so if we find any other types of SCEV
2400     // as operands of the addrec then we bail and return nullptr here.
2401     // Otherwise, we return the type of the operand of a trunc that we find.
2402     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2403       return T->getOperand()->getType();
2404     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2405       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2406       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2407         return T->getOperand()->getType();
2408     }
2409     return nullptr;
2410   };
2411   if (auto *SrcType = FindTruncSrcType()) {
2412     SmallVector<const SCEV *, 8> LargeOps;
2413     bool Ok = true;
2414     // Check all the operands to see if they can be represented in the
2415     // source type of the truncate.
2416     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2417       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2418         if (T->getOperand()->getType() != SrcType) {
2419           Ok = false;
2420           break;
2421         }
2422         LargeOps.push_back(T->getOperand());
2423       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2424         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2425       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2426         SmallVector<const SCEV *, 8> LargeMulOps;
2427         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2428           if (const SCEVTruncateExpr *T =
2429                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2430             if (T->getOperand()->getType() != SrcType) {
2431               Ok = false;
2432               break;
2433             }
2434             LargeMulOps.push_back(T->getOperand());
2435           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2436             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2437           } else {
2438             Ok = false;
2439             break;
2440           }
2441         }
2442         if (Ok)
2443           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2444       } else {
2445         Ok = false;
2446         break;
2447       }
2448     }
2449     if (Ok) {
2450       // Evaluate the expression in the larger type.
2451       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2452       // If it folds to something simple, use it. Otherwise, don't.
2453       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2454         return getTruncateExpr(Fold, Ty);
2455     }
2456   }
2457 
2458   // Skip past any other cast SCEVs.
2459   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2460     ++Idx;
2461 
2462   // If there are add operands they would be next.
2463   if (Idx < Ops.size()) {
2464     bool DeletedAdd = false;
2465     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2466       if (Ops.size() > AddOpsInlineThreshold ||
2467           Add->getNumOperands() > AddOpsInlineThreshold)
2468         break;
2469       // If we have an add, expand the add operands onto the end of the operands
2470       // list.
2471       Ops.erase(Ops.begin()+Idx);
2472       Ops.append(Add->op_begin(), Add->op_end());
2473       DeletedAdd = true;
2474     }
2475 
2476     // If we deleted at least one add, we added operands to the end of the list,
2477     // and they are not necessarily sorted.  Recurse to resort and resimplify
2478     // any operands we just acquired.
2479     if (DeletedAdd)
2480       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2481   }
2482 
2483   // Skip over the add expression until we get to a multiply.
2484   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2485     ++Idx;
2486 
2487   // Check to see if there are any folding opportunities present with
2488   // operands multiplied by constant values.
2489   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2490     uint64_t BitWidth = getTypeSizeInBits(Ty);
2491     DenseMap<const SCEV *, APInt> M;
2492     SmallVector<const SCEV *, 8> NewOps;
2493     APInt AccumulatedConstant(BitWidth, 0);
2494     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2495                                      Ops.data(), Ops.size(),
2496                                      APInt(BitWidth, 1), *this)) {
2497       struct APIntCompare {
2498         bool operator()(const APInt &LHS, const APInt &RHS) const {
2499           return LHS.ult(RHS);
2500         }
2501       };
2502 
2503       // Some interesting folding opportunity is present, so its worthwhile to
2504       // re-generate the operands list. Group the operands by constant scale,
2505       // to avoid multiplying by the same constant scale multiple times.
2506       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2507       for (const SCEV *NewOp : NewOps)
2508         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2509       // Re-generate the operands list.
2510       Ops.clear();
2511       if (AccumulatedConstant != 0)
2512         Ops.push_back(getConstant(AccumulatedConstant));
2513       for (auto &MulOp : MulOpLists)
2514         if (MulOp.first != 0)
2515           Ops.push_back(getMulExpr(
2516               getConstant(MulOp.first),
2517               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2518               SCEV::FlagAnyWrap, Depth + 1));
2519       if (Ops.empty())
2520         return getZero(Ty);
2521       if (Ops.size() == 1)
2522         return Ops[0];
2523       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2524     }
2525   }
2526 
2527   // If we are adding something to a multiply expression, make sure the
2528   // something is not already an operand of the multiply.  If so, merge it into
2529   // the multiply.
2530   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2531     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2532     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2533       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2534       if (isa<SCEVConstant>(MulOpSCEV))
2535         continue;
2536       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2537         if (MulOpSCEV == Ops[AddOp]) {
2538           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2539           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2540           if (Mul->getNumOperands() != 2) {
2541             // If the multiply has more than two operands, we must get the
2542             // Y*Z term.
2543             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2544                                                 Mul->op_begin()+MulOp);
2545             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2546             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2547           }
2548           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2549           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2550           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2551                                             SCEV::FlagAnyWrap, Depth + 1);
2552           if (Ops.size() == 2) return OuterMul;
2553           if (AddOp < Idx) {
2554             Ops.erase(Ops.begin()+AddOp);
2555             Ops.erase(Ops.begin()+Idx-1);
2556           } else {
2557             Ops.erase(Ops.begin()+Idx);
2558             Ops.erase(Ops.begin()+AddOp-1);
2559           }
2560           Ops.push_back(OuterMul);
2561           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2562         }
2563 
2564       // Check this multiply against other multiplies being added together.
2565       for (unsigned OtherMulIdx = Idx+1;
2566            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2567            ++OtherMulIdx) {
2568         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2569         // If MulOp occurs in OtherMul, we can fold the two multiplies
2570         // together.
2571         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2572              OMulOp != e; ++OMulOp)
2573           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2574             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2575             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2576             if (Mul->getNumOperands() != 2) {
2577               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2578                                                   Mul->op_begin()+MulOp);
2579               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2580               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2581             }
2582             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2583             if (OtherMul->getNumOperands() != 2) {
2584               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2585                                                   OtherMul->op_begin()+OMulOp);
2586               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2587               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2588             }
2589             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2590             const SCEV *InnerMulSum =
2591                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2592             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2593                                               SCEV::FlagAnyWrap, Depth + 1);
2594             if (Ops.size() == 2) return OuterMul;
2595             Ops.erase(Ops.begin()+Idx);
2596             Ops.erase(Ops.begin()+OtherMulIdx-1);
2597             Ops.push_back(OuterMul);
2598             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2599           }
2600       }
2601     }
2602   }
2603 
2604   // If there are any add recurrences in the operands list, see if any other
2605   // added values are loop invariant.  If so, we can fold them into the
2606   // recurrence.
2607   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2608     ++Idx;
2609 
2610   // Scan over all recurrences, trying to fold loop invariants into them.
2611   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2612     // Scan all of the other operands to this add and add them to the vector if
2613     // they are loop invariant w.r.t. the recurrence.
2614     SmallVector<const SCEV *, 8> LIOps;
2615     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2616     const Loop *AddRecLoop = AddRec->getLoop();
2617     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2618       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2619         LIOps.push_back(Ops[i]);
2620         Ops.erase(Ops.begin()+i);
2621         --i; --e;
2622       }
2623 
2624     // If we found some loop invariants, fold them into the recurrence.
2625     if (!LIOps.empty()) {
2626       // Compute nowrap flags for the addition of the loop-invariant ops and
2627       // the addrec. Temporarily push it as an operand for that purpose.
2628       LIOps.push_back(AddRec);
2629       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2630       LIOps.pop_back();
2631 
2632       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2633       LIOps.push_back(AddRec->getStart());
2634 
2635       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2636       // This follows from the fact that the no-wrap flags on the outer add
2637       // expression are applicable on the 0th iteration, when the add recurrence
2638       // will be equal to its start value.
2639       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2640 
2641       // Build the new addrec. Propagate the NUW and NSW flags if both the
2642       // outer add and the inner addrec are guaranteed to have no overflow.
2643       // Always propagate NW.
2644       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2645       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2646 
2647       // If all of the other operands were loop invariant, we are done.
2648       if (Ops.size() == 1) return NewRec;
2649 
2650       // Otherwise, add the folded AddRec by the non-invariant parts.
2651       for (unsigned i = 0;; ++i)
2652         if (Ops[i] == AddRec) {
2653           Ops[i] = NewRec;
2654           break;
2655         }
2656       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2657     }
2658 
2659     // Okay, if there weren't any loop invariants to be folded, check to see if
2660     // there are multiple AddRec's with the same loop induction variable being
2661     // added together.  If so, we can fold them.
2662     for (unsigned OtherIdx = Idx+1;
2663          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2664          ++OtherIdx) {
2665       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2666       // so that the 1st found AddRecExpr is dominated by all others.
2667       assert(DT.dominates(
2668            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2669            AddRec->getLoop()->getHeader()) &&
2670         "AddRecExprs are not sorted in reverse dominance order?");
2671       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2672         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2673         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2674         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2675              ++OtherIdx) {
2676           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2677           if (OtherAddRec->getLoop() == AddRecLoop) {
2678             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2679                  i != e; ++i) {
2680               if (i >= AddRecOps.size()) {
2681                 AddRecOps.append(OtherAddRec->op_begin()+i,
2682                                  OtherAddRec->op_end());
2683                 break;
2684               }
2685               SmallVector<const SCEV *, 2> TwoOps = {
2686                   AddRecOps[i], OtherAddRec->getOperand(i)};
2687               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2688             }
2689             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2690           }
2691         }
2692         // Step size has changed, so we cannot guarantee no self-wraparound.
2693         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2694         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2695       }
2696     }
2697 
2698     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2699     // next one.
2700   }
2701 
2702   // Okay, it looks like we really DO need an add expr.  Check to see if we
2703   // already have one, otherwise create a new one.
2704   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2705 }
2706 
2707 const SCEV *
2708 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2709                                     SCEV::NoWrapFlags Flags) {
2710   FoldingSetNodeID ID;
2711   ID.AddInteger(scAddExpr);
2712   for (const SCEV *Op : Ops)
2713     ID.AddPointer(Op);
2714   void *IP = nullptr;
2715   SCEVAddExpr *S =
2716       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2717   if (!S) {
2718     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2719     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2720     S = new (SCEVAllocator)
2721         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2722     UniqueSCEVs.InsertNode(S, IP);
2723     addToLoopUseLists(S);
2724   }
2725   S->setNoWrapFlags(Flags);
2726   return S;
2727 }
2728 
2729 const SCEV *
2730 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2731                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2732   FoldingSetNodeID ID;
2733   ID.AddInteger(scAddRecExpr);
2734   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2735     ID.AddPointer(Ops[i]);
2736   ID.AddPointer(L);
2737   void *IP = nullptr;
2738   SCEVAddRecExpr *S =
2739       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2740   if (!S) {
2741     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2742     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2743     S = new (SCEVAllocator)
2744         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2745     UniqueSCEVs.InsertNode(S, IP);
2746     addToLoopUseLists(S);
2747   }
2748   setNoWrapFlags(S, Flags);
2749   return S;
2750 }
2751 
2752 const SCEV *
2753 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2754                                     SCEV::NoWrapFlags Flags) {
2755   FoldingSetNodeID ID;
2756   ID.AddInteger(scMulExpr);
2757   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2758     ID.AddPointer(Ops[i]);
2759   void *IP = nullptr;
2760   SCEVMulExpr *S =
2761     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2762   if (!S) {
2763     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2764     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2765     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2766                                         O, Ops.size());
2767     UniqueSCEVs.InsertNode(S, IP);
2768     addToLoopUseLists(S);
2769   }
2770   S->setNoWrapFlags(Flags);
2771   return S;
2772 }
2773 
2774 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2775   uint64_t k = i*j;
2776   if (j > 1 && k / j != i) Overflow = true;
2777   return k;
2778 }
2779 
2780 /// Compute the result of "n choose k", the binomial coefficient.  If an
2781 /// intermediate computation overflows, Overflow will be set and the return will
2782 /// be garbage. Overflow is not cleared on absence of overflow.
2783 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2784   // We use the multiplicative formula:
2785   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2786   // At each iteration, we take the n-th term of the numeral and divide by the
2787   // (k-n)th term of the denominator.  This division will always produce an
2788   // integral result, and helps reduce the chance of overflow in the
2789   // intermediate computations. However, we can still overflow even when the
2790   // final result would fit.
2791 
2792   if (n == 0 || n == k) return 1;
2793   if (k > n) return 0;
2794 
2795   if (k > n/2)
2796     k = n-k;
2797 
2798   uint64_t r = 1;
2799   for (uint64_t i = 1; i <= k; ++i) {
2800     r = umul_ov(r, n-(i-1), Overflow);
2801     r /= i;
2802   }
2803   return r;
2804 }
2805 
2806 /// Determine if any of the operands in this SCEV are a constant or if
2807 /// any of the add or multiply expressions in this SCEV contain a constant.
2808 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2809   struct FindConstantInAddMulChain {
2810     bool FoundConstant = false;
2811 
2812     bool follow(const SCEV *S) {
2813       FoundConstant |= isa<SCEVConstant>(S);
2814       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2815     }
2816 
2817     bool isDone() const {
2818       return FoundConstant;
2819     }
2820   };
2821 
2822   FindConstantInAddMulChain F;
2823   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2824   ST.visitAll(StartExpr);
2825   return F.FoundConstant;
2826 }
2827 
2828 /// Get a canonical multiply expression, or something simpler if possible.
2829 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2830                                         SCEV::NoWrapFlags OrigFlags,
2831                                         unsigned Depth) {
2832   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2833          "only nuw or nsw allowed");
2834   assert(!Ops.empty() && "Cannot get empty mul!");
2835   if (Ops.size() == 1) return Ops[0];
2836 #ifndef NDEBUG
2837   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2838   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2839     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2840            "SCEVMulExpr operand types don't match!");
2841 #endif
2842 
2843   // Sort by complexity, this groups all similar expression types together.
2844   GroupByComplexity(Ops, &LI, DT);
2845 
2846   // If there are any constants, fold them together.
2847   unsigned Idx = 0;
2848   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2849     ++Idx;
2850     assert(Idx < Ops.size());
2851     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2852       // We found two constants, fold them together!
2853       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2854       if (Ops.size() == 2) return Ops[0];
2855       Ops.erase(Ops.begin()+1);  // Erase the folded element
2856       LHSC = cast<SCEVConstant>(Ops[0]);
2857     }
2858 
2859     // If we have a multiply of zero, it will always be zero.
2860     if (LHSC->getValue()->isZero())
2861       return LHSC;
2862 
2863     // If we are left with a constant one being multiplied, strip it off.
2864     if (LHSC->getValue()->isOne()) {
2865       Ops.erase(Ops.begin());
2866       --Idx;
2867     }
2868 
2869     if (Ops.size() == 1)
2870       return Ops[0];
2871   }
2872 
2873   // Delay expensive flag strengthening until necessary.
2874   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2875     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2876   };
2877 
2878   // Limit recursion calls depth.
2879   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2880     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2881 
2882   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2883     // Don't strengthen flags if we have no new information.
2884     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2885     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2886       Mul->setNoWrapFlags(ComputeFlags(Ops));
2887     return S;
2888   }
2889 
2890   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2891     if (Ops.size() == 2) {
2892       // C1*(C2+V) -> C1*C2 + C1*V
2893       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2894         // If any of Add's ops are Adds or Muls with a constant, apply this
2895         // transformation as well.
2896         //
2897         // TODO: There are some cases where this transformation is not
2898         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2899         // this transformation should be narrowed down.
2900         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2901           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2902                                        SCEV::FlagAnyWrap, Depth + 1),
2903                             getMulExpr(LHSC, Add->getOperand(1),
2904                                        SCEV::FlagAnyWrap, Depth + 1),
2905                             SCEV::FlagAnyWrap, Depth + 1);
2906 
2907       if (Ops[0]->isAllOnesValue()) {
2908         // If we have a mul by -1 of an add, try distributing the -1 among the
2909         // add operands.
2910         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2911           SmallVector<const SCEV *, 4> NewOps;
2912           bool AnyFolded = false;
2913           for (const SCEV *AddOp : Add->operands()) {
2914             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2915                                          Depth + 1);
2916             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2917             NewOps.push_back(Mul);
2918           }
2919           if (AnyFolded)
2920             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2921         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2922           // Negation preserves a recurrence's no self-wrap property.
2923           SmallVector<const SCEV *, 4> Operands;
2924           for (const SCEV *AddRecOp : AddRec->operands())
2925             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2926                                           Depth + 1));
2927 
2928           return getAddRecExpr(Operands, AddRec->getLoop(),
2929                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2930         }
2931       }
2932     }
2933   }
2934 
2935   // Skip over the add expression until we get to a multiply.
2936   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2937     ++Idx;
2938 
2939   // If there are mul operands inline them all into this expression.
2940   if (Idx < Ops.size()) {
2941     bool DeletedMul = false;
2942     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2943       if (Ops.size() > MulOpsInlineThreshold)
2944         break;
2945       // If we have an mul, expand the mul operands onto the end of the
2946       // operands list.
2947       Ops.erase(Ops.begin()+Idx);
2948       Ops.append(Mul->op_begin(), Mul->op_end());
2949       DeletedMul = true;
2950     }
2951 
2952     // If we deleted at least one mul, we added operands to the end of the
2953     // list, and they are not necessarily sorted.  Recurse to resort and
2954     // resimplify any operands we just acquired.
2955     if (DeletedMul)
2956       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2957   }
2958 
2959   // If there are any add recurrences in the operands list, see if any other
2960   // added values are loop invariant.  If so, we can fold them into the
2961   // recurrence.
2962   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2963     ++Idx;
2964 
2965   // Scan over all recurrences, trying to fold loop invariants into them.
2966   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2967     // Scan all of the other operands to this mul and add them to the vector
2968     // if they are loop invariant w.r.t. the recurrence.
2969     SmallVector<const SCEV *, 8> LIOps;
2970     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2971     const Loop *AddRecLoop = AddRec->getLoop();
2972     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2973       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2974         LIOps.push_back(Ops[i]);
2975         Ops.erase(Ops.begin()+i);
2976         --i; --e;
2977       }
2978 
2979     // If we found some loop invariants, fold them into the recurrence.
2980     if (!LIOps.empty()) {
2981       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2982       SmallVector<const SCEV *, 4> NewOps;
2983       NewOps.reserve(AddRec->getNumOperands());
2984       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2985       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2986         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2987                                     SCEV::FlagAnyWrap, Depth + 1));
2988 
2989       // Build the new addrec. Propagate the NUW and NSW flags if both the
2990       // outer mul and the inner addrec are guaranteed to have no overflow.
2991       //
2992       // No self-wrap cannot be guaranteed after changing the step size, but
2993       // will be inferred if either NUW or NSW is true.
2994       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2995       const SCEV *NewRec = getAddRecExpr(
2996           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2997 
2998       // If all of the other operands were loop invariant, we are done.
2999       if (Ops.size() == 1) return NewRec;
3000 
3001       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3002       for (unsigned i = 0;; ++i)
3003         if (Ops[i] == AddRec) {
3004           Ops[i] = NewRec;
3005           break;
3006         }
3007       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3008     }
3009 
3010     // Okay, if there weren't any loop invariants to be folded, check to see
3011     // if there are multiple AddRec's with the same loop induction variable
3012     // being multiplied together.  If so, we can fold them.
3013 
3014     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3015     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3016     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3017     //   ]]],+,...up to x=2n}.
3018     // Note that the arguments to choose() are always integers with values
3019     // known at compile time, never SCEV objects.
3020     //
3021     // The implementation avoids pointless extra computations when the two
3022     // addrec's are of different length (mathematically, it's equivalent to
3023     // an infinite stream of zeros on the right).
3024     bool OpsModified = false;
3025     for (unsigned OtherIdx = Idx+1;
3026          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3027          ++OtherIdx) {
3028       const SCEVAddRecExpr *OtherAddRec =
3029         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3030       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3031         continue;
3032 
3033       // Limit max number of arguments to avoid creation of unreasonably big
3034       // SCEVAddRecs with very complex operands.
3035       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3036           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3037         continue;
3038 
3039       bool Overflow = false;
3040       Type *Ty = AddRec->getType();
3041       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3042       SmallVector<const SCEV*, 7> AddRecOps;
3043       for (int x = 0, xe = AddRec->getNumOperands() +
3044              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3045         SmallVector <const SCEV *, 7> SumOps;
3046         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3047           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3048           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3049                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3050                z < ze && !Overflow; ++z) {
3051             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3052             uint64_t Coeff;
3053             if (LargerThan64Bits)
3054               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3055             else
3056               Coeff = Coeff1*Coeff2;
3057             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3058             const SCEV *Term1 = AddRec->getOperand(y-z);
3059             const SCEV *Term2 = OtherAddRec->getOperand(z);
3060             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3061                                         SCEV::FlagAnyWrap, Depth + 1));
3062           }
3063         }
3064         if (SumOps.empty())
3065           SumOps.push_back(getZero(Ty));
3066         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3067       }
3068       if (!Overflow) {
3069         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3070                                               SCEV::FlagAnyWrap);
3071         if (Ops.size() == 2) return NewAddRec;
3072         Ops[Idx] = NewAddRec;
3073         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3074         OpsModified = true;
3075         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3076         if (!AddRec)
3077           break;
3078       }
3079     }
3080     if (OpsModified)
3081       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3082 
3083     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3084     // next one.
3085   }
3086 
3087   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3088   // already have one, otherwise create a new one.
3089   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3090 }
3091 
3092 /// Represents an unsigned remainder expression based on unsigned division.
3093 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3094                                          const SCEV *RHS) {
3095   assert(getEffectiveSCEVType(LHS->getType()) ==
3096          getEffectiveSCEVType(RHS->getType()) &&
3097          "SCEVURemExpr operand types don't match!");
3098 
3099   // Short-circuit easy cases
3100   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3101     // If constant is one, the result is trivial
3102     if (RHSC->getValue()->isOne())
3103       return getZero(LHS->getType()); // X urem 1 --> 0
3104 
3105     // If constant is a power of two, fold into a zext(trunc(LHS)).
3106     if (RHSC->getAPInt().isPowerOf2()) {
3107       Type *FullTy = LHS->getType();
3108       Type *TruncTy =
3109           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3110       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3111     }
3112   }
3113 
3114   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3115   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3116   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3117   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3118 }
3119 
3120 /// Get a canonical unsigned division expression, or something simpler if
3121 /// possible.
3122 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3123                                          const SCEV *RHS) {
3124   assert(getEffectiveSCEVType(LHS->getType()) ==
3125          getEffectiveSCEVType(RHS->getType()) &&
3126          "SCEVUDivExpr operand types don't match!");
3127 
3128   FoldingSetNodeID ID;
3129   ID.AddInteger(scUDivExpr);
3130   ID.AddPointer(LHS);
3131   ID.AddPointer(RHS);
3132   void *IP = nullptr;
3133   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3134     return S;
3135 
3136   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3137     if (RHSC->getValue()->isOne())
3138       return LHS;                               // X udiv 1 --> x
3139     // If the denominator is zero, the result of the udiv is undefined. Don't
3140     // try to analyze it, because the resolution chosen here may differ from
3141     // the resolution chosen in other parts of the compiler.
3142     if (!RHSC->getValue()->isZero()) {
3143       // Determine if the division can be folded into the operands of
3144       // its operands.
3145       // TODO: Generalize this to non-constants by using known-bits information.
3146       Type *Ty = LHS->getType();
3147       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3148       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3149       // For non-power-of-two values, effectively round the value up to the
3150       // nearest power of two.
3151       if (!RHSC->getAPInt().isPowerOf2())
3152         ++MaxShiftAmt;
3153       IntegerType *ExtTy =
3154         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3155       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3156         if (const SCEVConstant *Step =
3157             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3158           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3159           const APInt &StepInt = Step->getAPInt();
3160           const APInt &DivInt = RHSC->getAPInt();
3161           if (!StepInt.urem(DivInt) &&
3162               getZeroExtendExpr(AR, ExtTy) ==
3163               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3164                             getZeroExtendExpr(Step, ExtTy),
3165                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3166             SmallVector<const SCEV *, 4> Operands;
3167             for (const SCEV *Op : AR->operands())
3168               Operands.push_back(getUDivExpr(Op, RHS));
3169             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3170           }
3171           /// Get a canonical UDivExpr for a recurrence.
3172           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3173           // We can currently only fold X%N if X is constant.
3174           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3175           if (StartC && !DivInt.urem(StepInt) &&
3176               getZeroExtendExpr(AR, ExtTy) ==
3177               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3178                             getZeroExtendExpr(Step, ExtTy),
3179                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3180             const APInt &StartInt = StartC->getAPInt();
3181             const APInt &StartRem = StartInt.urem(StepInt);
3182             if (StartRem != 0) {
3183               const SCEV *NewLHS =
3184                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3185                                 AR->getLoop(), SCEV::FlagNW);
3186               if (LHS != NewLHS) {
3187                 LHS = NewLHS;
3188 
3189                 // Reset the ID to include the new LHS, and check if it is
3190                 // already cached.
3191                 ID.clear();
3192                 ID.AddInteger(scUDivExpr);
3193                 ID.AddPointer(LHS);
3194                 ID.AddPointer(RHS);
3195                 IP = nullptr;
3196                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3197                   return S;
3198               }
3199             }
3200           }
3201         }
3202       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3203       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3204         SmallVector<const SCEV *, 4> Operands;
3205         for (const SCEV *Op : M->operands())
3206           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3207         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3208           // Find an operand that's safely divisible.
3209           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3210             const SCEV *Op = M->getOperand(i);
3211             const SCEV *Div = getUDivExpr(Op, RHSC);
3212             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3213               Operands = SmallVector<const SCEV *, 4>(M->operands());
3214               Operands[i] = Div;
3215               return getMulExpr(Operands);
3216             }
3217           }
3218       }
3219 
3220       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3221       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3222         if (auto *DivisorConstant =
3223                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3224           bool Overflow = false;
3225           APInt NewRHS =
3226               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3227           if (Overflow) {
3228             return getConstant(RHSC->getType(), 0, false);
3229           }
3230           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3231         }
3232       }
3233 
3234       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3235       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3236         SmallVector<const SCEV *, 4> Operands;
3237         for (const SCEV *Op : A->operands())
3238           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3239         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3240           Operands.clear();
3241           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3242             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3243             if (isa<SCEVUDivExpr>(Op) ||
3244                 getMulExpr(Op, RHS) != A->getOperand(i))
3245               break;
3246             Operands.push_back(Op);
3247           }
3248           if (Operands.size() == A->getNumOperands())
3249             return getAddExpr(Operands);
3250         }
3251       }
3252 
3253       // Fold if both operands are constant.
3254       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3255         Constant *LHSCV = LHSC->getValue();
3256         Constant *RHSCV = RHSC->getValue();
3257         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3258                                                                    RHSCV)));
3259       }
3260     }
3261   }
3262 
3263   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3264   // changes). Make sure we get a new one.
3265   IP = nullptr;
3266   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3267   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3268                                              LHS, RHS);
3269   UniqueSCEVs.InsertNode(S, IP);
3270   addToLoopUseLists(S);
3271   return S;
3272 }
3273 
3274 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3275   APInt A = C1->getAPInt().abs();
3276   APInt B = C2->getAPInt().abs();
3277   uint32_t ABW = A.getBitWidth();
3278   uint32_t BBW = B.getBitWidth();
3279 
3280   if (ABW > BBW)
3281     B = B.zext(ABW);
3282   else if (ABW < BBW)
3283     A = A.zext(BBW);
3284 
3285   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3286 }
3287 
3288 /// Get a canonical unsigned division expression, or something simpler if
3289 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3290 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3291 /// it's not exact because the udiv may be clearing bits.
3292 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3293                                               const SCEV *RHS) {
3294   // TODO: we could try to find factors in all sorts of things, but for now we
3295   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3296   // end of this file for inspiration.
3297 
3298   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3299   if (!Mul || !Mul->hasNoUnsignedWrap())
3300     return getUDivExpr(LHS, RHS);
3301 
3302   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3303     // If the mulexpr multiplies by a constant, then that constant must be the
3304     // first element of the mulexpr.
3305     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3306       if (LHSCst == RHSCst) {
3307         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3308         return getMulExpr(Operands);
3309       }
3310 
3311       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3312       // that there's a factor provided by one of the other terms. We need to
3313       // check.
3314       APInt Factor = gcd(LHSCst, RHSCst);
3315       if (!Factor.isIntN(1)) {
3316         LHSCst =
3317             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3318         RHSCst =
3319             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3320         SmallVector<const SCEV *, 2> Operands;
3321         Operands.push_back(LHSCst);
3322         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3323         LHS = getMulExpr(Operands);
3324         RHS = RHSCst;
3325         Mul = dyn_cast<SCEVMulExpr>(LHS);
3326         if (!Mul)
3327           return getUDivExactExpr(LHS, RHS);
3328       }
3329     }
3330   }
3331 
3332   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3333     if (Mul->getOperand(i) == RHS) {
3334       SmallVector<const SCEV *, 2> Operands;
3335       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3336       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3337       return getMulExpr(Operands);
3338     }
3339   }
3340 
3341   return getUDivExpr(LHS, RHS);
3342 }
3343 
3344 /// Get an add recurrence expression for the specified loop.  Simplify the
3345 /// expression as much as possible.
3346 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3347                                            const Loop *L,
3348                                            SCEV::NoWrapFlags Flags) {
3349   SmallVector<const SCEV *, 4> Operands;
3350   Operands.push_back(Start);
3351   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3352     if (StepChrec->getLoop() == L) {
3353       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3354       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3355     }
3356 
3357   Operands.push_back(Step);
3358   return getAddRecExpr(Operands, L, Flags);
3359 }
3360 
3361 /// Get an add recurrence expression for the specified loop.  Simplify the
3362 /// expression as much as possible.
3363 const SCEV *
3364 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3365                                const Loop *L, SCEV::NoWrapFlags Flags) {
3366   if (Operands.size() == 1) return Operands[0];
3367 #ifndef NDEBUG
3368   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3369   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3370     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3371            "SCEVAddRecExpr operand types don't match!");
3372   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3373     assert(isLoopInvariant(Operands[i], L) &&
3374            "SCEVAddRecExpr operand is not loop-invariant!");
3375 #endif
3376 
3377   if (Operands.back()->isZero()) {
3378     Operands.pop_back();
3379     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3380   }
3381 
3382   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3383   // use that information to infer NUW and NSW flags. However, computing a
3384   // BE count requires calling getAddRecExpr, so we may not yet have a
3385   // meaningful BE count at this point (and if we don't, we'd be stuck
3386   // with a SCEVCouldNotCompute as the cached BE count).
3387 
3388   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3389 
3390   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3391   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3392     const Loop *NestedLoop = NestedAR->getLoop();
3393     if (L->contains(NestedLoop)
3394             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3395             : (!NestedLoop->contains(L) &&
3396                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3397       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3398       Operands[0] = NestedAR->getStart();
3399       // AddRecs require their operands be loop-invariant with respect to their
3400       // loops. Don't perform this transformation if it would break this
3401       // requirement.
3402       bool AllInvariant = all_of(
3403           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3404 
3405       if (AllInvariant) {
3406         // Create a recurrence for the outer loop with the same step size.
3407         //
3408         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3409         // inner recurrence has the same property.
3410         SCEV::NoWrapFlags OuterFlags =
3411           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3412 
3413         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3414         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3415           return isLoopInvariant(Op, NestedLoop);
3416         });
3417 
3418         if (AllInvariant) {
3419           // Ok, both add recurrences are valid after the transformation.
3420           //
3421           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3422           // the outer recurrence has the same property.
3423           SCEV::NoWrapFlags InnerFlags =
3424             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3425           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3426         }
3427       }
3428       // Reset Operands to its original state.
3429       Operands[0] = NestedAR;
3430     }
3431   }
3432 
3433   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3434   // already have one, otherwise create a new one.
3435   return getOrCreateAddRecExpr(Operands, L, Flags);
3436 }
3437 
3438 const SCEV *
3439 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3440                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3441   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3442   // getSCEV(Base)->getType() has the same address space as Base->getType()
3443   // because SCEV::getType() preserves the address space.
3444   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3445   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3446   // instruction to its SCEV, because the Instruction may be guarded by control
3447   // flow and the no-overflow bits may not be valid for the expression in any
3448   // context. This can be fixed similarly to how these flags are handled for
3449   // adds.
3450   SCEV::NoWrapFlags OffsetWrap =
3451       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3452 
3453   Type *CurTy = GEP->getType();
3454   bool FirstIter = true;
3455   SmallVector<const SCEV *, 4> Offsets;
3456   for (const SCEV *IndexExpr : IndexExprs) {
3457     // Compute the (potentially symbolic) offset in bytes for this index.
3458     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3459       // For a struct, add the member offset.
3460       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3461       unsigned FieldNo = Index->getZExtValue();
3462       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3463       Offsets.push_back(FieldOffset);
3464 
3465       // Update CurTy to the type of the field at Index.
3466       CurTy = STy->getTypeAtIndex(Index);
3467     } else {
3468       // Update CurTy to its element type.
3469       if (FirstIter) {
3470         assert(isa<PointerType>(CurTy) &&
3471                "The first index of a GEP indexes a pointer");
3472         CurTy = GEP->getSourceElementType();
3473         FirstIter = false;
3474       } else {
3475         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3476       }
3477       // For an array, add the element offset, explicitly scaled.
3478       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3479       // Getelementptr indices are signed.
3480       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3481 
3482       // Multiply the index by the element size to compute the element offset.
3483       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3484       Offsets.push_back(LocalOffset);
3485     }
3486   }
3487 
3488   // Handle degenerate case of GEP without offsets.
3489   if (Offsets.empty())
3490     return BaseExpr;
3491 
3492   // Add the offsets together, assuming nsw if inbounds.
3493   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3494   // Add the base address and the offset. We cannot use the nsw flag, as the
3495   // base address is unsigned. However, if we know that the offset is
3496   // non-negative, we can use nuw.
3497   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3498                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3499   return getAddExpr(BaseExpr, Offset, BaseWrap);
3500 }
3501 
3502 std::tuple<SCEV *, FoldingSetNodeID, void *>
3503 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3504                                          ArrayRef<const SCEV *> Ops) {
3505   FoldingSetNodeID ID;
3506   void *IP = nullptr;
3507   ID.AddInteger(SCEVType);
3508   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3509     ID.AddPointer(Ops[i]);
3510   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3511       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3512 }
3513 
3514 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3515   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3516   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3517 }
3518 
3519 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3520                                            SmallVectorImpl<const SCEV *> &Ops) {
3521   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3522   if (Ops.size() == 1) return Ops[0];
3523 #ifndef NDEBUG
3524   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3525   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3526     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3527            "Operand types don't match!");
3528 #endif
3529 
3530   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3531   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3532 
3533   // Sort by complexity, this groups all similar expression types together.
3534   GroupByComplexity(Ops, &LI, DT);
3535 
3536   // Check if we have created the same expression before.
3537   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3538     return S;
3539   }
3540 
3541   // If there are any constants, fold them together.
3542   unsigned Idx = 0;
3543   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3544     ++Idx;
3545     assert(Idx < Ops.size());
3546     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3547       if (Kind == scSMaxExpr)
3548         return APIntOps::smax(LHS, RHS);
3549       else if (Kind == scSMinExpr)
3550         return APIntOps::smin(LHS, RHS);
3551       else if (Kind == scUMaxExpr)
3552         return APIntOps::umax(LHS, RHS);
3553       else if (Kind == scUMinExpr)
3554         return APIntOps::umin(LHS, RHS);
3555       llvm_unreachable("Unknown SCEV min/max opcode");
3556     };
3557 
3558     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3559       // We found two constants, fold them together!
3560       ConstantInt *Fold = ConstantInt::get(
3561           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3562       Ops[0] = getConstant(Fold);
3563       Ops.erase(Ops.begin()+1);  // Erase the folded element
3564       if (Ops.size() == 1) return Ops[0];
3565       LHSC = cast<SCEVConstant>(Ops[0]);
3566     }
3567 
3568     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3569     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3570 
3571     if (IsMax ? IsMinV : IsMaxV) {
3572       // If we are left with a constant minimum(/maximum)-int, strip it off.
3573       Ops.erase(Ops.begin());
3574       --Idx;
3575     } else if (IsMax ? IsMaxV : IsMinV) {
3576       // If we have a max(/min) with a constant maximum(/minimum)-int,
3577       // it will always be the extremum.
3578       return LHSC;
3579     }
3580 
3581     if (Ops.size() == 1) return Ops[0];
3582   }
3583 
3584   // Find the first operation of the same kind
3585   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3586     ++Idx;
3587 
3588   // Check to see if one of the operands is of the same kind. If so, expand its
3589   // operands onto our operand list, and recurse to simplify.
3590   if (Idx < Ops.size()) {
3591     bool DeletedAny = false;
3592     while (Ops[Idx]->getSCEVType() == Kind) {
3593       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3594       Ops.erase(Ops.begin()+Idx);
3595       Ops.append(SMME->op_begin(), SMME->op_end());
3596       DeletedAny = true;
3597     }
3598 
3599     if (DeletedAny)
3600       return getMinMaxExpr(Kind, Ops);
3601   }
3602 
3603   // Okay, check to see if the same value occurs in the operand list twice.  If
3604   // so, delete one.  Since we sorted the list, these values are required to
3605   // be adjacent.
3606   llvm::CmpInst::Predicate GEPred =
3607       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3608   llvm::CmpInst::Predicate LEPred =
3609       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3610   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3611   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3612   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3613     if (Ops[i] == Ops[i + 1] ||
3614         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3615       //  X op Y op Y  -->  X op Y
3616       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3617       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3618       --i;
3619       --e;
3620     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3621                                                Ops[i + 1])) {
3622       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3623       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3624       --i;
3625       --e;
3626     }
3627   }
3628 
3629   if (Ops.size() == 1) return Ops[0];
3630 
3631   assert(!Ops.empty() && "Reduced smax down to nothing!");
3632 
3633   // Okay, it looks like we really DO need an expr.  Check to see if we
3634   // already have one, otherwise create a new one.
3635   const SCEV *ExistingSCEV;
3636   FoldingSetNodeID ID;
3637   void *IP;
3638   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3639   if (ExistingSCEV)
3640     return ExistingSCEV;
3641   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3642   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3643   SCEV *S = new (SCEVAllocator)
3644       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3645 
3646   UniqueSCEVs.InsertNode(S, IP);
3647   addToLoopUseLists(S);
3648   return S;
3649 }
3650 
3651 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3652   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3653   return getSMaxExpr(Ops);
3654 }
3655 
3656 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3657   return getMinMaxExpr(scSMaxExpr, Ops);
3658 }
3659 
3660 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3661   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3662   return getUMaxExpr(Ops);
3663 }
3664 
3665 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3666   return getMinMaxExpr(scUMaxExpr, Ops);
3667 }
3668 
3669 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3670                                          const SCEV *RHS) {
3671   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3672   return getSMinExpr(Ops);
3673 }
3674 
3675 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3676   return getMinMaxExpr(scSMinExpr, Ops);
3677 }
3678 
3679 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3680                                          const SCEV *RHS) {
3681   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3682   return getUMinExpr(Ops);
3683 }
3684 
3685 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3686   return getMinMaxExpr(scUMinExpr, Ops);
3687 }
3688 
3689 const SCEV *
3690 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3691                                              ScalableVectorType *ScalableTy) {
3692   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3693   Constant *One = ConstantInt::get(IntTy, 1);
3694   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3695   // Note that the expression we created is the final expression, we don't
3696   // want to simplify it any further Also, if we call a normal getSCEV(),
3697   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3698   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3699 }
3700 
3701 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3702   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3703     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3704   // We can bypass creating a target-independent constant expression and then
3705   // folding it back into a ConstantInt. This is just a compile-time
3706   // optimization.
3707   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3708 }
3709 
3710 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3711   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3712     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3713   // We can bypass creating a target-independent constant expression and then
3714   // folding it back into a ConstantInt. This is just a compile-time
3715   // optimization.
3716   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3717 }
3718 
3719 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3720                                              StructType *STy,
3721                                              unsigned FieldNo) {
3722   // We can bypass creating a target-independent constant expression and then
3723   // folding it back into a ConstantInt. This is just a compile-time
3724   // optimization.
3725   return getConstant(
3726       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3727 }
3728 
3729 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3730   // Don't attempt to do anything other than create a SCEVUnknown object
3731   // here.  createSCEV only calls getUnknown after checking for all other
3732   // interesting possibilities, and any other code that calls getUnknown
3733   // is doing so in order to hide a value from SCEV canonicalization.
3734 
3735   FoldingSetNodeID ID;
3736   ID.AddInteger(scUnknown);
3737   ID.AddPointer(V);
3738   void *IP = nullptr;
3739   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3740     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3741            "Stale SCEVUnknown in uniquing map!");
3742     return S;
3743   }
3744   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3745                                             FirstUnknown);
3746   FirstUnknown = cast<SCEVUnknown>(S);
3747   UniqueSCEVs.InsertNode(S, IP);
3748   return S;
3749 }
3750 
3751 //===----------------------------------------------------------------------===//
3752 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3753 //
3754 
3755 /// Test if values of the given type are analyzable within the SCEV
3756 /// framework. This primarily includes integer types, and it can optionally
3757 /// include pointer types if the ScalarEvolution class has access to
3758 /// target-specific information.
3759 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3760   // Integers and pointers are always SCEVable.
3761   return Ty->isIntOrPtrTy();
3762 }
3763 
3764 /// Return the size in bits of the specified type, for which isSCEVable must
3765 /// return true.
3766 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3767   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3768   if (Ty->isPointerTy())
3769     return getDataLayout().getIndexTypeSizeInBits(Ty);
3770   return getDataLayout().getTypeSizeInBits(Ty);
3771 }
3772 
3773 /// Return a type with the same bitwidth as the given type and which represents
3774 /// how SCEV will treat the given type, for which isSCEVable must return
3775 /// true. For pointer types, this is the pointer index sized integer type.
3776 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3777   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3778 
3779   if (Ty->isIntegerTy())
3780     return Ty;
3781 
3782   // The only other support type is pointer.
3783   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3784   return getDataLayout().getIndexType(Ty);
3785 }
3786 
3787 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3788   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3789 }
3790 
3791 const SCEV *ScalarEvolution::getCouldNotCompute() {
3792   return CouldNotCompute.get();
3793 }
3794 
3795 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3796   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3797     auto *SU = dyn_cast<SCEVUnknown>(S);
3798     return SU && SU->getValue() == nullptr;
3799   });
3800 
3801   return !ContainsNulls;
3802 }
3803 
3804 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3805   HasRecMapType::iterator I = HasRecMap.find(S);
3806   if (I != HasRecMap.end())
3807     return I->second;
3808 
3809   bool FoundAddRec =
3810       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3811   HasRecMap.insert({S, FoundAddRec});
3812   return FoundAddRec;
3813 }
3814 
3815 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3816 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3817 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3818 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3819   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3820   if (!Add)
3821     return {S, nullptr};
3822 
3823   if (Add->getNumOperands() != 2)
3824     return {S, nullptr};
3825 
3826   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3827   if (!ConstOp)
3828     return {S, nullptr};
3829 
3830   return {Add->getOperand(1), ConstOp->getValue()};
3831 }
3832 
3833 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3834 /// by the value and offset from any ValueOffsetPair in the set.
3835 SetVector<ScalarEvolution::ValueOffsetPair> *
3836 ScalarEvolution::getSCEVValues(const SCEV *S) {
3837   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3838   if (SI == ExprValueMap.end())
3839     return nullptr;
3840 #ifndef NDEBUG
3841   if (VerifySCEVMap) {
3842     // Check there is no dangling Value in the set returned.
3843     for (const auto &VE : SI->second)
3844       assert(ValueExprMap.count(VE.first));
3845   }
3846 #endif
3847   return &SI->second;
3848 }
3849 
3850 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3851 /// cannot be used separately. eraseValueFromMap should be used to remove
3852 /// V from ValueExprMap and ExprValueMap at the same time.
3853 void ScalarEvolution::eraseValueFromMap(Value *V) {
3854   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3855   if (I != ValueExprMap.end()) {
3856     const SCEV *S = I->second;
3857     // Remove {V, 0} from the set of ExprValueMap[S]
3858     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3859       SV->remove({V, nullptr});
3860 
3861     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3862     const SCEV *Stripped;
3863     ConstantInt *Offset;
3864     std::tie(Stripped, Offset) = splitAddExpr(S);
3865     if (Offset != nullptr) {
3866       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3867         SV->remove({V, Offset});
3868     }
3869     ValueExprMap.erase(V);
3870   }
3871 }
3872 
3873 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3874 /// TODO: In reality it is better to check the poison recursively
3875 /// but this is better than nothing.
3876 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3877   if (auto *I = dyn_cast<Instruction>(V)) {
3878     if (isa<OverflowingBinaryOperator>(I)) {
3879       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3880         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3881           return true;
3882         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3883           return true;
3884       }
3885     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3886       return true;
3887   }
3888   return false;
3889 }
3890 
3891 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3892 /// create a new one.
3893 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3894   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3895 
3896   const SCEV *S = getExistingSCEV(V);
3897   if (S == nullptr) {
3898     S = createSCEV(V);
3899     // During PHI resolution, it is possible to create two SCEVs for the same
3900     // V, so it is needed to double check whether V->S is inserted into
3901     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3902     std::pair<ValueExprMapType::iterator, bool> Pair =
3903         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3904     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3905       ExprValueMap[S].insert({V, nullptr});
3906 
3907       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3908       // ExprValueMap.
3909       const SCEV *Stripped = S;
3910       ConstantInt *Offset = nullptr;
3911       std::tie(Stripped, Offset) = splitAddExpr(S);
3912       // If stripped is SCEVUnknown, don't bother to save
3913       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3914       // increase the complexity of the expansion code.
3915       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3916       // because it may generate add/sub instead of GEP in SCEV expansion.
3917       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3918           !isa<GetElementPtrInst>(V))
3919         ExprValueMap[Stripped].insert({V, Offset});
3920     }
3921   }
3922   return S;
3923 }
3924 
3925 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3926   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3927 
3928   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3929   if (I != ValueExprMap.end()) {
3930     const SCEV *S = I->second;
3931     if (checkValidity(S))
3932       return S;
3933     eraseValueFromMap(V);
3934     forgetMemoizedResults(S);
3935   }
3936   return nullptr;
3937 }
3938 
3939 /// Return a SCEV corresponding to -V = -1*V
3940 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3941                                              SCEV::NoWrapFlags Flags) {
3942   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3943     return getConstant(
3944                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3945 
3946   Type *Ty = V->getType();
3947   Ty = getEffectiveSCEVType(Ty);
3948   return getMulExpr(V, getMinusOne(Ty), Flags);
3949 }
3950 
3951 /// If Expr computes ~A, return A else return nullptr
3952 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3953   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3954   if (!Add || Add->getNumOperands() != 2 ||
3955       !Add->getOperand(0)->isAllOnesValue())
3956     return nullptr;
3957 
3958   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3959   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3960       !AddRHS->getOperand(0)->isAllOnesValue())
3961     return nullptr;
3962 
3963   return AddRHS->getOperand(1);
3964 }
3965 
3966 /// Return a SCEV corresponding to ~V = -1-V
3967 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3968   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3969     return getConstant(
3970                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3971 
3972   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3973   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3974     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3975       SmallVector<const SCEV *, 2> MatchedOperands;
3976       for (const SCEV *Operand : MME->operands()) {
3977         const SCEV *Matched = MatchNotExpr(Operand);
3978         if (!Matched)
3979           return (const SCEV *)nullptr;
3980         MatchedOperands.push_back(Matched);
3981       }
3982       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3983                            MatchedOperands);
3984     };
3985     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3986       return Replaced;
3987   }
3988 
3989   Type *Ty = V->getType();
3990   Ty = getEffectiveSCEVType(Ty);
3991   return getMinusSCEV(getMinusOne(Ty), V);
3992 }
3993 
3994 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3995                                           SCEV::NoWrapFlags Flags,
3996                                           unsigned Depth) {
3997   // Fast path: X - X --> 0.
3998   if (LHS == RHS)
3999     return getZero(LHS->getType());
4000 
4001   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4002   // makes it so that we cannot make much use of NUW.
4003   auto AddFlags = SCEV::FlagAnyWrap;
4004   const bool RHSIsNotMinSigned =
4005       !getSignedRangeMin(RHS).isMinSignedValue();
4006   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4007     // Let M be the minimum representable signed value. Then (-1)*RHS
4008     // signed-wraps if and only if RHS is M. That can happen even for
4009     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4010     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4011     // (-1)*RHS, we need to prove that RHS != M.
4012     //
4013     // If LHS is non-negative and we know that LHS - RHS does not
4014     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4015     // either by proving that RHS > M or that LHS >= 0.
4016     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4017       AddFlags = SCEV::FlagNSW;
4018     }
4019   }
4020 
4021   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4022   // RHS is NSW and LHS >= 0.
4023   //
4024   // The difficulty here is that the NSW flag may have been proven
4025   // relative to a loop that is to be found in a recurrence in LHS and
4026   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4027   // larger scope than intended.
4028   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4029 
4030   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4031 }
4032 
4033 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4034                                                      unsigned Depth) {
4035   Type *SrcTy = V->getType();
4036   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4037          "Cannot truncate or zero extend with non-integer arguments!");
4038   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4039     return V;  // No conversion
4040   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4041     return getTruncateExpr(V, Ty, Depth);
4042   return getZeroExtendExpr(V, Ty, Depth);
4043 }
4044 
4045 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4046                                                      unsigned Depth) {
4047   Type *SrcTy = V->getType();
4048   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4049          "Cannot truncate or zero extend with non-integer arguments!");
4050   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4051     return V;  // No conversion
4052   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4053     return getTruncateExpr(V, Ty, Depth);
4054   return getSignExtendExpr(V, Ty, Depth);
4055 }
4056 
4057 const SCEV *
4058 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4059   Type *SrcTy = V->getType();
4060   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4061          "Cannot noop or zero extend with non-integer arguments!");
4062   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4063          "getNoopOrZeroExtend cannot truncate!");
4064   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4065     return V;  // No conversion
4066   return getZeroExtendExpr(V, Ty);
4067 }
4068 
4069 const SCEV *
4070 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4071   Type *SrcTy = V->getType();
4072   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4073          "Cannot noop or sign extend with non-integer arguments!");
4074   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4075          "getNoopOrSignExtend cannot truncate!");
4076   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4077     return V;  // No conversion
4078   return getSignExtendExpr(V, Ty);
4079 }
4080 
4081 const SCEV *
4082 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4083   Type *SrcTy = V->getType();
4084   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4085          "Cannot noop or any extend with non-integer arguments!");
4086   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4087          "getNoopOrAnyExtend cannot truncate!");
4088   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4089     return V;  // No conversion
4090   return getAnyExtendExpr(V, Ty);
4091 }
4092 
4093 const SCEV *
4094 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4095   Type *SrcTy = V->getType();
4096   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4097          "Cannot truncate or noop with non-integer arguments!");
4098   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4099          "getTruncateOrNoop cannot extend!");
4100   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4101     return V;  // No conversion
4102   return getTruncateExpr(V, Ty);
4103 }
4104 
4105 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4106                                                         const SCEV *RHS) {
4107   const SCEV *PromotedLHS = LHS;
4108   const SCEV *PromotedRHS = RHS;
4109 
4110   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4111     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4112   else
4113     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4114 
4115   return getUMaxExpr(PromotedLHS, PromotedRHS);
4116 }
4117 
4118 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4119                                                         const SCEV *RHS) {
4120   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4121   return getUMinFromMismatchedTypes(Ops);
4122 }
4123 
4124 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4125     SmallVectorImpl<const SCEV *> &Ops) {
4126   assert(!Ops.empty() && "At least one operand must be!");
4127   // Trivial case.
4128   if (Ops.size() == 1)
4129     return Ops[0];
4130 
4131   // Find the max type first.
4132   Type *MaxType = nullptr;
4133   for (auto *S : Ops)
4134     if (MaxType)
4135       MaxType = getWiderType(MaxType, S->getType());
4136     else
4137       MaxType = S->getType();
4138   assert(MaxType && "Failed to find maximum type!");
4139 
4140   // Extend all ops to max type.
4141   SmallVector<const SCEV *, 2> PromotedOps;
4142   for (auto *S : Ops)
4143     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4144 
4145   // Generate umin.
4146   return getUMinExpr(PromotedOps);
4147 }
4148 
4149 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4150   // A pointer operand may evaluate to a nonpointer expression, such as null.
4151   if (!V->getType()->isPointerTy())
4152     return V;
4153 
4154   while (true) {
4155     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4156       V = Cast->getOperand();
4157     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4158       const SCEV *PtrOp = nullptr;
4159       for (const SCEV *NAryOp : NAry->operands()) {
4160         if (NAryOp->getType()->isPointerTy()) {
4161           // Cannot find the base of an expression with multiple pointer ops.
4162           if (PtrOp)
4163             return V;
4164           PtrOp = NAryOp;
4165         }
4166       }
4167       if (!PtrOp) // All operands were non-pointer.
4168         return V;
4169       V = PtrOp;
4170     } else // Not something we can look further into.
4171       return V;
4172   }
4173 }
4174 
4175 /// Push users of the given Instruction onto the given Worklist.
4176 static void
4177 PushDefUseChildren(Instruction *I,
4178                    SmallVectorImpl<Instruction *> &Worklist) {
4179   // Push the def-use children onto the Worklist stack.
4180   for (User *U : I->users())
4181     Worklist.push_back(cast<Instruction>(U));
4182 }
4183 
4184 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4185   SmallVector<Instruction *, 16> Worklist;
4186   PushDefUseChildren(PN, Worklist);
4187 
4188   SmallPtrSet<Instruction *, 8> Visited;
4189   Visited.insert(PN);
4190   while (!Worklist.empty()) {
4191     Instruction *I = Worklist.pop_back_val();
4192     if (!Visited.insert(I).second)
4193       continue;
4194 
4195     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4196     if (It != ValueExprMap.end()) {
4197       const SCEV *Old = It->second;
4198 
4199       // Short-circuit the def-use traversal if the symbolic name
4200       // ceases to appear in expressions.
4201       if (Old != SymName && !hasOperand(Old, SymName))
4202         continue;
4203 
4204       // SCEVUnknown for a PHI either means that it has an unrecognized
4205       // structure, it's a PHI that's in the progress of being computed
4206       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4207       // additional loop trip count information isn't going to change anything.
4208       // In the second case, createNodeForPHI will perform the necessary
4209       // updates on its own when it gets to that point. In the third, we do
4210       // want to forget the SCEVUnknown.
4211       if (!isa<PHINode>(I) ||
4212           !isa<SCEVUnknown>(Old) ||
4213           (I != PN && Old == SymName)) {
4214         eraseValueFromMap(It->first);
4215         forgetMemoizedResults(Old);
4216       }
4217     }
4218 
4219     PushDefUseChildren(I, Worklist);
4220   }
4221 }
4222 
4223 namespace {
4224 
4225 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4226 /// expression in case its Loop is L. If it is not L then
4227 /// if IgnoreOtherLoops is true then use AddRec itself
4228 /// otherwise rewrite cannot be done.
4229 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4230 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4231 public:
4232   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4233                              bool IgnoreOtherLoops = true) {
4234     SCEVInitRewriter Rewriter(L, SE);
4235     const SCEV *Result = Rewriter.visit(S);
4236     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4237       return SE.getCouldNotCompute();
4238     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4239                ? SE.getCouldNotCompute()
4240                : Result;
4241   }
4242 
4243   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4244     if (!SE.isLoopInvariant(Expr, L))
4245       SeenLoopVariantSCEVUnknown = true;
4246     return Expr;
4247   }
4248 
4249   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4250     // Only re-write AddRecExprs for this loop.
4251     if (Expr->getLoop() == L)
4252       return Expr->getStart();
4253     SeenOtherLoops = true;
4254     return Expr;
4255   }
4256 
4257   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4258 
4259   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4260 
4261 private:
4262   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4263       : SCEVRewriteVisitor(SE), L(L) {}
4264 
4265   const Loop *L;
4266   bool SeenLoopVariantSCEVUnknown = false;
4267   bool SeenOtherLoops = false;
4268 };
4269 
4270 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4271 /// increment expression in case its Loop is L. If it is not L then
4272 /// use AddRec itself.
4273 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4274 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4275 public:
4276   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4277     SCEVPostIncRewriter Rewriter(L, SE);
4278     const SCEV *Result = Rewriter.visit(S);
4279     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4280         ? SE.getCouldNotCompute()
4281         : Result;
4282   }
4283 
4284   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4285     if (!SE.isLoopInvariant(Expr, L))
4286       SeenLoopVariantSCEVUnknown = true;
4287     return Expr;
4288   }
4289 
4290   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4291     // Only re-write AddRecExprs for this loop.
4292     if (Expr->getLoop() == L)
4293       return Expr->getPostIncExpr(SE);
4294     SeenOtherLoops = true;
4295     return Expr;
4296   }
4297 
4298   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4299 
4300   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4301 
4302 private:
4303   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4304       : SCEVRewriteVisitor(SE), L(L) {}
4305 
4306   const Loop *L;
4307   bool SeenLoopVariantSCEVUnknown = false;
4308   bool SeenOtherLoops = false;
4309 };
4310 
4311 /// This class evaluates the compare condition by matching it against the
4312 /// condition of loop latch. If there is a match we assume a true value
4313 /// for the condition while building SCEV nodes.
4314 class SCEVBackedgeConditionFolder
4315     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4316 public:
4317   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4318                              ScalarEvolution &SE) {
4319     bool IsPosBECond = false;
4320     Value *BECond = nullptr;
4321     if (BasicBlock *Latch = L->getLoopLatch()) {
4322       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4323       if (BI && BI->isConditional()) {
4324         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4325                "Both outgoing branches should not target same header!");
4326         BECond = BI->getCondition();
4327         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4328       } else {
4329         return S;
4330       }
4331     }
4332     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4333     return Rewriter.visit(S);
4334   }
4335 
4336   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4337     const SCEV *Result = Expr;
4338     bool InvariantF = SE.isLoopInvariant(Expr, L);
4339 
4340     if (!InvariantF) {
4341       Instruction *I = cast<Instruction>(Expr->getValue());
4342       switch (I->getOpcode()) {
4343       case Instruction::Select: {
4344         SelectInst *SI = cast<SelectInst>(I);
4345         Optional<const SCEV *> Res =
4346             compareWithBackedgeCondition(SI->getCondition());
4347         if (Res.hasValue()) {
4348           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4349           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4350         }
4351         break;
4352       }
4353       default: {
4354         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4355         if (Res.hasValue())
4356           Result = Res.getValue();
4357         break;
4358       }
4359       }
4360     }
4361     return Result;
4362   }
4363 
4364 private:
4365   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4366                                        bool IsPosBECond, ScalarEvolution &SE)
4367       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4368         IsPositiveBECond(IsPosBECond) {}
4369 
4370   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4371 
4372   const Loop *L;
4373   /// Loop back condition.
4374   Value *BackedgeCond = nullptr;
4375   /// Set to true if loop back is on positive branch condition.
4376   bool IsPositiveBECond;
4377 };
4378 
4379 Optional<const SCEV *>
4380 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4381 
4382   // If value matches the backedge condition for loop latch,
4383   // then return a constant evolution node based on loopback
4384   // branch taken.
4385   if (BackedgeCond == IC)
4386     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4387                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4388   return None;
4389 }
4390 
4391 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4392 public:
4393   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4394                              ScalarEvolution &SE) {
4395     SCEVShiftRewriter Rewriter(L, SE);
4396     const SCEV *Result = Rewriter.visit(S);
4397     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4398   }
4399 
4400   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4401     // Only allow AddRecExprs for this loop.
4402     if (!SE.isLoopInvariant(Expr, L))
4403       Valid = false;
4404     return Expr;
4405   }
4406 
4407   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4408     if (Expr->getLoop() == L && Expr->isAffine())
4409       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4410     Valid = false;
4411     return Expr;
4412   }
4413 
4414   bool isValid() { return Valid; }
4415 
4416 private:
4417   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4418       : SCEVRewriteVisitor(SE), L(L) {}
4419 
4420   const Loop *L;
4421   bool Valid = true;
4422 };
4423 
4424 } // end anonymous namespace
4425 
4426 SCEV::NoWrapFlags
4427 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4428   if (!AR->isAffine())
4429     return SCEV::FlagAnyWrap;
4430 
4431   using OBO = OverflowingBinaryOperator;
4432 
4433   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4434 
4435   if (!AR->hasNoSignedWrap()) {
4436     ConstantRange AddRecRange = getSignedRange(AR);
4437     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4438 
4439     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4440         Instruction::Add, IncRange, OBO::NoSignedWrap);
4441     if (NSWRegion.contains(AddRecRange))
4442       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4443   }
4444 
4445   if (!AR->hasNoUnsignedWrap()) {
4446     ConstantRange AddRecRange = getUnsignedRange(AR);
4447     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4448 
4449     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4450         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4451     if (NUWRegion.contains(AddRecRange))
4452       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4453   }
4454 
4455   return Result;
4456 }
4457 
4458 SCEV::NoWrapFlags
4459 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4460   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4461 
4462   if (AR->hasNoSignedWrap())
4463     return Result;
4464 
4465   if (!AR->isAffine())
4466     return Result;
4467 
4468   const SCEV *Step = AR->getStepRecurrence(*this);
4469   const Loop *L = AR->getLoop();
4470 
4471   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4472   // Note that this serves two purposes: It filters out loops that are
4473   // simply not analyzable, and it covers the case where this code is
4474   // being called from within backedge-taken count analysis, such that
4475   // attempting to ask for the backedge-taken count would likely result
4476   // in infinite recursion. In the later case, the analysis code will
4477   // cope with a conservative value, and it will take care to purge
4478   // that value once it has finished.
4479   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4480 
4481   // Normally, in the cases we can prove no-overflow via a
4482   // backedge guarding condition, we can also compute a backedge
4483   // taken count for the loop.  The exceptions are assumptions and
4484   // guards present in the loop -- SCEV is not great at exploiting
4485   // these to compute max backedge taken counts, but can still use
4486   // these to prove lack of overflow.  Use this fact to avoid
4487   // doing extra work that may not pay off.
4488 
4489   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4490       AC.assumptions().empty())
4491     return Result;
4492 
4493   // If the backedge is guarded by a comparison with the pre-inc  value the
4494   // addrec is safe. Also, if the entry is guarded by a comparison with the
4495   // start value and the backedge is guarded by a comparison with the post-inc
4496   // value, the addrec is safe.
4497   ICmpInst::Predicate Pred;
4498   const SCEV *OverflowLimit =
4499     getSignedOverflowLimitForStep(Step, &Pred, this);
4500   if (OverflowLimit &&
4501       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4502        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4503     Result = setFlags(Result, SCEV::FlagNSW);
4504   }
4505   return Result;
4506 }
4507 SCEV::NoWrapFlags
4508 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4509   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4510 
4511   if (AR->hasNoUnsignedWrap())
4512     return Result;
4513 
4514   if (!AR->isAffine())
4515     return Result;
4516 
4517   const SCEV *Step = AR->getStepRecurrence(*this);
4518   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4519   const Loop *L = AR->getLoop();
4520 
4521   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4522   // Note that this serves two purposes: It filters out loops that are
4523   // simply not analyzable, and it covers the case where this code is
4524   // being called from within backedge-taken count analysis, such that
4525   // attempting to ask for the backedge-taken count would likely result
4526   // in infinite recursion. In the later case, the analysis code will
4527   // cope with a conservative value, and it will take care to purge
4528   // that value once it has finished.
4529   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4530 
4531   // Normally, in the cases we can prove no-overflow via a
4532   // backedge guarding condition, we can also compute a backedge
4533   // taken count for the loop.  The exceptions are assumptions and
4534   // guards present in the loop -- SCEV is not great at exploiting
4535   // these to compute max backedge taken counts, but can still use
4536   // these to prove lack of overflow.  Use this fact to avoid
4537   // doing extra work that may not pay off.
4538 
4539   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4540       AC.assumptions().empty())
4541     return Result;
4542 
4543   // If the backedge is guarded by a comparison with the pre-inc  value the
4544   // addrec is safe. Also, if the entry is guarded by a comparison with the
4545   // start value and the backedge is guarded by a comparison with the post-inc
4546   // value, the addrec is safe.
4547   if (isKnownPositive(Step)) {
4548     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4549                                 getUnsignedRangeMax(Step));
4550     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4551         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4552       Result = setFlags(Result, SCEV::FlagNUW);
4553     }
4554   }
4555 
4556   return Result;
4557 }
4558 
4559 namespace {
4560 
4561 /// Represents an abstract binary operation.  This may exist as a
4562 /// normal instruction or constant expression, or may have been
4563 /// derived from an expression tree.
4564 struct BinaryOp {
4565   unsigned Opcode;
4566   Value *LHS;
4567   Value *RHS;
4568   bool IsNSW = false;
4569   bool IsNUW = false;
4570 
4571   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4572   /// constant expression.
4573   Operator *Op = nullptr;
4574 
4575   explicit BinaryOp(Operator *Op)
4576       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4577         Op(Op) {
4578     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4579       IsNSW = OBO->hasNoSignedWrap();
4580       IsNUW = OBO->hasNoUnsignedWrap();
4581     }
4582   }
4583 
4584   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4585                     bool IsNUW = false)
4586       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4587 };
4588 
4589 } // end anonymous namespace
4590 
4591 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4592 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4593   auto *Op = dyn_cast<Operator>(V);
4594   if (!Op)
4595     return None;
4596 
4597   // Implementation detail: all the cleverness here should happen without
4598   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4599   // SCEV expressions when possible, and we should not break that.
4600 
4601   switch (Op->getOpcode()) {
4602   case Instruction::Add:
4603   case Instruction::Sub:
4604   case Instruction::Mul:
4605   case Instruction::UDiv:
4606   case Instruction::URem:
4607   case Instruction::And:
4608   case Instruction::Or:
4609   case Instruction::AShr:
4610   case Instruction::Shl:
4611     return BinaryOp(Op);
4612 
4613   case Instruction::Xor:
4614     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4615       // If the RHS of the xor is a signmask, then this is just an add.
4616       // Instcombine turns add of signmask into xor as a strength reduction step.
4617       if (RHSC->getValue().isSignMask())
4618         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4619     return BinaryOp(Op);
4620 
4621   case Instruction::LShr:
4622     // Turn logical shift right of a constant into a unsigned divide.
4623     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4624       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4625 
4626       // If the shift count is not less than the bitwidth, the result of
4627       // the shift is undefined. Don't try to analyze it, because the
4628       // resolution chosen here may differ from the resolution chosen in
4629       // other parts of the compiler.
4630       if (SA->getValue().ult(BitWidth)) {
4631         Constant *X =
4632             ConstantInt::get(SA->getContext(),
4633                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4634         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4635       }
4636     }
4637     return BinaryOp(Op);
4638 
4639   case Instruction::ExtractValue: {
4640     auto *EVI = cast<ExtractValueInst>(Op);
4641     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4642       break;
4643 
4644     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4645     if (!WO)
4646       break;
4647 
4648     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4649     bool Signed = WO->isSigned();
4650     // TODO: Should add nuw/nsw flags for mul as well.
4651     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4652       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4653 
4654     // Now that we know that all uses of the arithmetic-result component of
4655     // CI are guarded by the overflow check, we can go ahead and pretend
4656     // that the arithmetic is non-overflowing.
4657     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4658                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4659   }
4660 
4661   default:
4662     break;
4663   }
4664 
4665   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4666   // semantics as a Sub, return a binary sub expression.
4667   if (auto *II = dyn_cast<IntrinsicInst>(V))
4668     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4669       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4670 
4671   return None;
4672 }
4673 
4674 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4675 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4676 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4677 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4678 /// follows one of the following patterns:
4679 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4680 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4681 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4682 /// we return the type of the truncation operation, and indicate whether the
4683 /// truncated type should be treated as signed/unsigned by setting
4684 /// \p Signed to true/false, respectively.
4685 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4686                                bool &Signed, ScalarEvolution &SE) {
4687   // The case where Op == SymbolicPHI (that is, with no type conversions on
4688   // the way) is handled by the regular add recurrence creating logic and
4689   // would have already been triggered in createAddRecForPHI. Reaching it here
4690   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4691   // because one of the other operands of the SCEVAddExpr updating this PHI is
4692   // not invariant).
4693   //
4694   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4695   // this case predicates that allow us to prove that Op == SymbolicPHI will
4696   // be added.
4697   if (Op == SymbolicPHI)
4698     return nullptr;
4699 
4700   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4701   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4702   if (SourceBits != NewBits)
4703     return nullptr;
4704 
4705   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4706   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4707   if (!SExt && !ZExt)
4708     return nullptr;
4709   const SCEVTruncateExpr *Trunc =
4710       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4711            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4712   if (!Trunc)
4713     return nullptr;
4714   const SCEV *X = Trunc->getOperand();
4715   if (X != SymbolicPHI)
4716     return nullptr;
4717   Signed = SExt != nullptr;
4718   return Trunc->getType();
4719 }
4720 
4721 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4722   if (!PN->getType()->isIntegerTy())
4723     return nullptr;
4724   const Loop *L = LI.getLoopFor(PN->getParent());
4725   if (!L || L->getHeader() != PN->getParent())
4726     return nullptr;
4727   return L;
4728 }
4729 
4730 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4731 // computation that updates the phi follows the following pattern:
4732 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4733 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4734 // If so, try to see if it can be rewritten as an AddRecExpr under some
4735 // Predicates. If successful, return them as a pair. Also cache the results
4736 // of the analysis.
4737 //
4738 // Example usage scenario:
4739 //    Say the Rewriter is called for the following SCEV:
4740 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4741 //    where:
4742 //         %X = phi i64 (%Start, %BEValue)
4743 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4744 //    and call this function with %SymbolicPHI = %X.
4745 //
4746 //    The analysis will find that the value coming around the backedge has
4747 //    the following SCEV:
4748 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4749 //    Upon concluding that this matches the desired pattern, the function
4750 //    will return the pair {NewAddRec, SmallPredsVec} where:
4751 //         NewAddRec = {%Start,+,%Step}
4752 //         SmallPredsVec = {P1, P2, P3} as follows:
4753 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4754 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4755 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4756 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4757 //    under the predicates {P1,P2,P3}.
4758 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4759 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4760 //
4761 // TODO's:
4762 //
4763 // 1) Extend the Induction descriptor to also support inductions that involve
4764 //    casts: When needed (namely, when we are called in the context of the
4765 //    vectorizer induction analysis), a Set of cast instructions will be
4766 //    populated by this method, and provided back to isInductionPHI. This is
4767 //    needed to allow the vectorizer to properly record them to be ignored by
4768 //    the cost model and to avoid vectorizing them (otherwise these casts,
4769 //    which are redundant under the runtime overflow checks, will be
4770 //    vectorized, which can be costly).
4771 //
4772 // 2) Support additional induction/PHISCEV patterns: We also want to support
4773 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4774 //    after the induction update operation (the induction increment):
4775 //
4776 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4777 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4778 //
4779 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4780 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4781 //
4782 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4783 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4784 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4785   SmallVector<const SCEVPredicate *, 3> Predicates;
4786 
4787   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4788   // return an AddRec expression under some predicate.
4789 
4790   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4791   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4792   assert(L && "Expecting an integer loop header phi");
4793 
4794   // The loop may have multiple entrances or multiple exits; we can analyze
4795   // this phi as an addrec if it has a unique entry value and a unique
4796   // backedge value.
4797   Value *BEValueV = nullptr, *StartValueV = nullptr;
4798   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4799     Value *V = PN->getIncomingValue(i);
4800     if (L->contains(PN->getIncomingBlock(i))) {
4801       if (!BEValueV) {
4802         BEValueV = V;
4803       } else if (BEValueV != V) {
4804         BEValueV = nullptr;
4805         break;
4806       }
4807     } else if (!StartValueV) {
4808       StartValueV = V;
4809     } else if (StartValueV != V) {
4810       StartValueV = nullptr;
4811       break;
4812     }
4813   }
4814   if (!BEValueV || !StartValueV)
4815     return None;
4816 
4817   const SCEV *BEValue = getSCEV(BEValueV);
4818 
4819   // If the value coming around the backedge is an add with the symbolic
4820   // value we just inserted, possibly with casts that we can ignore under
4821   // an appropriate runtime guard, then we found a simple induction variable!
4822   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4823   if (!Add)
4824     return None;
4825 
4826   // If there is a single occurrence of the symbolic value, possibly
4827   // casted, replace it with a recurrence.
4828   unsigned FoundIndex = Add->getNumOperands();
4829   Type *TruncTy = nullptr;
4830   bool Signed;
4831   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4832     if ((TruncTy =
4833              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4834       if (FoundIndex == e) {
4835         FoundIndex = i;
4836         break;
4837       }
4838 
4839   if (FoundIndex == Add->getNumOperands())
4840     return None;
4841 
4842   // Create an add with everything but the specified operand.
4843   SmallVector<const SCEV *, 8> Ops;
4844   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4845     if (i != FoundIndex)
4846       Ops.push_back(Add->getOperand(i));
4847   const SCEV *Accum = getAddExpr(Ops);
4848 
4849   // The runtime checks will not be valid if the step amount is
4850   // varying inside the loop.
4851   if (!isLoopInvariant(Accum, L))
4852     return None;
4853 
4854   // *** Part2: Create the predicates
4855 
4856   // Analysis was successful: we have a phi-with-cast pattern for which we
4857   // can return an AddRec expression under the following predicates:
4858   //
4859   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4860   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4861   // P2: An Equal predicate that guarantees that
4862   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4863   // P3: An Equal predicate that guarantees that
4864   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4865   //
4866   // As we next prove, the above predicates guarantee that:
4867   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4868   //
4869   //
4870   // More formally, we want to prove that:
4871   //     Expr(i+1) = Start + (i+1) * Accum
4872   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4873   //
4874   // Given that:
4875   // 1) Expr(0) = Start
4876   // 2) Expr(1) = Start + Accum
4877   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4878   // 3) Induction hypothesis (step i):
4879   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4880   //
4881   // Proof:
4882   //  Expr(i+1) =
4883   //   = Start + (i+1)*Accum
4884   //   = (Start + i*Accum) + Accum
4885   //   = Expr(i) + Accum
4886   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4887   //                                                             :: from step i
4888   //
4889   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4890   //
4891   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4892   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4893   //     + Accum                                                     :: from P3
4894   //
4895   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4896   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4897   //
4898   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4899   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4900   //
4901   // By induction, the same applies to all iterations 1<=i<n:
4902   //
4903 
4904   // Create a truncated addrec for which we will add a no overflow check (P1).
4905   const SCEV *StartVal = getSCEV(StartValueV);
4906   const SCEV *PHISCEV =
4907       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4908                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4909 
4910   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4911   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4912   // will be constant.
4913   //
4914   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4915   // add P1.
4916   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4917     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4918         Signed ? SCEVWrapPredicate::IncrementNSSW
4919                : SCEVWrapPredicate::IncrementNUSW;
4920     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4921     Predicates.push_back(AddRecPred);
4922   }
4923 
4924   // Create the Equal Predicates P2,P3:
4925 
4926   // It is possible that the predicates P2 and/or P3 are computable at
4927   // compile time due to StartVal and/or Accum being constants.
4928   // If either one is, then we can check that now and escape if either P2
4929   // or P3 is false.
4930 
4931   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4932   // for each of StartVal and Accum
4933   auto getExtendedExpr = [&](const SCEV *Expr,
4934                              bool CreateSignExtend) -> const SCEV * {
4935     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4936     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4937     const SCEV *ExtendedExpr =
4938         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4939                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4940     return ExtendedExpr;
4941   };
4942 
4943   // Given:
4944   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4945   //               = getExtendedExpr(Expr)
4946   // Determine whether the predicate P: Expr == ExtendedExpr
4947   // is known to be false at compile time
4948   auto PredIsKnownFalse = [&](const SCEV *Expr,
4949                               const SCEV *ExtendedExpr) -> bool {
4950     return Expr != ExtendedExpr &&
4951            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4952   };
4953 
4954   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4955   if (PredIsKnownFalse(StartVal, StartExtended)) {
4956     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4957     return None;
4958   }
4959 
4960   // The Step is always Signed (because the overflow checks are either
4961   // NSSW or NUSW)
4962   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4963   if (PredIsKnownFalse(Accum, AccumExtended)) {
4964     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4965     return None;
4966   }
4967 
4968   auto AppendPredicate = [&](const SCEV *Expr,
4969                              const SCEV *ExtendedExpr) -> void {
4970     if (Expr != ExtendedExpr &&
4971         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4972       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4973       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4974       Predicates.push_back(Pred);
4975     }
4976   };
4977 
4978   AppendPredicate(StartVal, StartExtended);
4979   AppendPredicate(Accum, AccumExtended);
4980 
4981   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4982   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4983   // into NewAR if it will also add the runtime overflow checks specified in
4984   // Predicates.
4985   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4986 
4987   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4988       std::make_pair(NewAR, Predicates);
4989   // Remember the result of the analysis for this SCEV at this locayyytion.
4990   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4991   return PredRewrite;
4992 }
4993 
4994 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4995 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4996   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4997   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4998   if (!L)
4999     return None;
5000 
5001   // Check to see if we already analyzed this PHI.
5002   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5003   if (I != PredicatedSCEVRewrites.end()) {
5004     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5005         I->second;
5006     // Analysis was done before and failed to create an AddRec:
5007     if (Rewrite.first == SymbolicPHI)
5008       return None;
5009     // Analysis was done before and succeeded to create an AddRec under
5010     // a predicate:
5011     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5012     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5013     return Rewrite;
5014   }
5015 
5016   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5017     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5018 
5019   // Record in the cache that the analysis failed
5020   if (!Rewrite) {
5021     SmallVector<const SCEVPredicate *, 3> Predicates;
5022     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5023     return None;
5024   }
5025 
5026   return Rewrite;
5027 }
5028 
5029 // FIXME: This utility is currently required because the Rewriter currently
5030 // does not rewrite this expression:
5031 // {0, +, (sext ix (trunc iy to ix) to iy)}
5032 // into {0, +, %step},
5033 // even when the following Equal predicate exists:
5034 // "%step == (sext ix (trunc iy to ix) to iy)".
5035 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5036     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5037   if (AR1 == AR2)
5038     return true;
5039 
5040   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5041     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5042         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5043       return false;
5044     return true;
5045   };
5046 
5047   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5048       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5049     return false;
5050   return true;
5051 }
5052 
5053 /// A helper function for createAddRecFromPHI to handle simple cases.
5054 ///
5055 /// This function tries to find an AddRec expression for the simplest (yet most
5056 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5057 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5058 /// technique for finding the AddRec expression.
5059 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5060                                                       Value *BEValueV,
5061                                                       Value *StartValueV) {
5062   const Loop *L = LI.getLoopFor(PN->getParent());
5063   assert(L && L->getHeader() == PN->getParent());
5064   assert(BEValueV && StartValueV);
5065 
5066   auto BO = MatchBinaryOp(BEValueV, DT);
5067   if (!BO)
5068     return nullptr;
5069 
5070   if (BO->Opcode != Instruction::Add)
5071     return nullptr;
5072 
5073   const SCEV *Accum = nullptr;
5074   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5075     Accum = getSCEV(BO->RHS);
5076   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5077     Accum = getSCEV(BO->LHS);
5078 
5079   if (!Accum)
5080     return nullptr;
5081 
5082   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5083   if (BO->IsNUW)
5084     Flags = setFlags(Flags, SCEV::FlagNUW);
5085   if (BO->IsNSW)
5086     Flags = setFlags(Flags, SCEV::FlagNSW);
5087 
5088   const SCEV *StartVal = getSCEV(StartValueV);
5089   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5090 
5091   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5092 
5093   // We can add Flags to the post-inc expression only if we
5094   // know that it is *undefined behavior* for BEValueV to
5095   // overflow.
5096   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5097     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5098       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5099 
5100   return PHISCEV;
5101 }
5102 
5103 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5104   const Loop *L = LI.getLoopFor(PN->getParent());
5105   if (!L || L->getHeader() != PN->getParent())
5106     return nullptr;
5107 
5108   // The loop may have multiple entrances or multiple exits; we can analyze
5109   // this phi as an addrec if it has a unique entry value and a unique
5110   // backedge value.
5111   Value *BEValueV = nullptr, *StartValueV = nullptr;
5112   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5113     Value *V = PN->getIncomingValue(i);
5114     if (L->contains(PN->getIncomingBlock(i))) {
5115       if (!BEValueV) {
5116         BEValueV = V;
5117       } else if (BEValueV != V) {
5118         BEValueV = nullptr;
5119         break;
5120       }
5121     } else if (!StartValueV) {
5122       StartValueV = V;
5123     } else if (StartValueV != V) {
5124       StartValueV = nullptr;
5125       break;
5126     }
5127   }
5128   if (!BEValueV || !StartValueV)
5129     return nullptr;
5130 
5131   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5132          "PHI node already processed?");
5133 
5134   // First, try to find AddRec expression without creating a fictituos symbolic
5135   // value for PN.
5136   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5137     return S;
5138 
5139   // Handle PHI node value symbolically.
5140   const SCEV *SymbolicName = getUnknown(PN);
5141   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5142 
5143   // Using this symbolic name for the PHI, analyze the value coming around
5144   // the back-edge.
5145   const SCEV *BEValue = getSCEV(BEValueV);
5146 
5147   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5148   // has a special value for the first iteration of the loop.
5149 
5150   // If the value coming around the backedge is an add with the symbolic
5151   // value we just inserted, then we found a simple induction variable!
5152   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5153     // If there is a single occurrence of the symbolic value, replace it
5154     // with a recurrence.
5155     unsigned FoundIndex = Add->getNumOperands();
5156     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5157       if (Add->getOperand(i) == SymbolicName)
5158         if (FoundIndex == e) {
5159           FoundIndex = i;
5160           break;
5161         }
5162 
5163     if (FoundIndex != Add->getNumOperands()) {
5164       // Create an add with everything but the specified operand.
5165       SmallVector<const SCEV *, 8> Ops;
5166       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5167         if (i != FoundIndex)
5168           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5169                                                              L, *this));
5170       const SCEV *Accum = getAddExpr(Ops);
5171 
5172       // This is not a valid addrec if the step amount is varying each
5173       // loop iteration, but is not itself an addrec in this loop.
5174       if (isLoopInvariant(Accum, L) ||
5175           (isa<SCEVAddRecExpr>(Accum) &&
5176            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5177         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5178 
5179         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5180           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5181             if (BO->IsNUW)
5182               Flags = setFlags(Flags, SCEV::FlagNUW);
5183             if (BO->IsNSW)
5184               Flags = setFlags(Flags, SCEV::FlagNSW);
5185           }
5186         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5187           // If the increment is an inbounds GEP, then we know the address
5188           // space cannot be wrapped around. We cannot make any guarantee
5189           // about signed or unsigned overflow because pointers are
5190           // unsigned but we may have a negative index from the base
5191           // pointer. We can guarantee that no unsigned wrap occurs if the
5192           // indices form a positive value.
5193           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5194             Flags = setFlags(Flags, SCEV::FlagNW);
5195 
5196             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5197             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5198               Flags = setFlags(Flags, SCEV::FlagNUW);
5199           }
5200 
5201           // We cannot transfer nuw and nsw flags from subtraction
5202           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5203           // for instance.
5204         }
5205 
5206         const SCEV *StartVal = getSCEV(StartValueV);
5207         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5208 
5209         // Okay, for the entire analysis of this edge we assumed the PHI
5210         // to be symbolic.  We now need to go back and purge all of the
5211         // entries for the scalars that use the symbolic expression.
5212         forgetSymbolicName(PN, SymbolicName);
5213         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5214 
5215         // We can add Flags to the post-inc expression only if we
5216         // know that it is *undefined behavior* for BEValueV to
5217         // overflow.
5218         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5219           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5220             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5221 
5222         return PHISCEV;
5223       }
5224     }
5225   } else {
5226     // Otherwise, this could be a loop like this:
5227     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5228     // In this case, j = {1,+,1}  and BEValue is j.
5229     // Because the other in-value of i (0) fits the evolution of BEValue
5230     // i really is an addrec evolution.
5231     //
5232     // We can generalize this saying that i is the shifted value of BEValue
5233     // by one iteration:
5234     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5235     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5236     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5237     if (Shifted != getCouldNotCompute() &&
5238         Start != getCouldNotCompute()) {
5239       const SCEV *StartVal = getSCEV(StartValueV);
5240       if (Start == StartVal) {
5241         // Okay, for the entire analysis of this edge we assumed the PHI
5242         // to be symbolic.  We now need to go back and purge all of the
5243         // entries for the scalars that use the symbolic expression.
5244         forgetSymbolicName(PN, SymbolicName);
5245         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5246         return Shifted;
5247       }
5248     }
5249   }
5250 
5251   // Remove the temporary PHI node SCEV that has been inserted while intending
5252   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5253   // as it will prevent later (possibly simpler) SCEV expressions to be added
5254   // to the ValueExprMap.
5255   eraseValueFromMap(PN);
5256 
5257   return nullptr;
5258 }
5259 
5260 // Checks if the SCEV S is available at BB.  S is considered available at BB
5261 // if S can be materialized at BB without introducing a fault.
5262 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5263                                BasicBlock *BB) {
5264   struct CheckAvailable {
5265     bool TraversalDone = false;
5266     bool Available = true;
5267 
5268     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5269     BasicBlock *BB = nullptr;
5270     DominatorTree &DT;
5271 
5272     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5273       : L(L), BB(BB), DT(DT) {}
5274 
5275     bool setUnavailable() {
5276       TraversalDone = true;
5277       Available = false;
5278       return false;
5279     }
5280 
5281     bool follow(const SCEV *S) {
5282       switch (S->getSCEVType()) {
5283       case scConstant:
5284       case scPtrToInt:
5285       case scTruncate:
5286       case scZeroExtend:
5287       case scSignExtend:
5288       case scAddExpr:
5289       case scMulExpr:
5290       case scUMaxExpr:
5291       case scSMaxExpr:
5292       case scUMinExpr:
5293       case scSMinExpr:
5294         // These expressions are available if their operand(s) is/are.
5295         return true;
5296 
5297       case scAddRecExpr: {
5298         // We allow add recurrences that are on the loop BB is in, or some
5299         // outer loop.  This guarantees availability because the value of the
5300         // add recurrence at BB is simply the "current" value of the induction
5301         // variable.  We can relax this in the future; for instance an add
5302         // recurrence on a sibling dominating loop is also available at BB.
5303         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5304         if (L && (ARLoop == L || ARLoop->contains(L)))
5305           return true;
5306 
5307         return setUnavailable();
5308       }
5309 
5310       case scUnknown: {
5311         // For SCEVUnknown, we check for simple dominance.
5312         const auto *SU = cast<SCEVUnknown>(S);
5313         Value *V = SU->getValue();
5314 
5315         if (isa<Argument>(V))
5316           return false;
5317 
5318         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5319           return false;
5320 
5321         return setUnavailable();
5322       }
5323 
5324       case scUDivExpr:
5325       case scCouldNotCompute:
5326         // We do not try to smart about these at all.
5327         return setUnavailable();
5328       }
5329       llvm_unreachable("Unknown SCEV kind!");
5330     }
5331 
5332     bool isDone() { return TraversalDone; }
5333   };
5334 
5335   CheckAvailable CA(L, BB, DT);
5336   SCEVTraversal<CheckAvailable> ST(CA);
5337 
5338   ST.visitAll(S);
5339   return CA.Available;
5340 }
5341 
5342 // Try to match a control flow sequence that branches out at BI and merges back
5343 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5344 // match.
5345 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5346                           Value *&C, Value *&LHS, Value *&RHS) {
5347   C = BI->getCondition();
5348 
5349   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5350   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5351 
5352   if (!LeftEdge.isSingleEdge())
5353     return false;
5354 
5355   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5356 
5357   Use &LeftUse = Merge->getOperandUse(0);
5358   Use &RightUse = Merge->getOperandUse(1);
5359 
5360   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5361     LHS = LeftUse;
5362     RHS = RightUse;
5363     return true;
5364   }
5365 
5366   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5367     LHS = RightUse;
5368     RHS = LeftUse;
5369     return true;
5370   }
5371 
5372   return false;
5373 }
5374 
5375 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5376   auto IsReachable =
5377       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5378   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5379     const Loop *L = LI.getLoopFor(PN->getParent());
5380 
5381     // We don't want to break LCSSA, even in a SCEV expression tree.
5382     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5383       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5384         return nullptr;
5385 
5386     // Try to match
5387     //
5388     //  br %cond, label %left, label %right
5389     // left:
5390     //  br label %merge
5391     // right:
5392     //  br label %merge
5393     // merge:
5394     //  V = phi [ %x, %left ], [ %y, %right ]
5395     //
5396     // as "select %cond, %x, %y"
5397 
5398     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5399     assert(IDom && "At least the entry block should dominate PN");
5400 
5401     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5402     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5403 
5404     if (BI && BI->isConditional() &&
5405         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5406         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5407         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5408       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5409   }
5410 
5411   return nullptr;
5412 }
5413 
5414 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5415   if (const SCEV *S = createAddRecFromPHI(PN))
5416     return S;
5417 
5418   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5419     return S;
5420 
5421   // If the PHI has a single incoming value, follow that value, unless the
5422   // PHI's incoming blocks are in a different loop, in which case doing so
5423   // risks breaking LCSSA form. Instcombine would normally zap these, but
5424   // it doesn't have DominatorTree information, so it may miss cases.
5425   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5426     if (LI.replacementPreservesLCSSAForm(PN, V))
5427       return getSCEV(V);
5428 
5429   // If it's not a loop phi, we can't handle it yet.
5430   return getUnknown(PN);
5431 }
5432 
5433 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5434                                                       Value *Cond,
5435                                                       Value *TrueVal,
5436                                                       Value *FalseVal) {
5437   // Handle "constant" branch or select. This can occur for instance when a
5438   // loop pass transforms an inner loop and moves on to process the outer loop.
5439   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5440     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5441 
5442   // Try to match some simple smax or umax patterns.
5443   auto *ICI = dyn_cast<ICmpInst>(Cond);
5444   if (!ICI)
5445     return getUnknown(I);
5446 
5447   Value *LHS = ICI->getOperand(0);
5448   Value *RHS = ICI->getOperand(1);
5449 
5450   switch (ICI->getPredicate()) {
5451   case ICmpInst::ICMP_SLT:
5452   case ICmpInst::ICMP_SLE:
5453     std::swap(LHS, RHS);
5454     LLVM_FALLTHROUGH;
5455   case ICmpInst::ICMP_SGT:
5456   case ICmpInst::ICMP_SGE:
5457     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5458     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5459     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5460       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5461       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5462       const SCEV *LA = getSCEV(TrueVal);
5463       const SCEV *RA = getSCEV(FalseVal);
5464       const SCEV *LDiff = getMinusSCEV(LA, LS);
5465       const SCEV *RDiff = getMinusSCEV(RA, RS);
5466       if (LDiff == RDiff)
5467         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5468       LDiff = getMinusSCEV(LA, RS);
5469       RDiff = getMinusSCEV(RA, LS);
5470       if (LDiff == RDiff)
5471         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5472     }
5473     break;
5474   case ICmpInst::ICMP_ULT:
5475   case ICmpInst::ICMP_ULE:
5476     std::swap(LHS, RHS);
5477     LLVM_FALLTHROUGH;
5478   case ICmpInst::ICMP_UGT:
5479   case ICmpInst::ICMP_UGE:
5480     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5481     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5482     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5483       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5484       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5485       const SCEV *LA = getSCEV(TrueVal);
5486       const SCEV *RA = getSCEV(FalseVal);
5487       const SCEV *LDiff = getMinusSCEV(LA, LS);
5488       const SCEV *RDiff = getMinusSCEV(RA, RS);
5489       if (LDiff == RDiff)
5490         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5491       LDiff = getMinusSCEV(LA, RS);
5492       RDiff = getMinusSCEV(RA, LS);
5493       if (LDiff == RDiff)
5494         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5495     }
5496     break;
5497   case ICmpInst::ICMP_NE:
5498     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5499     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5500         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5501       const SCEV *One = getOne(I->getType());
5502       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5503       const SCEV *LA = getSCEV(TrueVal);
5504       const SCEV *RA = getSCEV(FalseVal);
5505       const SCEV *LDiff = getMinusSCEV(LA, LS);
5506       const SCEV *RDiff = getMinusSCEV(RA, One);
5507       if (LDiff == RDiff)
5508         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5509     }
5510     break;
5511   case ICmpInst::ICMP_EQ:
5512     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5513     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5514         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5515       const SCEV *One = getOne(I->getType());
5516       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5517       const SCEV *LA = getSCEV(TrueVal);
5518       const SCEV *RA = getSCEV(FalseVal);
5519       const SCEV *LDiff = getMinusSCEV(LA, One);
5520       const SCEV *RDiff = getMinusSCEV(RA, LS);
5521       if (LDiff == RDiff)
5522         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5523     }
5524     break;
5525   default:
5526     break;
5527   }
5528 
5529   return getUnknown(I);
5530 }
5531 
5532 /// Expand GEP instructions into add and multiply operations. This allows them
5533 /// to be analyzed by regular SCEV code.
5534 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5535   // Don't attempt to analyze GEPs over unsized objects.
5536   if (!GEP->getSourceElementType()->isSized())
5537     return getUnknown(GEP);
5538 
5539   SmallVector<const SCEV *, 4> IndexExprs;
5540   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5541     IndexExprs.push_back(getSCEV(*Index));
5542   return getGEPExpr(GEP, IndexExprs);
5543 }
5544 
5545 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5546   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5547     return C->getAPInt().countTrailingZeros();
5548 
5549   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5550     return GetMinTrailingZeros(I->getOperand());
5551 
5552   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5553     return std::min(GetMinTrailingZeros(T->getOperand()),
5554                     (uint32_t)getTypeSizeInBits(T->getType()));
5555 
5556   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5557     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5558     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5559                ? getTypeSizeInBits(E->getType())
5560                : OpRes;
5561   }
5562 
5563   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5564     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5565     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5566                ? getTypeSizeInBits(E->getType())
5567                : OpRes;
5568   }
5569 
5570   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5571     // The result is the min of all operands results.
5572     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5573     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5574       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5575     return MinOpRes;
5576   }
5577 
5578   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5579     // The result is the sum of all operands results.
5580     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5581     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5582     for (unsigned i = 1, e = M->getNumOperands();
5583          SumOpRes != BitWidth && i != e; ++i)
5584       SumOpRes =
5585           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5586     return SumOpRes;
5587   }
5588 
5589   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5590     // The result is the min of all operands results.
5591     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5592     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5593       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5594     return MinOpRes;
5595   }
5596 
5597   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5598     // The result is the min of all operands results.
5599     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5600     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5601       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5602     return MinOpRes;
5603   }
5604 
5605   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5606     // The result is the min of all operands results.
5607     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5608     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5609       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5610     return MinOpRes;
5611   }
5612 
5613   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5614     // For a SCEVUnknown, ask ValueTracking.
5615     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5616     return Known.countMinTrailingZeros();
5617   }
5618 
5619   // SCEVUDivExpr
5620   return 0;
5621 }
5622 
5623 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5624   auto I = MinTrailingZerosCache.find(S);
5625   if (I != MinTrailingZerosCache.end())
5626     return I->second;
5627 
5628   uint32_t Result = GetMinTrailingZerosImpl(S);
5629   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5630   assert(InsertPair.second && "Should insert a new key");
5631   return InsertPair.first->second;
5632 }
5633 
5634 /// Helper method to assign a range to V from metadata present in the IR.
5635 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5636   if (Instruction *I = dyn_cast<Instruction>(V))
5637     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5638       return getConstantRangeFromMetadata(*MD);
5639 
5640   return None;
5641 }
5642 
5643 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5644                                      SCEV::NoWrapFlags Flags) {
5645   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5646     AddRec->setNoWrapFlags(Flags);
5647     UnsignedRanges.erase(AddRec);
5648     SignedRanges.erase(AddRec);
5649   }
5650 }
5651 
5652 ConstantRange ScalarEvolution::
5653 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5654   const DataLayout &DL = getDataLayout();
5655 
5656   unsigned BitWidth = getTypeSizeInBits(U->getType());
5657   ConstantRange CR(BitWidth, /*isFullSet=*/true);
5658 
5659   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5660   // use information about the trip count to improve our available range.  Note
5661   // that the trip count independent cases are already handled by known bits.
5662   // WARNING: The definition of recurrence used here is subtly different than
5663   // the one used by AddRec (and thus most of this file).  Step is allowed to
5664   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5665   // and other addrecs in the same loop (for non-affine addrecs).  The code
5666   // below intentionally handles the case where step is not loop invariant.
5667   auto *P = dyn_cast<PHINode>(U->getValue());
5668   if (!P)
5669     return CR;
5670 
5671   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5672   // even the values that are not available in these blocks may come from them,
5673   // and this leads to false-positive recurrence test.
5674   for (auto *Pred : predecessors(P->getParent()))
5675     if (!DT.isReachableFromEntry(Pred))
5676       return CR;
5677 
5678   BinaryOperator *BO;
5679   Value *Start, *Step;
5680   if (!matchSimpleRecurrence(P, BO, Start, Step))
5681     return CR;
5682 
5683   // If we found a recurrence in reachable code, we must be in a loop. Note
5684   // that BO might be in some subloop of L, and that's completely okay.
5685   auto *L = LI.getLoopFor(P->getParent());
5686   assert(L && L->getHeader() == P->getParent());
5687   if (!L->contains(BO->getParent()))
5688     // NOTE: This bailout should be an assert instead.  However, asserting
5689     // the condition here exposes a case where LoopFusion is querying SCEV
5690     // with malformed loop information during the midst of the transform.
5691     // There doesn't appear to be an obvious fix, so for the moment bailout
5692     // until the caller issue can be fixed.  PR49566 tracks the bug.
5693     return CR;
5694 
5695   // TODO: Extend to other opcodes such as ashr, mul, and div
5696   switch (BO->getOpcode()) {
5697   default:
5698     return CR;
5699   case Instruction::LShr:
5700   case Instruction::Shl:
5701     break;
5702   };
5703 
5704   if (BO->getOperand(0) != P)
5705     // TODO: Handle the power function forms some day.
5706     return CR;
5707 
5708   unsigned TC = getSmallConstantMaxTripCount(L);
5709   if (!TC || TC >= BitWidth)
5710     return CR;
5711 
5712   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5713   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5714   assert(KnownStart.getBitWidth() == BitWidth &&
5715          KnownStep.getBitWidth() == BitWidth);
5716 
5717   // Compute total shift amount, being careful of overflow and bitwidths.
5718   auto MaxShiftAmt = KnownStep.getMaxValue();
5719   APInt TCAP(BitWidth, TC-1);
5720   bool Overflow = false;
5721   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5722   if (Overflow)
5723     return CR;
5724 
5725   switch (BO->getOpcode()) {
5726   default:
5727     llvm_unreachable("filtered out above");
5728   case Instruction::LShr: {
5729     // For each lshr, three cases:
5730     //   shift = 0 => unchanged value
5731     //   saturation => 0
5732     //   other => a smaller positive number
5733     // Thus, the low end of the unsigned range is the last value produced.
5734     auto KnownEnd = KnownBits::lshr(KnownStart,
5735                                     KnownBits::makeConstant(TotalShift));
5736     auto R = ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
5737                                         KnownStart.getMaxValue() + 1);
5738     CR = CR.intersectWith(R);
5739     break;
5740   }
5741   case Instruction::Shl: {
5742     // Iff no bits are shifted out, value increases on every shift.
5743     auto KnownEnd = KnownBits::shl(KnownStart,
5744                                    KnownBits::makeConstant(TotalShift));
5745     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5746       CR = CR.intersectWith(ConstantRange(KnownStart.getMinValue(),
5747                                           KnownEnd.getMaxValue() + 1));
5748     break;
5749   }
5750   };
5751   return CR;
5752 }
5753 
5754 
5755 
5756 /// Determine the range for a particular SCEV.  If SignHint is
5757 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5758 /// with a "cleaner" unsigned (resp. signed) representation.
5759 const ConstantRange &
5760 ScalarEvolution::getRangeRef(const SCEV *S,
5761                              ScalarEvolution::RangeSignHint SignHint) {
5762   DenseMap<const SCEV *, ConstantRange> &Cache =
5763       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5764                                                        : SignedRanges;
5765   ConstantRange::PreferredRangeType RangeType =
5766       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5767           ? ConstantRange::Unsigned : ConstantRange::Signed;
5768 
5769   // See if we've computed this range already.
5770   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5771   if (I != Cache.end())
5772     return I->second;
5773 
5774   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5775     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5776 
5777   unsigned BitWidth = getTypeSizeInBits(S->getType());
5778   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5779   using OBO = OverflowingBinaryOperator;
5780 
5781   // If the value has known zeros, the maximum value will have those known zeros
5782   // as well.
5783   uint32_t TZ = GetMinTrailingZeros(S);
5784   if (TZ != 0) {
5785     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5786       ConservativeResult =
5787           ConstantRange(APInt::getMinValue(BitWidth),
5788                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5789     else
5790       ConservativeResult = ConstantRange(
5791           APInt::getSignedMinValue(BitWidth),
5792           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5793   }
5794 
5795   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5796     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5797     unsigned WrapType = OBO::AnyWrap;
5798     if (Add->hasNoSignedWrap())
5799       WrapType |= OBO::NoSignedWrap;
5800     if (Add->hasNoUnsignedWrap())
5801       WrapType |= OBO::NoUnsignedWrap;
5802     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5803       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5804                           WrapType, RangeType);
5805     return setRange(Add, SignHint,
5806                     ConservativeResult.intersectWith(X, RangeType));
5807   }
5808 
5809   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5810     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5811     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5812       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5813     return setRange(Mul, SignHint,
5814                     ConservativeResult.intersectWith(X, RangeType));
5815   }
5816 
5817   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5818     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5819     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5820       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5821     return setRange(SMax, SignHint,
5822                     ConservativeResult.intersectWith(X, RangeType));
5823   }
5824 
5825   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5826     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5827     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5828       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5829     return setRange(UMax, SignHint,
5830                     ConservativeResult.intersectWith(X, RangeType));
5831   }
5832 
5833   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5834     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5835     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5836       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5837     return setRange(SMin, SignHint,
5838                     ConservativeResult.intersectWith(X, RangeType));
5839   }
5840 
5841   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5842     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5843     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5844       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5845     return setRange(UMin, SignHint,
5846                     ConservativeResult.intersectWith(X, RangeType));
5847   }
5848 
5849   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5850     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5851     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5852     return setRange(UDiv, SignHint,
5853                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5854   }
5855 
5856   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5857     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5858     return setRange(ZExt, SignHint,
5859                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5860                                                      RangeType));
5861   }
5862 
5863   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5864     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5865     return setRange(SExt, SignHint,
5866                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5867                                                      RangeType));
5868   }
5869 
5870   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5871     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5872     return setRange(PtrToInt, SignHint, X);
5873   }
5874 
5875   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5876     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5877     return setRange(Trunc, SignHint,
5878                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5879                                                      RangeType));
5880   }
5881 
5882   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5883     // If there's no unsigned wrap, the value will never be less than its
5884     // initial value.
5885     if (AddRec->hasNoUnsignedWrap()) {
5886       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5887       if (!UnsignedMinValue.isNullValue())
5888         ConservativeResult = ConservativeResult.intersectWith(
5889             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5890     }
5891 
5892     // If there's no signed wrap, and all the operands except initial value have
5893     // the same sign or zero, the value won't ever be:
5894     // 1: smaller than initial value if operands are non negative,
5895     // 2: bigger than initial value if operands are non positive.
5896     // For both cases, value can not cross signed min/max boundary.
5897     if (AddRec->hasNoSignedWrap()) {
5898       bool AllNonNeg = true;
5899       bool AllNonPos = true;
5900       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5901         if (!isKnownNonNegative(AddRec->getOperand(i)))
5902           AllNonNeg = false;
5903         if (!isKnownNonPositive(AddRec->getOperand(i)))
5904           AllNonPos = false;
5905       }
5906       if (AllNonNeg)
5907         ConservativeResult = ConservativeResult.intersectWith(
5908             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5909                                        APInt::getSignedMinValue(BitWidth)),
5910             RangeType);
5911       else if (AllNonPos)
5912         ConservativeResult = ConservativeResult.intersectWith(
5913             ConstantRange::getNonEmpty(
5914                 APInt::getSignedMinValue(BitWidth),
5915                 getSignedRangeMax(AddRec->getStart()) + 1),
5916             RangeType);
5917     }
5918 
5919     // TODO: non-affine addrec
5920     if (AddRec->isAffine()) {
5921       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5922       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5923           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5924         auto RangeFromAffine = getRangeForAffineAR(
5925             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5926             BitWidth);
5927         ConservativeResult =
5928             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5929 
5930         auto RangeFromFactoring = getRangeViaFactoring(
5931             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5932             BitWidth);
5933         ConservativeResult =
5934             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5935       }
5936 
5937       // Now try symbolic BE count and more powerful methods.
5938       if (UseExpensiveRangeSharpening) {
5939         const SCEV *SymbolicMaxBECount =
5940             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5941         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5942             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5943             AddRec->hasNoSelfWrap()) {
5944           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5945               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5946           ConservativeResult =
5947               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5948         }
5949       }
5950     }
5951 
5952     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5953   }
5954 
5955   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5956 
5957     // Check if the IR explicitly contains !range metadata.
5958     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5959     if (MDRange.hasValue())
5960       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5961                                                             RangeType);
5962 
5963     // Use facts about recurrences in the underlying IR.  Note that add
5964     // recurrences are AddRecExprs and thus don't hit this path.  This
5965     // primarily handles shift recurrences.
5966     auto CR = getRangeForUnknownRecurrence(U);
5967     ConservativeResult = ConservativeResult.intersectWith(CR);
5968 
5969     // See if ValueTracking can give us a useful range.
5970     const DataLayout &DL = getDataLayout();
5971     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5972     if (Known.getBitWidth() != BitWidth)
5973       Known = Known.zextOrTrunc(BitWidth);
5974 
5975     // ValueTracking may be able to compute a tighter result for the number of
5976     // sign bits than for the value of those sign bits.
5977     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5978     if (U->getType()->isPointerTy()) {
5979       // If the pointer size is larger than the index size type, this can cause
5980       // NS to be larger than BitWidth. So compensate for this.
5981       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5982       int ptrIdxDiff = ptrSize - BitWidth;
5983       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5984         NS -= ptrIdxDiff;
5985     }
5986 
5987     if (NS > 1) {
5988       // If we know any of the sign bits, we know all of the sign bits.
5989       if (!Known.Zero.getHiBits(NS).isNullValue())
5990         Known.Zero.setHighBits(NS);
5991       if (!Known.One.getHiBits(NS).isNullValue())
5992         Known.One.setHighBits(NS);
5993     }
5994 
5995     if (Known.getMinValue() != Known.getMaxValue() + 1)
5996       ConservativeResult = ConservativeResult.intersectWith(
5997           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5998           RangeType);
5999     if (NS > 1)
6000       ConservativeResult = ConservativeResult.intersectWith(
6001           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6002                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6003           RangeType);
6004 
6005     // A range of Phi is a subset of union of all ranges of its input.
6006     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6007       // Make sure that we do not run over cycled Phis.
6008       if (PendingPhiRanges.insert(Phi).second) {
6009         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6010         for (auto &Op : Phi->operands()) {
6011           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6012           RangeFromOps = RangeFromOps.unionWith(OpRange);
6013           // No point to continue if we already have a full set.
6014           if (RangeFromOps.isFullSet())
6015             break;
6016         }
6017         ConservativeResult =
6018             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6019         bool Erased = PendingPhiRanges.erase(Phi);
6020         assert(Erased && "Failed to erase Phi properly?");
6021         (void) Erased;
6022       }
6023     }
6024 
6025     return setRange(U, SignHint, std::move(ConservativeResult));
6026   }
6027 
6028   return setRange(S, SignHint, std::move(ConservativeResult));
6029 }
6030 
6031 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6032 // values that the expression can take. Initially, the expression has a value
6033 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6034 // argument defines if we treat Step as signed or unsigned.
6035 static ConstantRange getRangeForAffineARHelper(APInt Step,
6036                                                const ConstantRange &StartRange,
6037                                                const APInt &MaxBECount,
6038                                                unsigned BitWidth, bool Signed) {
6039   // If either Step or MaxBECount is 0, then the expression won't change, and we
6040   // just need to return the initial range.
6041   if (Step == 0 || MaxBECount == 0)
6042     return StartRange;
6043 
6044   // If we don't know anything about the initial value (i.e. StartRange is
6045   // FullRange), then we don't know anything about the final range either.
6046   // Return FullRange.
6047   if (StartRange.isFullSet())
6048     return ConstantRange::getFull(BitWidth);
6049 
6050   // If Step is signed and negative, then we use its absolute value, but we also
6051   // note that we're moving in the opposite direction.
6052   bool Descending = Signed && Step.isNegative();
6053 
6054   if (Signed)
6055     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6056     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6057     // This equations hold true due to the well-defined wrap-around behavior of
6058     // APInt.
6059     Step = Step.abs();
6060 
6061   // Check if Offset is more than full span of BitWidth. If it is, the
6062   // expression is guaranteed to overflow.
6063   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6064     return ConstantRange::getFull(BitWidth);
6065 
6066   // Offset is by how much the expression can change. Checks above guarantee no
6067   // overflow here.
6068   APInt Offset = Step * MaxBECount;
6069 
6070   // Minimum value of the final range will match the minimal value of StartRange
6071   // if the expression is increasing and will be decreased by Offset otherwise.
6072   // Maximum value of the final range will match the maximal value of StartRange
6073   // if the expression is decreasing and will be increased by Offset otherwise.
6074   APInt StartLower = StartRange.getLower();
6075   APInt StartUpper = StartRange.getUpper() - 1;
6076   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6077                                    : (StartUpper + std::move(Offset));
6078 
6079   // It's possible that the new minimum/maximum value will fall into the initial
6080   // range (due to wrap around). This means that the expression can take any
6081   // value in this bitwidth, and we have to return full range.
6082   if (StartRange.contains(MovedBoundary))
6083     return ConstantRange::getFull(BitWidth);
6084 
6085   APInt NewLower =
6086       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6087   APInt NewUpper =
6088       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6089   NewUpper += 1;
6090 
6091   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6092   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6093 }
6094 
6095 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6096                                                    const SCEV *Step,
6097                                                    const SCEV *MaxBECount,
6098                                                    unsigned BitWidth) {
6099   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6100          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6101          "Precondition!");
6102 
6103   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6104   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6105 
6106   // First, consider step signed.
6107   ConstantRange StartSRange = getSignedRange(Start);
6108   ConstantRange StepSRange = getSignedRange(Step);
6109 
6110   // If Step can be both positive and negative, we need to find ranges for the
6111   // maximum absolute step values in both directions and union them.
6112   ConstantRange SR =
6113       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6114                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6115   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6116                                               StartSRange, MaxBECountValue,
6117                                               BitWidth, /* Signed = */ true));
6118 
6119   // Next, consider step unsigned.
6120   ConstantRange UR = getRangeForAffineARHelper(
6121       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6122       MaxBECountValue, BitWidth, /* Signed = */ false);
6123 
6124   // Finally, intersect signed and unsigned ranges.
6125   return SR.intersectWith(UR, ConstantRange::Smallest);
6126 }
6127 
6128 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6129     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6130     ScalarEvolution::RangeSignHint SignHint) {
6131   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6132   assert(AddRec->hasNoSelfWrap() &&
6133          "This only works for non-self-wrapping AddRecs!");
6134   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6135   const SCEV *Step = AddRec->getStepRecurrence(*this);
6136   // Only deal with constant step to save compile time.
6137   if (!isa<SCEVConstant>(Step))
6138     return ConstantRange::getFull(BitWidth);
6139   // Let's make sure that we can prove that we do not self-wrap during
6140   // MaxBECount iterations. We need this because MaxBECount is a maximum
6141   // iteration count estimate, and we might infer nw from some exit for which we
6142   // do not know max exit count (or any other side reasoning).
6143   // TODO: Turn into assert at some point.
6144   if (getTypeSizeInBits(MaxBECount->getType()) >
6145       getTypeSizeInBits(AddRec->getType()))
6146     return ConstantRange::getFull(BitWidth);
6147   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6148   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6149   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6150   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6151   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6152                                          MaxItersWithoutWrap))
6153     return ConstantRange::getFull(BitWidth);
6154 
6155   ICmpInst::Predicate LEPred =
6156       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6157   ICmpInst::Predicate GEPred =
6158       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6159   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6160 
6161   // We know that there is no self-wrap. Let's take Start and End values and
6162   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6163   // the iteration. They either lie inside the range [Min(Start, End),
6164   // Max(Start, End)] or outside it:
6165   //
6166   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6167   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6168   //
6169   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6170   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6171   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6172   // Start <= End and step is positive, or Start >= End and step is negative.
6173   const SCEV *Start = AddRec->getStart();
6174   ConstantRange StartRange = getRangeRef(Start, SignHint);
6175   ConstantRange EndRange = getRangeRef(End, SignHint);
6176   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6177   // If they already cover full iteration space, we will know nothing useful
6178   // even if we prove what we want to prove.
6179   if (RangeBetween.isFullSet())
6180     return RangeBetween;
6181   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6182   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6183                                : RangeBetween.isWrappedSet();
6184   if (IsWrappedSet)
6185     return ConstantRange::getFull(BitWidth);
6186 
6187   if (isKnownPositive(Step) &&
6188       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6189     return RangeBetween;
6190   else if (isKnownNegative(Step) &&
6191            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6192     return RangeBetween;
6193   return ConstantRange::getFull(BitWidth);
6194 }
6195 
6196 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6197                                                     const SCEV *Step,
6198                                                     const SCEV *MaxBECount,
6199                                                     unsigned BitWidth) {
6200   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6201   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6202 
6203   struct SelectPattern {
6204     Value *Condition = nullptr;
6205     APInt TrueValue;
6206     APInt FalseValue;
6207 
6208     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6209                            const SCEV *S) {
6210       Optional<unsigned> CastOp;
6211       APInt Offset(BitWidth, 0);
6212 
6213       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6214              "Should be!");
6215 
6216       // Peel off a constant offset:
6217       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6218         // In the future we could consider being smarter here and handle
6219         // {Start+Step,+,Step} too.
6220         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6221           return;
6222 
6223         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6224         S = SA->getOperand(1);
6225       }
6226 
6227       // Peel off a cast operation
6228       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6229         CastOp = SCast->getSCEVType();
6230         S = SCast->getOperand();
6231       }
6232 
6233       using namespace llvm::PatternMatch;
6234 
6235       auto *SU = dyn_cast<SCEVUnknown>(S);
6236       const APInt *TrueVal, *FalseVal;
6237       if (!SU ||
6238           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6239                                           m_APInt(FalseVal)))) {
6240         Condition = nullptr;
6241         return;
6242       }
6243 
6244       TrueValue = *TrueVal;
6245       FalseValue = *FalseVal;
6246 
6247       // Re-apply the cast we peeled off earlier
6248       if (CastOp.hasValue())
6249         switch (*CastOp) {
6250         default:
6251           llvm_unreachable("Unknown SCEV cast type!");
6252 
6253         case scTruncate:
6254           TrueValue = TrueValue.trunc(BitWidth);
6255           FalseValue = FalseValue.trunc(BitWidth);
6256           break;
6257         case scZeroExtend:
6258           TrueValue = TrueValue.zext(BitWidth);
6259           FalseValue = FalseValue.zext(BitWidth);
6260           break;
6261         case scSignExtend:
6262           TrueValue = TrueValue.sext(BitWidth);
6263           FalseValue = FalseValue.sext(BitWidth);
6264           break;
6265         }
6266 
6267       // Re-apply the constant offset we peeled off earlier
6268       TrueValue += Offset;
6269       FalseValue += Offset;
6270     }
6271 
6272     bool isRecognized() { return Condition != nullptr; }
6273   };
6274 
6275   SelectPattern StartPattern(*this, BitWidth, Start);
6276   if (!StartPattern.isRecognized())
6277     return ConstantRange::getFull(BitWidth);
6278 
6279   SelectPattern StepPattern(*this, BitWidth, Step);
6280   if (!StepPattern.isRecognized())
6281     return ConstantRange::getFull(BitWidth);
6282 
6283   if (StartPattern.Condition != StepPattern.Condition) {
6284     // We don't handle this case today; but we could, by considering four
6285     // possibilities below instead of two. I'm not sure if there are cases where
6286     // that will help over what getRange already does, though.
6287     return ConstantRange::getFull(BitWidth);
6288   }
6289 
6290   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6291   // construct arbitrary general SCEV expressions here.  This function is called
6292   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6293   // say) can end up caching a suboptimal value.
6294 
6295   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6296   // C2352 and C2512 (otherwise it isn't needed).
6297 
6298   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6299   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6300   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6301   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6302 
6303   ConstantRange TrueRange =
6304       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6305   ConstantRange FalseRange =
6306       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6307 
6308   return TrueRange.unionWith(FalseRange);
6309 }
6310 
6311 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6312   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6313   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6314 
6315   // Return early if there are no flags to propagate to the SCEV.
6316   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6317   if (BinOp->hasNoUnsignedWrap())
6318     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6319   if (BinOp->hasNoSignedWrap())
6320     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6321   if (Flags == SCEV::FlagAnyWrap)
6322     return SCEV::FlagAnyWrap;
6323 
6324   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6325 }
6326 
6327 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6328   // Here we check that I is in the header of the innermost loop containing I,
6329   // since we only deal with instructions in the loop header. The actual loop we
6330   // need to check later will come from an add recurrence, but getting that
6331   // requires computing the SCEV of the operands, which can be expensive. This
6332   // check we can do cheaply to rule out some cases early.
6333   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6334   if (InnermostContainingLoop == nullptr ||
6335       InnermostContainingLoop->getHeader() != I->getParent())
6336     return false;
6337 
6338   // Only proceed if we can prove that I does not yield poison.
6339   if (!programUndefinedIfPoison(I))
6340     return false;
6341 
6342   // At this point we know that if I is executed, then it does not wrap
6343   // according to at least one of NSW or NUW. If I is not executed, then we do
6344   // not know if the calculation that I represents would wrap. Multiple
6345   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6346   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6347   // derived from other instructions that map to the same SCEV. We cannot make
6348   // that guarantee for cases where I is not executed. So we need to find the
6349   // loop that I is considered in relation to and prove that I is executed for
6350   // every iteration of that loop. That implies that the value that I
6351   // calculates does not wrap anywhere in the loop, so then we can apply the
6352   // flags to the SCEV.
6353   //
6354   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6355   // from different loops, so that we know which loop to prove that I is
6356   // executed in.
6357   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6358     // I could be an extractvalue from a call to an overflow intrinsic.
6359     // TODO: We can do better here in some cases.
6360     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6361       return false;
6362     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6363     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6364       bool AllOtherOpsLoopInvariant = true;
6365       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6366            ++OtherOpIndex) {
6367         if (OtherOpIndex != OpIndex) {
6368           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6369           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6370             AllOtherOpsLoopInvariant = false;
6371             break;
6372           }
6373         }
6374       }
6375       if (AllOtherOpsLoopInvariant &&
6376           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6377         return true;
6378     }
6379   }
6380   return false;
6381 }
6382 
6383 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6384   // If we know that \c I can never be poison period, then that's enough.
6385   if (isSCEVExprNeverPoison(I))
6386     return true;
6387 
6388   // For an add recurrence specifically, we assume that infinite loops without
6389   // side effects are undefined behavior, and then reason as follows:
6390   //
6391   // If the add recurrence is poison in any iteration, it is poison on all
6392   // future iterations (since incrementing poison yields poison). If the result
6393   // of the add recurrence is fed into the loop latch condition and the loop
6394   // does not contain any throws or exiting blocks other than the latch, we now
6395   // have the ability to "choose" whether the backedge is taken or not (by
6396   // choosing a sufficiently evil value for the poison feeding into the branch)
6397   // for every iteration including and after the one in which \p I first became
6398   // poison.  There are two possibilities (let's call the iteration in which \p
6399   // I first became poison as K):
6400   //
6401   //  1. In the set of iterations including and after K, the loop body executes
6402   //     no side effects.  In this case executing the backege an infinte number
6403   //     of times will yield undefined behavior.
6404   //
6405   //  2. In the set of iterations including and after K, the loop body executes
6406   //     at least one side effect.  In this case, that specific instance of side
6407   //     effect is control dependent on poison, which also yields undefined
6408   //     behavior.
6409 
6410   auto *ExitingBB = L->getExitingBlock();
6411   auto *LatchBB = L->getLoopLatch();
6412   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6413     return false;
6414 
6415   SmallPtrSet<const Instruction *, 16> Pushed;
6416   SmallVector<const Instruction *, 8> PoisonStack;
6417 
6418   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6419   // things that are known to be poison under that assumption go on the
6420   // PoisonStack.
6421   Pushed.insert(I);
6422   PoisonStack.push_back(I);
6423 
6424   bool LatchControlDependentOnPoison = false;
6425   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6426     const Instruction *Poison = PoisonStack.pop_back_val();
6427 
6428     for (auto *PoisonUser : Poison->users()) {
6429       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6430         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6431           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6432       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6433         assert(BI->isConditional() && "Only possibility!");
6434         if (BI->getParent() == LatchBB) {
6435           LatchControlDependentOnPoison = true;
6436           break;
6437         }
6438       }
6439     }
6440   }
6441 
6442   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6443 }
6444 
6445 ScalarEvolution::LoopProperties
6446 ScalarEvolution::getLoopProperties(const Loop *L) {
6447   using LoopProperties = ScalarEvolution::LoopProperties;
6448 
6449   auto Itr = LoopPropertiesCache.find(L);
6450   if (Itr == LoopPropertiesCache.end()) {
6451     auto HasSideEffects = [](Instruction *I) {
6452       if (auto *SI = dyn_cast<StoreInst>(I))
6453         return !SI->isSimple();
6454 
6455       return I->mayHaveSideEffects();
6456     };
6457 
6458     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6459                          /*HasNoSideEffects*/ true};
6460 
6461     for (auto *BB : L->getBlocks())
6462       for (auto &I : *BB) {
6463         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6464           LP.HasNoAbnormalExits = false;
6465         if (HasSideEffects(&I))
6466           LP.HasNoSideEffects = false;
6467         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6468           break; // We're already as pessimistic as we can get.
6469       }
6470 
6471     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6472     assert(InsertPair.second && "We just checked!");
6473     Itr = InsertPair.first;
6474   }
6475 
6476   return Itr->second;
6477 }
6478 
6479 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6480   if (!isSCEVable(V->getType()))
6481     return getUnknown(V);
6482 
6483   if (Instruction *I = dyn_cast<Instruction>(V)) {
6484     // Don't attempt to analyze instructions in blocks that aren't
6485     // reachable. Such instructions don't matter, and they aren't required
6486     // to obey basic rules for definitions dominating uses which this
6487     // analysis depends on.
6488     if (!DT.isReachableFromEntry(I->getParent()))
6489       return getUnknown(UndefValue::get(V->getType()));
6490   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6491     return getConstant(CI);
6492   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6493     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6494   else if (!isa<ConstantExpr>(V))
6495     return getUnknown(V);
6496 
6497   Operator *U = cast<Operator>(V);
6498   if (auto BO = MatchBinaryOp(U, DT)) {
6499     switch (BO->Opcode) {
6500     case Instruction::Add: {
6501       // The simple thing to do would be to just call getSCEV on both operands
6502       // and call getAddExpr with the result. However if we're looking at a
6503       // bunch of things all added together, this can be quite inefficient,
6504       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6505       // Instead, gather up all the operands and make a single getAddExpr call.
6506       // LLVM IR canonical form means we need only traverse the left operands.
6507       SmallVector<const SCEV *, 4> AddOps;
6508       do {
6509         if (BO->Op) {
6510           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6511             AddOps.push_back(OpSCEV);
6512             break;
6513           }
6514 
6515           // If a NUW or NSW flag can be applied to the SCEV for this
6516           // addition, then compute the SCEV for this addition by itself
6517           // with a separate call to getAddExpr. We need to do that
6518           // instead of pushing the operands of the addition onto AddOps,
6519           // since the flags are only known to apply to this particular
6520           // addition - they may not apply to other additions that can be
6521           // formed with operands from AddOps.
6522           const SCEV *RHS = getSCEV(BO->RHS);
6523           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6524           if (Flags != SCEV::FlagAnyWrap) {
6525             const SCEV *LHS = getSCEV(BO->LHS);
6526             if (BO->Opcode == Instruction::Sub)
6527               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6528             else
6529               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6530             break;
6531           }
6532         }
6533 
6534         if (BO->Opcode == Instruction::Sub)
6535           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6536         else
6537           AddOps.push_back(getSCEV(BO->RHS));
6538 
6539         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6540         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6541                        NewBO->Opcode != Instruction::Sub)) {
6542           AddOps.push_back(getSCEV(BO->LHS));
6543           break;
6544         }
6545         BO = NewBO;
6546       } while (true);
6547 
6548       return getAddExpr(AddOps);
6549     }
6550 
6551     case Instruction::Mul: {
6552       SmallVector<const SCEV *, 4> MulOps;
6553       do {
6554         if (BO->Op) {
6555           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6556             MulOps.push_back(OpSCEV);
6557             break;
6558           }
6559 
6560           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6561           if (Flags != SCEV::FlagAnyWrap) {
6562             MulOps.push_back(
6563                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6564             break;
6565           }
6566         }
6567 
6568         MulOps.push_back(getSCEV(BO->RHS));
6569         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6570         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6571           MulOps.push_back(getSCEV(BO->LHS));
6572           break;
6573         }
6574         BO = NewBO;
6575       } while (true);
6576 
6577       return getMulExpr(MulOps);
6578     }
6579     case Instruction::UDiv:
6580       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6581     case Instruction::URem:
6582       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6583     case Instruction::Sub: {
6584       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6585       if (BO->Op)
6586         Flags = getNoWrapFlagsFromUB(BO->Op);
6587       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6588     }
6589     case Instruction::And:
6590       // For an expression like x&255 that merely masks off the high bits,
6591       // use zext(trunc(x)) as the SCEV expression.
6592       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6593         if (CI->isZero())
6594           return getSCEV(BO->RHS);
6595         if (CI->isMinusOne())
6596           return getSCEV(BO->LHS);
6597         const APInt &A = CI->getValue();
6598 
6599         // Instcombine's ShrinkDemandedConstant may strip bits out of
6600         // constants, obscuring what would otherwise be a low-bits mask.
6601         // Use computeKnownBits to compute what ShrinkDemandedConstant
6602         // knew about to reconstruct a low-bits mask value.
6603         unsigned LZ = A.countLeadingZeros();
6604         unsigned TZ = A.countTrailingZeros();
6605         unsigned BitWidth = A.getBitWidth();
6606         KnownBits Known(BitWidth);
6607         computeKnownBits(BO->LHS, Known, getDataLayout(),
6608                          0, &AC, nullptr, &DT);
6609 
6610         APInt EffectiveMask =
6611             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6612         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6613           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6614           const SCEV *LHS = getSCEV(BO->LHS);
6615           const SCEV *ShiftedLHS = nullptr;
6616           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6617             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6618               // For an expression like (x * 8) & 8, simplify the multiply.
6619               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6620               unsigned GCD = std::min(MulZeros, TZ);
6621               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6622               SmallVector<const SCEV*, 4> MulOps;
6623               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6624               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6625               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6626               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6627             }
6628           }
6629           if (!ShiftedLHS)
6630             ShiftedLHS = getUDivExpr(LHS, MulCount);
6631           return getMulExpr(
6632               getZeroExtendExpr(
6633                   getTruncateExpr(ShiftedLHS,
6634                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6635                   BO->LHS->getType()),
6636               MulCount);
6637         }
6638       }
6639       break;
6640 
6641     case Instruction::Or:
6642       // If the RHS of the Or is a constant, we may have something like:
6643       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6644       // optimizations will transparently handle this case.
6645       //
6646       // In order for this transformation to be safe, the LHS must be of the
6647       // form X*(2^n) and the Or constant must be less than 2^n.
6648       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6649         const SCEV *LHS = getSCEV(BO->LHS);
6650         const APInt &CIVal = CI->getValue();
6651         if (GetMinTrailingZeros(LHS) >=
6652             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6653           // Build a plain add SCEV.
6654           return getAddExpr(LHS, getSCEV(CI),
6655                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6656         }
6657       }
6658       break;
6659 
6660     case Instruction::Xor:
6661       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6662         // If the RHS of xor is -1, then this is a not operation.
6663         if (CI->isMinusOne())
6664           return getNotSCEV(getSCEV(BO->LHS));
6665 
6666         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6667         // This is a variant of the check for xor with -1, and it handles
6668         // the case where instcombine has trimmed non-demanded bits out
6669         // of an xor with -1.
6670         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6671           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6672             if (LBO->getOpcode() == Instruction::And &&
6673                 LCI->getValue() == CI->getValue())
6674               if (const SCEVZeroExtendExpr *Z =
6675                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6676                 Type *UTy = BO->LHS->getType();
6677                 const SCEV *Z0 = Z->getOperand();
6678                 Type *Z0Ty = Z0->getType();
6679                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6680 
6681                 // If C is a low-bits mask, the zero extend is serving to
6682                 // mask off the high bits. Complement the operand and
6683                 // re-apply the zext.
6684                 if (CI->getValue().isMask(Z0TySize))
6685                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6686 
6687                 // If C is a single bit, it may be in the sign-bit position
6688                 // before the zero-extend. In this case, represent the xor
6689                 // using an add, which is equivalent, and re-apply the zext.
6690                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6691                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6692                     Trunc.isSignMask())
6693                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6694                                            UTy);
6695               }
6696       }
6697       break;
6698 
6699     case Instruction::Shl:
6700       // Turn shift left of a constant amount into a multiply.
6701       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6702         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6703 
6704         // If the shift count is not less than the bitwidth, the result of
6705         // the shift is undefined. Don't try to analyze it, because the
6706         // resolution chosen here may differ from the resolution chosen in
6707         // other parts of the compiler.
6708         if (SA->getValue().uge(BitWidth))
6709           break;
6710 
6711         // We can safely preserve the nuw flag in all cases. It's also safe to
6712         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6713         // requires special handling. It can be preserved as long as we're not
6714         // left shifting by bitwidth - 1.
6715         auto Flags = SCEV::FlagAnyWrap;
6716         if (BO->Op) {
6717           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6718           if ((MulFlags & SCEV::FlagNSW) &&
6719               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6720             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6721           if (MulFlags & SCEV::FlagNUW)
6722             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6723         }
6724 
6725         Constant *X = ConstantInt::get(
6726             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6727         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6728       }
6729       break;
6730 
6731     case Instruction::AShr: {
6732       // AShr X, C, where C is a constant.
6733       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6734       if (!CI)
6735         break;
6736 
6737       Type *OuterTy = BO->LHS->getType();
6738       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6739       // If the shift count is not less than the bitwidth, the result of
6740       // the shift is undefined. Don't try to analyze it, because the
6741       // resolution chosen here may differ from the resolution chosen in
6742       // other parts of the compiler.
6743       if (CI->getValue().uge(BitWidth))
6744         break;
6745 
6746       if (CI->isZero())
6747         return getSCEV(BO->LHS); // shift by zero --> noop
6748 
6749       uint64_t AShrAmt = CI->getZExtValue();
6750       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6751 
6752       Operator *L = dyn_cast<Operator>(BO->LHS);
6753       if (L && L->getOpcode() == Instruction::Shl) {
6754         // X = Shl A, n
6755         // Y = AShr X, m
6756         // Both n and m are constant.
6757 
6758         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6759         if (L->getOperand(1) == BO->RHS)
6760           // For a two-shift sext-inreg, i.e. n = m,
6761           // use sext(trunc(x)) as the SCEV expression.
6762           return getSignExtendExpr(
6763               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6764 
6765         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6766         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6767           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6768           if (ShlAmt > AShrAmt) {
6769             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6770             // expression. We already checked that ShlAmt < BitWidth, so
6771             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6772             // ShlAmt - AShrAmt < Amt.
6773             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6774                                             ShlAmt - AShrAmt);
6775             return getSignExtendExpr(
6776                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6777                 getConstant(Mul)), OuterTy);
6778           }
6779         }
6780       }
6781       break;
6782     }
6783     }
6784   }
6785 
6786   switch (U->getOpcode()) {
6787   case Instruction::Trunc:
6788     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6789 
6790   case Instruction::ZExt:
6791     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6792 
6793   case Instruction::SExt:
6794     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6795       // The NSW flag of a subtract does not always survive the conversion to
6796       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6797       // more likely to preserve NSW and allow later AddRec optimisations.
6798       //
6799       // NOTE: This is effectively duplicating this logic from getSignExtend:
6800       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6801       // but by that point the NSW information has potentially been lost.
6802       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6803         Type *Ty = U->getType();
6804         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6805         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6806         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6807       }
6808     }
6809     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6810 
6811   case Instruction::BitCast:
6812     // BitCasts are no-op casts so we just eliminate the cast.
6813     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6814       return getSCEV(U->getOperand(0));
6815     break;
6816 
6817   case Instruction::PtrToInt: {
6818     // Pointer to integer cast is straight-forward, so do model it.
6819     const SCEV *Op = getSCEV(U->getOperand(0));
6820     Type *DstIntTy = U->getType();
6821     // But only if effective SCEV (integer) type is wide enough to represent
6822     // all possible pointer values.
6823     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
6824     if (isa<SCEVCouldNotCompute>(IntOp))
6825       return getUnknown(V);
6826     return IntOp;
6827   }
6828   case Instruction::IntToPtr:
6829     // Just don't deal with inttoptr casts.
6830     return getUnknown(V);
6831 
6832   case Instruction::SDiv:
6833     // If both operands are non-negative, this is just an udiv.
6834     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6835         isKnownNonNegative(getSCEV(U->getOperand(1))))
6836       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6837     break;
6838 
6839   case Instruction::SRem:
6840     // If both operands are non-negative, this is just an urem.
6841     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6842         isKnownNonNegative(getSCEV(U->getOperand(1))))
6843       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6844     break;
6845 
6846   case Instruction::GetElementPtr:
6847     return createNodeForGEP(cast<GEPOperator>(U));
6848 
6849   case Instruction::PHI:
6850     return createNodeForPHI(cast<PHINode>(U));
6851 
6852   case Instruction::Select:
6853     // U can also be a select constant expr, which let fall through.  Since
6854     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6855     // constant expressions cannot have instructions as operands, we'd have
6856     // returned getUnknown for a select constant expressions anyway.
6857     if (isa<Instruction>(U))
6858       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6859                                       U->getOperand(1), U->getOperand(2));
6860     break;
6861 
6862   case Instruction::Call:
6863   case Instruction::Invoke:
6864     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6865       return getSCEV(RV);
6866 
6867     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6868       switch (II->getIntrinsicID()) {
6869       case Intrinsic::abs:
6870         return getAbsExpr(
6871             getSCEV(II->getArgOperand(0)),
6872             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6873       case Intrinsic::umax:
6874         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6875                            getSCEV(II->getArgOperand(1)));
6876       case Intrinsic::umin:
6877         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6878                            getSCEV(II->getArgOperand(1)));
6879       case Intrinsic::smax:
6880         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6881                            getSCEV(II->getArgOperand(1)));
6882       case Intrinsic::smin:
6883         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6884                            getSCEV(II->getArgOperand(1)));
6885       case Intrinsic::usub_sat: {
6886         const SCEV *X = getSCEV(II->getArgOperand(0));
6887         const SCEV *Y = getSCEV(II->getArgOperand(1));
6888         const SCEV *ClampedY = getUMinExpr(X, Y);
6889         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6890       }
6891       case Intrinsic::uadd_sat: {
6892         const SCEV *X = getSCEV(II->getArgOperand(0));
6893         const SCEV *Y = getSCEV(II->getArgOperand(1));
6894         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6895         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6896       }
6897       case Intrinsic::start_loop_iterations:
6898         // A start_loop_iterations is just equivalent to the first operand for
6899         // SCEV purposes.
6900         return getSCEV(II->getArgOperand(0));
6901       default:
6902         break;
6903       }
6904     }
6905     break;
6906   }
6907 
6908   return getUnknown(V);
6909 }
6910 
6911 //===----------------------------------------------------------------------===//
6912 //                   Iteration Count Computation Code
6913 //
6914 
6915 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6916   if (!ExitCount)
6917     return 0;
6918 
6919   ConstantInt *ExitConst = ExitCount->getValue();
6920 
6921   // Guard against huge trip counts.
6922   if (ExitConst->getValue().getActiveBits() > 32)
6923     return 0;
6924 
6925   // In case of integer overflow, this returns 0, which is correct.
6926   return ((unsigned)ExitConst->getZExtValue()) + 1;
6927 }
6928 
6929 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6930   if (BasicBlock *ExitingBB = L->getExitingBlock())
6931     return getSmallConstantTripCount(L, ExitingBB);
6932 
6933   // No trip count information for multiple exits.
6934   return 0;
6935 }
6936 
6937 unsigned
6938 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6939                                            const BasicBlock *ExitingBlock) {
6940   assert(ExitingBlock && "Must pass a non-null exiting block!");
6941   assert(L->isLoopExiting(ExitingBlock) &&
6942          "Exiting block must actually branch out of the loop!");
6943   const SCEVConstant *ExitCount =
6944       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6945   return getConstantTripCount(ExitCount);
6946 }
6947 
6948 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6949   const auto *MaxExitCount =
6950       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6951   return getConstantTripCount(MaxExitCount);
6952 }
6953 
6954 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6955   if (BasicBlock *ExitingBB = L->getExitingBlock())
6956     return getSmallConstantTripMultiple(L, ExitingBB);
6957 
6958   // No trip multiple information for multiple exits.
6959   return 0;
6960 }
6961 
6962 /// Returns the largest constant divisor of the trip count of this loop as a
6963 /// normal unsigned value, if possible. This means that the actual trip count is
6964 /// always a multiple of the returned value (don't forget the trip count could
6965 /// very well be zero as well!).
6966 ///
6967 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6968 /// multiple of a constant (which is also the case if the trip count is simply
6969 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6970 /// if the trip count is very large (>= 2^32).
6971 ///
6972 /// As explained in the comments for getSmallConstantTripCount, this assumes
6973 /// that control exits the loop via ExitingBlock.
6974 unsigned
6975 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6976                                               const BasicBlock *ExitingBlock) {
6977   assert(ExitingBlock && "Must pass a non-null exiting block!");
6978   assert(L->isLoopExiting(ExitingBlock) &&
6979          "Exiting block must actually branch out of the loop!");
6980   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6981   if (ExitCount == getCouldNotCompute())
6982     return 1;
6983 
6984   // Get the trip count from the BE count by adding 1.
6985   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6986 
6987   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6988   if (!TC)
6989     // Attempt to factor more general cases. Returns the greatest power of
6990     // two divisor. If overflow happens, the trip count expression is still
6991     // divisible by the greatest power of 2 divisor returned.
6992     return 1U << std::min((uint32_t)31,
6993                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
6994 
6995   ConstantInt *Result = TC->getValue();
6996 
6997   // Guard against huge trip counts (this requires checking
6998   // for zero to handle the case where the trip count == -1 and the
6999   // addition wraps).
7000   if (!Result || Result->getValue().getActiveBits() > 32 ||
7001       Result->getValue().getActiveBits() == 0)
7002     return 1;
7003 
7004   return (unsigned)Result->getZExtValue();
7005 }
7006 
7007 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7008                                           const BasicBlock *ExitingBlock,
7009                                           ExitCountKind Kind) {
7010   switch (Kind) {
7011   case Exact:
7012   case SymbolicMaximum:
7013     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7014   case ConstantMaximum:
7015     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7016   };
7017   llvm_unreachable("Invalid ExitCountKind!");
7018 }
7019 
7020 const SCEV *
7021 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7022                                                  SCEVUnionPredicate &Preds) {
7023   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7024 }
7025 
7026 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7027                                                    ExitCountKind Kind) {
7028   switch (Kind) {
7029   case Exact:
7030     return getBackedgeTakenInfo(L).getExact(L, this);
7031   case ConstantMaximum:
7032     return getBackedgeTakenInfo(L).getConstantMax(this);
7033   case SymbolicMaximum:
7034     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7035   };
7036   llvm_unreachable("Invalid ExitCountKind!");
7037 }
7038 
7039 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7040   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7041 }
7042 
7043 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7044 static void
7045 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7046   BasicBlock *Header = L->getHeader();
7047 
7048   // Push all Loop-header PHIs onto the Worklist stack.
7049   for (PHINode &PN : Header->phis())
7050     Worklist.push_back(&PN);
7051 }
7052 
7053 const ScalarEvolution::BackedgeTakenInfo &
7054 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7055   auto &BTI = getBackedgeTakenInfo(L);
7056   if (BTI.hasFullInfo())
7057     return BTI;
7058 
7059   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7060 
7061   if (!Pair.second)
7062     return Pair.first->second;
7063 
7064   BackedgeTakenInfo Result =
7065       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7066 
7067   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7068 }
7069 
7070 ScalarEvolution::BackedgeTakenInfo &
7071 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7072   // Initially insert an invalid entry for this loop. If the insertion
7073   // succeeds, proceed to actually compute a backedge-taken count and
7074   // update the value. The temporary CouldNotCompute value tells SCEV
7075   // code elsewhere that it shouldn't attempt to request a new
7076   // backedge-taken count, which could result in infinite recursion.
7077   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7078       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7079   if (!Pair.second)
7080     return Pair.first->second;
7081 
7082   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7083   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7084   // must be cleared in this scope.
7085   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7086 
7087   // In product build, there are no usage of statistic.
7088   (void)NumTripCountsComputed;
7089   (void)NumTripCountsNotComputed;
7090 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7091   const SCEV *BEExact = Result.getExact(L, this);
7092   if (BEExact != getCouldNotCompute()) {
7093     assert(isLoopInvariant(BEExact, L) &&
7094            isLoopInvariant(Result.getConstantMax(this), L) &&
7095            "Computed backedge-taken count isn't loop invariant for loop!");
7096     ++NumTripCountsComputed;
7097   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7098              isa<PHINode>(L->getHeader()->begin())) {
7099     // Only count loops that have phi nodes as not being computable.
7100     ++NumTripCountsNotComputed;
7101   }
7102 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7103 
7104   // Now that we know more about the trip count for this loop, forget any
7105   // existing SCEV values for PHI nodes in this loop since they are only
7106   // conservative estimates made without the benefit of trip count
7107   // information. This is similar to the code in forgetLoop, except that
7108   // it handles SCEVUnknown PHI nodes specially.
7109   if (Result.hasAnyInfo()) {
7110     SmallVector<Instruction *, 16> Worklist;
7111     PushLoopPHIs(L, Worklist);
7112 
7113     SmallPtrSet<Instruction *, 8> Discovered;
7114     while (!Worklist.empty()) {
7115       Instruction *I = Worklist.pop_back_val();
7116 
7117       ValueExprMapType::iterator It =
7118         ValueExprMap.find_as(static_cast<Value *>(I));
7119       if (It != ValueExprMap.end()) {
7120         const SCEV *Old = It->second;
7121 
7122         // SCEVUnknown for a PHI either means that it has an unrecognized
7123         // structure, or it's a PHI that's in the progress of being computed
7124         // by createNodeForPHI.  In the former case, additional loop trip
7125         // count information isn't going to change anything. In the later
7126         // case, createNodeForPHI will perform the necessary updates on its
7127         // own when it gets to that point.
7128         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7129           eraseValueFromMap(It->first);
7130           forgetMemoizedResults(Old);
7131         }
7132         if (PHINode *PN = dyn_cast<PHINode>(I))
7133           ConstantEvolutionLoopExitValue.erase(PN);
7134       }
7135 
7136       // Since we don't need to invalidate anything for correctness and we're
7137       // only invalidating to make SCEV's results more precise, we get to stop
7138       // early to avoid invalidating too much.  This is especially important in
7139       // cases like:
7140       //
7141       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7142       // loop0:
7143       //   %pn0 = phi
7144       //   ...
7145       // loop1:
7146       //   %pn1 = phi
7147       //   ...
7148       //
7149       // where both loop0 and loop1's backedge taken count uses the SCEV
7150       // expression for %v.  If we don't have the early stop below then in cases
7151       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7152       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7153       // count for loop1, effectively nullifying SCEV's trip count cache.
7154       for (auto *U : I->users())
7155         if (auto *I = dyn_cast<Instruction>(U)) {
7156           auto *LoopForUser = LI.getLoopFor(I->getParent());
7157           if (LoopForUser && L->contains(LoopForUser) &&
7158               Discovered.insert(I).second)
7159             Worklist.push_back(I);
7160         }
7161     }
7162   }
7163 
7164   // Re-lookup the insert position, since the call to
7165   // computeBackedgeTakenCount above could result in a
7166   // recusive call to getBackedgeTakenInfo (on a different
7167   // loop), which would invalidate the iterator computed
7168   // earlier.
7169   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7170 }
7171 
7172 void ScalarEvolution::forgetAllLoops() {
7173   // This method is intended to forget all info about loops. It should
7174   // invalidate caches as if the following happened:
7175   // - The trip counts of all loops have changed arbitrarily
7176   // - Every llvm::Value has been updated in place to produce a different
7177   // result.
7178   BackedgeTakenCounts.clear();
7179   PredicatedBackedgeTakenCounts.clear();
7180   LoopPropertiesCache.clear();
7181   ConstantEvolutionLoopExitValue.clear();
7182   ValueExprMap.clear();
7183   ValuesAtScopes.clear();
7184   LoopDispositions.clear();
7185   BlockDispositions.clear();
7186   UnsignedRanges.clear();
7187   SignedRanges.clear();
7188   ExprValueMap.clear();
7189   HasRecMap.clear();
7190   MinTrailingZerosCache.clear();
7191   PredicatedSCEVRewrites.clear();
7192 }
7193 
7194 void ScalarEvolution::forgetLoop(const Loop *L) {
7195   // Drop any stored trip count value.
7196   auto RemoveLoopFromBackedgeMap =
7197       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7198         auto BTCPos = Map.find(L);
7199         if (BTCPos != Map.end()) {
7200           BTCPos->second.clear();
7201           Map.erase(BTCPos);
7202         }
7203       };
7204 
7205   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7206   SmallVector<Instruction *, 32> Worklist;
7207   SmallPtrSet<Instruction *, 16> Visited;
7208 
7209   // Iterate over all the loops and sub-loops to drop SCEV information.
7210   while (!LoopWorklist.empty()) {
7211     auto *CurrL = LoopWorklist.pop_back_val();
7212 
7213     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7214     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7215 
7216     // Drop information about predicated SCEV rewrites for this loop.
7217     for (auto I = PredicatedSCEVRewrites.begin();
7218          I != PredicatedSCEVRewrites.end();) {
7219       std::pair<const SCEV *, const Loop *> Entry = I->first;
7220       if (Entry.second == CurrL)
7221         PredicatedSCEVRewrites.erase(I++);
7222       else
7223         ++I;
7224     }
7225 
7226     auto LoopUsersItr = LoopUsers.find(CurrL);
7227     if (LoopUsersItr != LoopUsers.end()) {
7228       for (auto *S : LoopUsersItr->second)
7229         forgetMemoizedResults(S);
7230       LoopUsers.erase(LoopUsersItr);
7231     }
7232 
7233     // Drop information about expressions based on loop-header PHIs.
7234     PushLoopPHIs(CurrL, Worklist);
7235 
7236     while (!Worklist.empty()) {
7237       Instruction *I = Worklist.pop_back_val();
7238       if (!Visited.insert(I).second)
7239         continue;
7240 
7241       ValueExprMapType::iterator It =
7242           ValueExprMap.find_as(static_cast<Value *>(I));
7243       if (It != ValueExprMap.end()) {
7244         eraseValueFromMap(It->first);
7245         forgetMemoizedResults(It->second);
7246         if (PHINode *PN = dyn_cast<PHINode>(I))
7247           ConstantEvolutionLoopExitValue.erase(PN);
7248       }
7249 
7250       PushDefUseChildren(I, Worklist);
7251     }
7252 
7253     LoopPropertiesCache.erase(CurrL);
7254     // Forget all contained loops too, to avoid dangling entries in the
7255     // ValuesAtScopes map.
7256     LoopWorklist.append(CurrL->begin(), CurrL->end());
7257   }
7258 }
7259 
7260 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7261   while (Loop *Parent = L->getParentLoop())
7262     L = Parent;
7263   forgetLoop(L);
7264 }
7265 
7266 void ScalarEvolution::forgetValue(Value *V) {
7267   Instruction *I = dyn_cast<Instruction>(V);
7268   if (!I) return;
7269 
7270   // Drop information about expressions based on loop-header PHIs.
7271   SmallVector<Instruction *, 16> Worklist;
7272   Worklist.push_back(I);
7273 
7274   SmallPtrSet<Instruction *, 8> Visited;
7275   while (!Worklist.empty()) {
7276     I = Worklist.pop_back_val();
7277     if (!Visited.insert(I).second)
7278       continue;
7279 
7280     ValueExprMapType::iterator It =
7281       ValueExprMap.find_as(static_cast<Value *>(I));
7282     if (It != ValueExprMap.end()) {
7283       eraseValueFromMap(It->first);
7284       forgetMemoizedResults(It->second);
7285       if (PHINode *PN = dyn_cast<PHINode>(I))
7286         ConstantEvolutionLoopExitValue.erase(PN);
7287     }
7288 
7289     PushDefUseChildren(I, Worklist);
7290   }
7291 }
7292 
7293 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7294   LoopDispositions.clear();
7295 }
7296 
7297 /// Get the exact loop backedge taken count considering all loop exits. A
7298 /// computable result can only be returned for loops with all exiting blocks
7299 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7300 /// is never skipped. This is a valid assumption as long as the loop exits via
7301 /// that test. For precise results, it is the caller's responsibility to specify
7302 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7303 const SCEV *
7304 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7305                                              SCEVUnionPredicate *Preds) const {
7306   // If any exits were not computable, the loop is not computable.
7307   if (!isComplete() || ExitNotTaken.empty())
7308     return SE->getCouldNotCompute();
7309 
7310   const BasicBlock *Latch = L->getLoopLatch();
7311   // All exiting blocks we have collected must dominate the only backedge.
7312   if (!Latch)
7313     return SE->getCouldNotCompute();
7314 
7315   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7316   // count is simply a minimum out of all these calculated exit counts.
7317   SmallVector<const SCEV *, 2> Ops;
7318   for (auto &ENT : ExitNotTaken) {
7319     const SCEV *BECount = ENT.ExactNotTaken;
7320     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7321     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7322            "We should only have known counts for exiting blocks that dominate "
7323            "latch!");
7324 
7325     Ops.push_back(BECount);
7326 
7327     if (Preds && !ENT.hasAlwaysTruePredicate())
7328       Preds->add(ENT.Predicate.get());
7329 
7330     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7331            "Predicate should be always true!");
7332   }
7333 
7334   return SE->getUMinFromMismatchedTypes(Ops);
7335 }
7336 
7337 /// Get the exact not taken count for this loop exit.
7338 const SCEV *
7339 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7340                                              ScalarEvolution *SE) const {
7341   for (auto &ENT : ExitNotTaken)
7342     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7343       return ENT.ExactNotTaken;
7344 
7345   return SE->getCouldNotCompute();
7346 }
7347 
7348 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7349     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7350   for (auto &ENT : ExitNotTaken)
7351     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7352       return ENT.MaxNotTaken;
7353 
7354   return SE->getCouldNotCompute();
7355 }
7356 
7357 /// getConstantMax - Get the constant max backedge taken count for the loop.
7358 const SCEV *
7359 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7360   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7361     return !ENT.hasAlwaysTruePredicate();
7362   };
7363 
7364   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7365     return SE->getCouldNotCompute();
7366 
7367   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7368           isa<SCEVConstant>(getConstantMax())) &&
7369          "No point in having a non-constant max backedge taken count!");
7370   return getConstantMax();
7371 }
7372 
7373 const SCEV *
7374 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7375                                                    ScalarEvolution *SE) {
7376   if (!SymbolicMax)
7377     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7378   return SymbolicMax;
7379 }
7380 
7381 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7382     ScalarEvolution *SE) const {
7383   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7384     return !ENT.hasAlwaysTruePredicate();
7385   };
7386   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7387 }
7388 
7389 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7390                                                     ScalarEvolution *SE) const {
7391   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7392       SE->hasOperand(getConstantMax(), S))
7393     return true;
7394 
7395   for (auto &ENT : ExitNotTaken)
7396     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7397         SE->hasOperand(ENT.ExactNotTaken, S))
7398       return true;
7399 
7400   return false;
7401 }
7402 
7403 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7404     : ExactNotTaken(E), MaxNotTaken(E) {
7405   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7406           isa<SCEVConstant>(MaxNotTaken)) &&
7407          "No point in having a non-constant max backedge taken count!");
7408 }
7409 
7410 ScalarEvolution::ExitLimit::ExitLimit(
7411     const SCEV *E, const SCEV *M, bool MaxOrZero,
7412     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7413     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7414   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7415           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7416          "Exact is not allowed to be less precise than Max");
7417   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7418           isa<SCEVConstant>(MaxNotTaken)) &&
7419          "No point in having a non-constant max backedge taken count!");
7420   for (auto *PredSet : PredSetList)
7421     for (auto *P : *PredSet)
7422       addPredicate(P);
7423 }
7424 
7425 ScalarEvolution::ExitLimit::ExitLimit(
7426     const SCEV *E, const SCEV *M, bool MaxOrZero,
7427     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7428     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7429   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7430           isa<SCEVConstant>(MaxNotTaken)) &&
7431          "No point in having a non-constant max backedge taken count!");
7432 }
7433 
7434 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7435                                       bool MaxOrZero)
7436     : ExitLimit(E, M, MaxOrZero, None) {
7437   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7438           isa<SCEVConstant>(MaxNotTaken)) &&
7439          "No point in having a non-constant max backedge taken count!");
7440 }
7441 
7442 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7443 /// computable exit into a persistent ExitNotTakenInfo array.
7444 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7445     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7446     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7447     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7448   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7449 
7450   ExitNotTaken.reserve(ExitCounts.size());
7451   std::transform(
7452       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7453       [&](const EdgeExitInfo &EEI) {
7454         BasicBlock *ExitBB = EEI.first;
7455         const ExitLimit &EL = EEI.second;
7456         if (EL.Predicates.empty())
7457           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7458                                   nullptr);
7459 
7460         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7461         for (auto *Pred : EL.Predicates)
7462           Predicate->add(Pred);
7463 
7464         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7465                                 std::move(Predicate));
7466       });
7467   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7468           isa<SCEVConstant>(ConstantMax)) &&
7469          "No point in having a non-constant max backedge taken count!");
7470 }
7471 
7472 /// Invalidate this result and free the ExitNotTakenInfo array.
7473 void ScalarEvolution::BackedgeTakenInfo::clear() {
7474   ExitNotTaken.clear();
7475 }
7476 
7477 /// Compute the number of times the backedge of the specified loop will execute.
7478 ScalarEvolution::BackedgeTakenInfo
7479 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7480                                            bool AllowPredicates) {
7481   SmallVector<BasicBlock *, 8> ExitingBlocks;
7482   L->getExitingBlocks(ExitingBlocks);
7483 
7484   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7485 
7486   SmallVector<EdgeExitInfo, 4> ExitCounts;
7487   bool CouldComputeBECount = true;
7488   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7489   const SCEV *MustExitMaxBECount = nullptr;
7490   const SCEV *MayExitMaxBECount = nullptr;
7491   bool MustExitMaxOrZero = false;
7492 
7493   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7494   // and compute maxBECount.
7495   // Do a union of all the predicates here.
7496   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7497     BasicBlock *ExitBB = ExitingBlocks[i];
7498 
7499     // We canonicalize untaken exits to br (constant), ignore them so that
7500     // proving an exit untaken doesn't negatively impact our ability to reason
7501     // about the loop as whole.
7502     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7503       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7504         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7505         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7506           continue;
7507       }
7508 
7509     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7510 
7511     assert((AllowPredicates || EL.Predicates.empty()) &&
7512            "Predicated exit limit when predicates are not allowed!");
7513 
7514     // 1. For each exit that can be computed, add an entry to ExitCounts.
7515     // CouldComputeBECount is true only if all exits can be computed.
7516     if (EL.ExactNotTaken == getCouldNotCompute())
7517       // We couldn't compute an exact value for this exit, so
7518       // we won't be able to compute an exact value for the loop.
7519       CouldComputeBECount = false;
7520     else
7521       ExitCounts.emplace_back(ExitBB, EL);
7522 
7523     // 2. Derive the loop's MaxBECount from each exit's max number of
7524     // non-exiting iterations. Partition the loop exits into two kinds:
7525     // LoopMustExits and LoopMayExits.
7526     //
7527     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7528     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7529     // MaxBECount is the minimum EL.MaxNotTaken of computable
7530     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7531     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7532     // computable EL.MaxNotTaken.
7533     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7534         DT.dominates(ExitBB, Latch)) {
7535       if (!MustExitMaxBECount) {
7536         MustExitMaxBECount = EL.MaxNotTaken;
7537         MustExitMaxOrZero = EL.MaxOrZero;
7538       } else {
7539         MustExitMaxBECount =
7540             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7541       }
7542     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7543       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7544         MayExitMaxBECount = EL.MaxNotTaken;
7545       else {
7546         MayExitMaxBECount =
7547             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7548       }
7549     }
7550   }
7551   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7552     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7553   // The loop backedge will be taken the maximum or zero times if there's
7554   // a single exit that must be taken the maximum or zero times.
7555   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7556   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7557                            MaxBECount, MaxOrZero);
7558 }
7559 
7560 ScalarEvolution::ExitLimit
7561 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7562                                       bool AllowPredicates) {
7563   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7564   // If our exiting block does not dominate the latch, then its connection with
7565   // loop's exit limit may be far from trivial.
7566   const BasicBlock *Latch = L->getLoopLatch();
7567   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7568     return getCouldNotCompute();
7569 
7570   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7571   Instruction *Term = ExitingBlock->getTerminator();
7572   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7573     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7574     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7575     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7576            "It should have one successor in loop and one exit block!");
7577     // Proceed to the next level to examine the exit condition expression.
7578     return computeExitLimitFromCond(
7579         L, BI->getCondition(), ExitIfTrue,
7580         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7581   }
7582 
7583   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7584     // For switch, make sure that there is a single exit from the loop.
7585     BasicBlock *Exit = nullptr;
7586     for (auto *SBB : successors(ExitingBlock))
7587       if (!L->contains(SBB)) {
7588         if (Exit) // Multiple exit successors.
7589           return getCouldNotCompute();
7590         Exit = SBB;
7591       }
7592     assert(Exit && "Exiting block must have at least one exit");
7593     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7594                                                 /*ControlsExit=*/IsOnlyExit);
7595   }
7596 
7597   return getCouldNotCompute();
7598 }
7599 
7600 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7601     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7602     bool ControlsExit, bool AllowPredicates) {
7603   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7604   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7605                                         ControlsExit, AllowPredicates);
7606 }
7607 
7608 Optional<ScalarEvolution::ExitLimit>
7609 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7610                                       bool ExitIfTrue, bool ControlsExit,
7611                                       bool AllowPredicates) {
7612   (void)this->L;
7613   (void)this->ExitIfTrue;
7614   (void)this->AllowPredicates;
7615 
7616   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7617          this->AllowPredicates == AllowPredicates &&
7618          "Variance in assumed invariant key components!");
7619   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7620   if (Itr == TripCountMap.end())
7621     return None;
7622   return Itr->second;
7623 }
7624 
7625 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7626                                              bool ExitIfTrue,
7627                                              bool ControlsExit,
7628                                              bool AllowPredicates,
7629                                              const ExitLimit &EL) {
7630   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7631          this->AllowPredicates == AllowPredicates &&
7632          "Variance in assumed invariant key components!");
7633 
7634   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7635   assert(InsertResult.second && "Expected successful insertion!");
7636   (void)InsertResult;
7637   (void)ExitIfTrue;
7638 }
7639 
7640 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7641     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7642     bool ControlsExit, bool AllowPredicates) {
7643 
7644   if (auto MaybeEL =
7645           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7646     return *MaybeEL;
7647 
7648   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7649                                               ControlsExit, AllowPredicates);
7650   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7651   return EL;
7652 }
7653 
7654 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7655     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7656     bool ControlsExit, bool AllowPredicates) {
7657   // Handle BinOp conditions (And, Or).
7658   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7659           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7660     return *LimitFromBinOp;
7661 
7662   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7663   // Proceed to the next level to examine the icmp.
7664   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7665     ExitLimit EL =
7666         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7667     if (EL.hasFullInfo() || !AllowPredicates)
7668       return EL;
7669 
7670     // Try again, but use SCEV predicates this time.
7671     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7672                                     /*AllowPredicates=*/true);
7673   }
7674 
7675   // Check for a constant condition. These are normally stripped out by
7676   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7677   // preserve the CFG and is temporarily leaving constant conditions
7678   // in place.
7679   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7680     if (ExitIfTrue == !CI->getZExtValue())
7681       // The backedge is always taken.
7682       return getCouldNotCompute();
7683     else
7684       // The backedge is never taken.
7685       return getZero(CI->getType());
7686   }
7687 
7688   // If it's not an integer or pointer comparison then compute it the hard way.
7689   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7690 }
7691 
7692 Optional<ScalarEvolution::ExitLimit>
7693 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7694     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7695     bool ControlsExit, bool AllowPredicates) {
7696   // Check if the controlling expression for this loop is an And or Or.
7697   Value *Op0, *Op1;
7698   bool IsAnd = false;
7699   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7700     IsAnd = true;
7701   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7702     IsAnd = false;
7703   else
7704     return None;
7705 
7706   // EitherMayExit is true in these two cases:
7707   //   br (and Op0 Op1), loop, exit
7708   //   br (or  Op0 Op1), exit, loop
7709   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7710   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7711                                                  ControlsExit && !EitherMayExit,
7712                                                  AllowPredicates);
7713   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7714                                                  ControlsExit && !EitherMayExit,
7715                                                  AllowPredicates);
7716 
7717   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7718   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7719   if (isa<ConstantInt>(Op1))
7720     return Op1 == NeutralElement ? EL0 : EL1;
7721   if (isa<ConstantInt>(Op0))
7722     return Op0 == NeutralElement ? EL1 : EL0;
7723 
7724   const SCEV *BECount = getCouldNotCompute();
7725   const SCEV *MaxBECount = getCouldNotCompute();
7726   if (EitherMayExit) {
7727     // Both conditions must be same for the loop to continue executing.
7728     // Choose the less conservative count.
7729     // If ExitCond is a short-circuit form (select), using
7730     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7731     // To see the detailed examples, please see
7732     // test/Analysis/ScalarEvolution/exit-count-select.ll
7733     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7734     if (!PoisonSafe)
7735       // Even if ExitCond is select, we can safely derive BECount using both
7736       // EL0 and EL1 in these cases:
7737       // (1) EL0.ExactNotTaken is non-zero
7738       // (2) EL1.ExactNotTaken is non-poison
7739       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7740       //     it cannot be umin(0, ..))
7741       // The PoisonSafe assignment below is simplified and the assertion after
7742       // BECount calculation fully guarantees the condition (3).
7743       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7744                    isa<SCEVConstant>(EL1.ExactNotTaken);
7745     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7746         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7747       BECount =
7748           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7749 
7750       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7751       // it should have been simplified to zero (see the condition (3) above)
7752       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7753              BECount->isZero());
7754     }
7755     if (EL0.MaxNotTaken == getCouldNotCompute())
7756       MaxBECount = EL1.MaxNotTaken;
7757     else if (EL1.MaxNotTaken == getCouldNotCompute())
7758       MaxBECount = EL0.MaxNotTaken;
7759     else
7760       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7761   } else {
7762     // Both conditions must be same at the same time for the loop to exit.
7763     // For now, be conservative.
7764     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7765       BECount = EL0.ExactNotTaken;
7766   }
7767 
7768   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7769   // to be more aggressive when computing BECount than when computing
7770   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7771   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7772   // to not.
7773   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7774       !isa<SCEVCouldNotCompute>(BECount))
7775     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7776 
7777   return ExitLimit(BECount, MaxBECount, false,
7778                    { &EL0.Predicates, &EL1.Predicates });
7779 }
7780 
7781 ScalarEvolution::ExitLimit
7782 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7783                                           ICmpInst *ExitCond,
7784                                           bool ExitIfTrue,
7785                                           bool ControlsExit,
7786                                           bool AllowPredicates) {
7787   // If the condition was exit on true, convert the condition to exit on false
7788   ICmpInst::Predicate Pred;
7789   if (!ExitIfTrue)
7790     Pred = ExitCond->getPredicate();
7791   else
7792     Pred = ExitCond->getInversePredicate();
7793   const ICmpInst::Predicate OriginalPred = Pred;
7794 
7795   // Handle common loops like: for (X = "string"; *X; ++X)
7796   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7797     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7798       ExitLimit ItCnt =
7799         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7800       if (ItCnt.hasAnyInfo())
7801         return ItCnt;
7802     }
7803 
7804   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7805   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7806 
7807   // Try to evaluate any dependencies out of the loop.
7808   LHS = getSCEVAtScope(LHS, L);
7809   RHS = getSCEVAtScope(RHS, L);
7810 
7811   // At this point, we would like to compute how many iterations of the
7812   // loop the predicate will return true for these inputs.
7813   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7814     // If there is a loop-invariant, force it into the RHS.
7815     std::swap(LHS, RHS);
7816     Pred = ICmpInst::getSwappedPredicate(Pred);
7817   }
7818 
7819   // Simplify the operands before analyzing them.
7820   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7821 
7822   // If we have a comparison of a chrec against a constant, try to use value
7823   // ranges to answer this query.
7824   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7825     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7826       if (AddRec->getLoop() == L) {
7827         // Form the constant range.
7828         ConstantRange CompRange =
7829             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7830 
7831         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7832         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7833       }
7834 
7835   switch (Pred) {
7836   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7837     // Convert to: while (X-Y != 0)
7838     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7839                                 AllowPredicates);
7840     if (EL.hasAnyInfo()) return EL;
7841     break;
7842   }
7843   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7844     // Convert to: while (X-Y == 0)
7845     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7846     if (EL.hasAnyInfo()) return EL;
7847     break;
7848   }
7849   case ICmpInst::ICMP_SLT:
7850   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7851     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7852     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7853                                     AllowPredicates);
7854     if (EL.hasAnyInfo()) return EL;
7855     break;
7856   }
7857   case ICmpInst::ICMP_SGT:
7858   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7859     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7860     ExitLimit EL =
7861         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7862                             AllowPredicates);
7863     if (EL.hasAnyInfo()) return EL;
7864     break;
7865   }
7866   default:
7867     break;
7868   }
7869 
7870   auto *ExhaustiveCount =
7871       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7872 
7873   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7874     return ExhaustiveCount;
7875 
7876   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7877                                       ExitCond->getOperand(1), L, OriginalPred);
7878 }
7879 
7880 ScalarEvolution::ExitLimit
7881 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7882                                                       SwitchInst *Switch,
7883                                                       BasicBlock *ExitingBlock,
7884                                                       bool ControlsExit) {
7885   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7886 
7887   // Give up if the exit is the default dest of a switch.
7888   if (Switch->getDefaultDest() == ExitingBlock)
7889     return getCouldNotCompute();
7890 
7891   assert(L->contains(Switch->getDefaultDest()) &&
7892          "Default case must not exit the loop!");
7893   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7894   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7895 
7896   // while (X != Y) --> while (X-Y != 0)
7897   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7898   if (EL.hasAnyInfo())
7899     return EL;
7900 
7901   return getCouldNotCompute();
7902 }
7903 
7904 static ConstantInt *
7905 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7906                                 ScalarEvolution &SE) {
7907   const SCEV *InVal = SE.getConstant(C);
7908   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7909   assert(isa<SCEVConstant>(Val) &&
7910          "Evaluation of SCEV at constant didn't fold correctly?");
7911   return cast<SCEVConstant>(Val)->getValue();
7912 }
7913 
7914 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7915 /// compute the backedge execution count.
7916 ScalarEvolution::ExitLimit
7917 ScalarEvolution::computeLoadConstantCompareExitLimit(
7918   LoadInst *LI,
7919   Constant *RHS,
7920   const Loop *L,
7921   ICmpInst::Predicate predicate) {
7922   if (LI->isVolatile()) return getCouldNotCompute();
7923 
7924   // Check to see if the loaded pointer is a getelementptr of a global.
7925   // TODO: Use SCEV instead of manually grubbing with GEPs.
7926   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7927   if (!GEP) return getCouldNotCompute();
7928 
7929   // Make sure that it is really a constant global we are gepping, with an
7930   // initializer, and make sure the first IDX is really 0.
7931   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7932   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7933       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7934       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7935     return getCouldNotCompute();
7936 
7937   // Okay, we allow one non-constant index into the GEP instruction.
7938   Value *VarIdx = nullptr;
7939   std::vector<Constant*> Indexes;
7940   unsigned VarIdxNum = 0;
7941   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7942     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7943       Indexes.push_back(CI);
7944     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7945       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7946       VarIdx = GEP->getOperand(i);
7947       VarIdxNum = i-2;
7948       Indexes.push_back(nullptr);
7949     }
7950 
7951   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7952   if (!VarIdx)
7953     return getCouldNotCompute();
7954 
7955   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7956   // Check to see if X is a loop variant variable value now.
7957   const SCEV *Idx = getSCEV(VarIdx);
7958   Idx = getSCEVAtScope(Idx, L);
7959 
7960   // We can only recognize very limited forms of loop index expressions, in
7961   // particular, only affine AddRec's like {C1,+,C2}<L>.
7962   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7963   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
7964       isLoopInvariant(IdxExpr, L) ||
7965       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7966       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7967     return getCouldNotCompute();
7968 
7969   unsigned MaxSteps = MaxBruteForceIterations;
7970   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7971     ConstantInt *ItCst = ConstantInt::get(
7972                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7973     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7974 
7975     // Form the GEP offset.
7976     Indexes[VarIdxNum] = Val;
7977 
7978     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7979                                                          Indexes);
7980     if (!Result) break;  // Cannot compute!
7981 
7982     // Evaluate the condition for this iteration.
7983     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7984     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7985     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7986       ++NumArrayLenItCounts;
7987       return getConstant(ItCst);   // Found terminating iteration!
7988     }
7989   }
7990   return getCouldNotCompute();
7991 }
7992 
7993 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7994     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7995   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7996   if (!RHS)
7997     return getCouldNotCompute();
7998 
7999   const BasicBlock *Latch = L->getLoopLatch();
8000   if (!Latch)
8001     return getCouldNotCompute();
8002 
8003   const BasicBlock *Predecessor = L->getLoopPredecessor();
8004   if (!Predecessor)
8005     return getCouldNotCompute();
8006 
8007   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8008   // Return LHS in OutLHS and shift_opt in OutOpCode.
8009   auto MatchPositiveShift =
8010       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8011 
8012     using namespace PatternMatch;
8013 
8014     ConstantInt *ShiftAmt;
8015     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8016       OutOpCode = Instruction::LShr;
8017     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8018       OutOpCode = Instruction::AShr;
8019     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8020       OutOpCode = Instruction::Shl;
8021     else
8022       return false;
8023 
8024     return ShiftAmt->getValue().isStrictlyPositive();
8025   };
8026 
8027   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8028   //
8029   // loop:
8030   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8031   //   %iv.shifted = lshr i32 %iv, <positive constant>
8032   //
8033   // Return true on a successful match.  Return the corresponding PHI node (%iv
8034   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8035   auto MatchShiftRecurrence =
8036       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8037     Optional<Instruction::BinaryOps> PostShiftOpCode;
8038 
8039     {
8040       Instruction::BinaryOps OpC;
8041       Value *V;
8042 
8043       // If we encounter a shift instruction, "peel off" the shift operation,
8044       // and remember that we did so.  Later when we inspect %iv's backedge
8045       // value, we will make sure that the backedge value uses the same
8046       // operation.
8047       //
8048       // Note: the peeled shift operation does not have to be the same
8049       // instruction as the one feeding into the PHI's backedge value.  We only
8050       // really care about it being the same *kind* of shift instruction --
8051       // that's all that is required for our later inferences to hold.
8052       if (MatchPositiveShift(LHS, V, OpC)) {
8053         PostShiftOpCode = OpC;
8054         LHS = V;
8055       }
8056     }
8057 
8058     PNOut = dyn_cast<PHINode>(LHS);
8059     if (!PNOut || PNOut->getParent() != L->getHeader())
8060       return false;
8061 
8062     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8063     Value *OpLHS;
8064 
8065     return
8066         // The backedge value for the PHI node must be a shift by a positive
8067         // amount
8068         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8069 
8070         // of the PHI node itself
8071         OpLHS == PNOut &&
8072 
8073         // and the kind of shift should be match the kind of shift we peeled
8074         // off, if any.
8075         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8076   };
8077 
8078   PHINode *PN;
8079   Instruction::BinaryOps OpCode;
8080   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8081     return getCouldNotCompute();
8082 
8083   const DataLayout &DL = getDataLayout();
8084 
8085   // The key rationale for this optimization is that for some kinds of shift
8086   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8087   // within a finite number of iterations.  If the condition guarding the
8088   // backedge (in the sense that the backedge is taken if the condition is true)
8089   // is false for the value the shift recurrence stabilizes to, then we know
8090   // that the backedge is taken only a finite number of times.
8091 
8092   ConstantInt *StableValue = nullptr;
8093   switch (OpCode) {
8094   default:
8095     llvm_unreachable("Impossible case!");
8096 
8097   case Instruction::AShr: {
8098     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8099     // bitwidth(K) iterations.
8100     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8101     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8102                                        Predecessor->getTerminator(), &DT);
8103     auto *Ty = cast<IntegerType>(RHS->getType());
8104     if (Known.isNonNegative())
8105       StableValue = ConstantInt::get(Ty, 0);
8106     else if (Known.isNegative())
8107       StableValue = ConstantInt::get(Ty, -1, true);
8108     else
8109       return getCouldNotCompute();
8110 
8111     break;
8112   }
8113   case Instruction::LShr:
8114   case Instruction::Shl:
8115     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8116     // stabilize to 0 in at most bitwidth(K) iterations.
8117     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8118     break;
8119   }
8120 
8121   auto *Result =
8122       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8123   assert(Result->getType()->isIntegerTy(1) &&
8124          "Otherwise cannot be an operand to a branch instruction");
8125 
8126   if (Result->isZeroValue()) {
8127     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8128     const SCEV *UpperBound =
8129         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8130     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8131   }
8132 
8133   return getCouldNotCompute();
8134 }
8135 
8136 /// Return true if we can constant fold an instruction of the specified type,
8137 /// assuming that all operands were constants.
8138 static bool CanConstantFold(const Instruction *I) {
8139   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8140       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8141       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8142     return true;
8143 
8144   if (const CallInst *CI = dyn_cast<CallInst>(I))
8145     if (const Function *F = CI->getCalledFunction())
8146       return canConstantFoldCallTo(CI, F);
8147   return false;
8148 }
8149 
8150 /// Determine whether this instruction can constant evolve within this loop
8151 /// assuming its operands can all constant evolve.
8152 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8153   // An instruction outside of the loop can't be derived from a loop PHI.
8154   if (!L->contains(I)) return false;
8155 
8156   if (isa<PHINode>(I)) {
8157     // We don't currently keep track of the control flow needed to evaluate
8158     // PHIs, so we cannot handle PHIs inside of loops.
8159     return L->getHeader() == I->getParent();
8160   }
8161 
8162   // If we won't be able to constant fold this expression even if the operands
8163   // are constants, bail early.
8164   return CanConstantFold(I);
8165 }
8166 
8167 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8168 /// recursing through each instruction operand until reaching a loop header phi.
8169 static PHINode *
8170 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8171                                DenseMap<Instruction *, PHINode *> &PHIMap,
8172                                unsigned Depth) {
8173   if (Depth > MaxConstantEvolvingDepth)
8174     return nullptr;
8175 
8176   // Otherwise, we can evaluate this instruction if all of its operands are
8177   // constant or derived from a PHI node themselves.
8178   PHINode *PHI = nullptr;
8179   for (Value *Op : UseInst->operands()) {
8180     if (isa<Constant>(Op)) continue;
8181 
8182     Instruction *OpInst = dyn_cast<Instruction>(Op);
8183     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8184 
8185     PHINode *P = dyn_cast<PHINode>(OpInst);
8186     if (!P)
8187       // If this operand is already visited, reuse the prior result.
8188       // We may have P != PHI if this is the deepest point at which the
8189       // inconsistent paths meet.
8190       P = PHIMap.lookup(OpInst);
8191     if (!P) {
8192       // Recurse and memoize the results, whether a phi is found or not.
8193       // This recursive call invalidates pointers into PHIMap.
8194       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8195       PHIMap[OpInst] = P;
8196     }
8197     if (!P)
8198       return nullptr;  // Not evolving from PHI
8199     if (PHI && PHI != P)
8200       return nullptr;  // Evolving from multiple different PHIs.
8201     PHI = P;
8202   }
8203   // This is a expression evolving from a constant PHI!
8204   return PHI;
8205 }
8206 
8207 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8208 /// in the loop that V is derived from.  We allow arbitrary operations along the
8209 /// way, but the operands of an operation must either be constants or a value
8210 /// derived from a constant PHI.  If this expression does not fit with these
8211 /// constraints, return null.
8212 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8213   Instruction *I = dyn_cast<Instruction>(V);
8214   if (!I || !canConstantEvolve(I, L)) return nullptr;
8215 
8216   if (PHINode *PN = dyn_cast<PHINode>(I))
8217     return PN;
8218 
8219   // Record non-constant instructions contained by the loop.
8220   DenseMap<Instruction *, PHINode *> PHIMap;
8221   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8222 }
8223 
8224 /// EvaluateExpression - Given an expression that passes the
8225 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8226 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8227 /// reason, return null.
8228 static Constant *EvaluateExpression(Value *V, const Loop *L,
8229                                     DenseMap<Instruction *, Constant *> &Vals,
8230                                     const DataLayout &DL,
8231                                     const TargetLibraryInfo *TLI) {
8232   // Convenient constant check, but redundant for recursive calls.
8233   if (Constant *C = dyn_cast<Constant>(V)) return C;
8234   Instruction *I = dyn_cast<Instruction>(V);
8235   if (!I) return nullptr;
8236 
8237   if (Constant *C = Vals.lookup(I)) return C;
8238 
8239   // An instruction inside the loop depends on a value outside the loop that we
8240   // weren't given a mapping for, or a value such as a call inside the loop.
8241   if (!canConstantEvolve(I, L)) return nullptr;
8242 
8243   // An unmapped PHI can be due to a branch or another loop inside this loop,
8244   // or due to this not being the initial iteration through a loop where we
8245   // couldn't compute the evolution of this particular PHI last time.
8246   if (isa<PHINode>(I)) return nullptr;
8247 
8248   std::vector<Constant*> Operands(I->getNumOperands());
8249 
8250   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8251     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8252     if (!Operand) {
8253       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8254       if (!Operands[i]) return nullptr;
8255       continue;
8256     }
8257     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8258     Vals[Operand] = C;
8259     if (!C) return nullptr;
8260     Operands[i] = C;
8261   }
8262 
8263   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8264     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8265                                            Operands[1], DL, TLI);
8266   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8267     if (!LI->isVolatile())
8268       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8269   }
8270   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8271 }
8272 
8273 
8274 // If every incoming value to PN except the one for BB is a specific Constant,
8275 // return that, else return nullptr.
8276 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8277   Constant *IncomingVal = nullptr;
8278 
8279   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8280     if (PN->getIncomingBlock(i) == BB)
8281       continue;
8282 
8283     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8284     if (!CurrentVal)
8285       return nullptr;
8286 
8287     if (IncomingVal != CurrentVal) {
8288       if (IncomingVal)
8289         return nullptr;
8290       IncomingVal = CurrentVal;
8291     }
8292   }
8293 
8294   return IncomingVal;
8295 }
8296 
8297 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8298 /// in the header of its containing loop, we know the loop executes a
8299 /// constant number of times, and the PHI node is just a recurrence
8300 /// involving constants, fold it.
8301 Constant *
8302 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8303                                                    const APInt &BEs,
8304                                                    const Loop *L) {
8305   auto I = ConstantEvolutionLoopExitValue.find(PN);
8306   if (I != ConstantEvolutionLoopExitValue.end())
8307     return I->second;
8308 
8309   if (BEs.ugt(MaxBruteForceIterations))
8310     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8311 
8312   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8313 
8314   DenseMap<Instruction *, Constant *> CurrentIterVals;
8315   BasicBlock *Header = L->getHeader();
8316   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8317 
8318   BasicBlock *Latch = L->getLoopLatch();
8319   if (!Latch)
8320     return nullptr;
8321 
8322   for (PHINode &PHI : Header->phis()) {
8323     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8324       CurrentIterVals[&PHI] = StartCST;
8325   }
8326   if (!CurrentIterVals.count(PN))
8327     return RetVal = nullptr;
8328 
8329   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8330 
8331   // Execute the loop symbolically to determine the exit value.
8332   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8333          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8334 
8335   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8336   unsigned IterationNum = 0;
8337   const DataLayout &DL = getDataLayout();
8338   for (; ; ++IterationNum) {
8339     if (IterationNum == NumIterations)
8340       return RetVal = CurrentIterVals[PN];  // Got exit value!
8341 
8342     // Compute the value of the PHIs for the next iteration.
8343     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8344     DenseMap<Instruction *, Constant *> NextIterVals;
8345     Constant *NextPHI =
8346         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8347     if (!NextPHI)
8348       return nullptr;        // Couldn't evaluate!
8349     NextIterVals[PN] = NextPHI;
8350 
8351     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8352 
8353     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8354     // cease to be able to evaluate one of them or if they stop evolving,
8355     // because that doesn't necessarily prevent us from computing PN.
8356     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8357     for (const auto &I : CurrentIterVals) {
8358       PHINode *PHI = dyn_cast<PHINode>(I.first);
8359       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8360       PHIsToCompute.emplace_back(PHI, I.second);
8361     }
8362     // We use two distinct loops because EvaluateExpression may invalidate any
8363     // iterators into CurrentIterVals.
8364     for (const auto &I : PHIsToCompute) {
8365       PHINode *PHI = I.first;
8366       Constant *&NextPHI = NextIterVals[PHI];
8367       if (!NextPHI) {   // Not already computed.
8368         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8369         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8370       }
8371       if (NextPHI != I.second)
8372         StoppedEvolving = false;
8373     }
8374 
8375     // If all entries in CurrentIterVals == NextIterVals then we can stop
8376     // iterating, the loop can't continue to change.
8377     if (StoppedEvolving)
8378       return RetVal = CurrentIterVals[PN];
8379 
8380     CurrentIterVals.swap(NextIterVals);
8381   }
8382 }
8383 
8384 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8385                                                           Value *Cond,
8386                                                           bool ExitWhen) {
8387   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8388   if (!PN) return getCouldNotCompute();
8389 
8390   // If the loop is canonicalized, the PHI will have exactly two entries.
8391   // That's the only form we support here.
8392   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8393 
8394   DenseMap<Instruction *, Constant *> CurrentIterVals;
8395   BasicBlock *Header = L->getHeader();
8396   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8397 
8398   BasicBlock *Latch = L->getLoopLatch();
8399   assert(Latch && "Should follow from NumIncomingValues == 2!");
8400 
8401   for (PHINode &PHI : Header->phis()) {
8402     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8403       CurrentIterVals[&PHI] = StartCST;
8404   }
8405   if (!CurrentIterVals.count(PN))
8406     return getCouldNotCompute();
8407 
8408   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8409   // the loop symbolically to determine when the condition gets a value of
8410   // "ExitWhen".
8411   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8412   const DataLayout &DL = getDataLayout();
8413   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8414     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8415         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8416 
8417     // Couldn't symbolically evaluate.
8418     if (!CondVal) return getCouldNotCompute();
8419 
8420     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8421       ++NumBruteForceTripCountsComputed;
8422       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8423     }
8424 
8425     // Update all the PHI nodes for the next iteration.
8426     DenseMap<Instruction *, Constant *> NextIterVals;
8427 
8428     // Create a list of which PHIs we need to compute. We want to do this before
8429     // calling EvaluateExpression on them because that may invalidate iterators
8430     // into CurrentIterVals.
8431     SmallVector<PHINode *, 8> PHIsToCompute;
8432     for (const auto &I : CurrentIterVals) {
8433       PHINode *PHI = dyn_cast<PHINode>(I.first);
8434       if (!PHI || PHI->getParent() != Header) continue;
8435       PHIsToCompute.push_back(PHI);
8436     }
8437     for (PHINode *PHI : PHIsToCompute) {
8438       Constant *&NextPHI = NextIterVals[PHI];
8439       if (NextPHI) continue;    // Already computed!
8440 
8441       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8442       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8443     }
8444     CurrentIterVals.swap(NextIterVals);
8445   }
8446 
8447   // Too many iterations were needed to evaluate.
8448   return getCouldNotCompute();
8449 }
8450 
8451 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8452   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8453       ValuesAtScopes[V];
8454   // Check to see if we've folded this expression at this loop before.
8455   for (auto &LS : Values)
8456     if (LS.first == L)
8457       return LS.second ? LS.second : V;
8458 
8459   Values.emplace_back(L, nullptr);
8460 
8461   // Otherwise compute it.
8462   const SCEV *C = computeSCEVAtScope(V, L);
8463   for (auto &LS : reverse(ValuesAtScopes[V]))
8464     if (LS.first == L) {
8465       LS.second = C;
8466       break;
8467     }
8468   return C;
8469 }
8470 
8471 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8472 /// will return Constants for objects which aren't represented by a
8473 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8474 /// Returns NULL if the SCEV isn't representable as a Constant.
8475 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8476   switch (V->getSCEVType()) {
8477   case scCouldNotCompute:
8478   case scAddRecExpr:
8479     return nullptr;
8480   case scConstant:
8481     return cast<SCEVConstant>(V)->getValue();
8482   case scUnknown:
8483     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8484   case scSignExtend: {
8485     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8486     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8487       return ConstantExpr::getSExt(CastOp, SS->getType());
8488     return nullptr;
8489   }
8490   case scZeroExtend: {
8491     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8492     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8493       return ConstantExpr::getZExt(CastOp, SZ->getType());
8494     return nullptr;
8495   }
8496   case scPtrToInt: {
8497     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8498     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8499       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8500 
8501     return nullptr;
8502   }
8503   case scTruncate: {
8504     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8505     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8506       return ConstantExpr::getTrunc(CastOp, ST->getType());
8507     return nullptr;
8508   }
8509   case scAddExpr: {
8510     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8511     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8512       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8513         unsigned AS = PTy->getAddressSpace();
8514         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8515         C = ConstantExpr::getBitCast(C, DestPtrTy);
8516       }
8517       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8518         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8519         if (!C2)
8520           return nullptr;
8521 
8522         // First pointer!
8523         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8524           unsigned AS = C2->getType()->getPointerAddressSpace();
8525           std::swap(C, C2);
8526           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8527           // The offsets have been converted to bytes.  We can add bytes to an
8528           // i8* by GEP with the byte count in the first index.
8529           C = ConstantExpr::getBitCast(C, DestPtrTy);
8530         }
8531 
8532         // Don't bother trying to sum two pointers. We probably can't
8533         // statically compute a load that results from it anyway.
8534         if (C2->getType()->isPointerTy())
8535           return nullptr;
8536 
8537         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8538           if (PTy->getElementType()->isStructTy())
8539             C2 = ConstantExpr::getIntegerCast(
8540                 C2, Type::getInt32Ty(C->getContext()), true);
8541           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8542         } else
8543           C = ConstantExpr::getAdd(C, C2);
8544       }
8545       return C;
8546     }
8547     return nullptr;
8548   }
8549   case scMulExpr: {
8550     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8551     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8552       // Don't bother with pointers at all.
8553       if (C->getType()->isPointerTy())
8554         return nullptr;
8555       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8556         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8557         if (!C2 || C2->getType()->isPointerTy())
8558           return nullptr;
8559         C = ConstantExpr::getMul(C, C2);
8560       }
8561       return C;
8562     }
8563     return nullptr;
8564   }
8565   case scUDivExpr: {
8566     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8567     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8568       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8569         if (LHS->getType() == RHS->getType())
8570           return ConstantExpr::getUDiv(LHS, RHS);
8571     return nullptr;
8572   }
8573   case scSMaxExpr:
8574   case scUMaxExpr:
8575   case scSMinExpr:
8576   case scUMinExpr:
8577     return nullptr; // TODO: smax, umax, smin, umax.
8578   }
8579   llvm_unreachable("Unknown SCEV kind!");
8580 }
8581 
8582 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8583   if (isa<SCEVConstant>(V)) return V;
8584 
8585   // If this instruction is evolved from a constant-evolving PHI, compute the
8586   // exit value from the loop without using SCEVs.
8587   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8588     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8589       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8590         const Loop *CurrLoop = this->LI[I->getParent()];
8591         // Looking for loop exit value.
8592         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8593             PN->getParent() == CurrLoop->getHeader()) {
8594           // Okay, there is no closed form solution for the PHI node.  Check
8595           // to see if the loop that contains it has a known backedge-taken
8596           // count.  If so, we may be able to force computation of the exit
8597           // value.
8598           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8599           // This trivial case can show up in some degenerate cases where
8600           // the incoming IR has not yet been fully simplified.
8601           if (BackedgeTakenCount->isZero()) {
8602             Value *InitValue = nullptr;
8603             bool MultipleInitValues = false;
8604             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8605               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8606                 if (!InitValue)
8607                   InitValue = PN->getIncomingValue(i);
8608                 else if (InitValue != PN->getIncomingValue(i)) {
8609                   MultipleInitValues = true;
8610                   break;
8611                 }
8612               }
8613             }
8614             if (!MultipleInitValues && InitValue)
8615               return getSCEV(InitValue);
8616           }
8617           // Do we have a loop invariant value flowing around the backedge
8618           // for a loop which must execute the backedge?
8619           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8620               isKnownPositive(BackedgeTakenCount) &&
8621               PN->getNumIncomingValues() == 2) {
8622 
8623             unsigned InLoopPred =
8624                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8625             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8626             if (CurrLoop->isLoopInvariant(BackedgeVal))
8627               return getSCEV(BackedgeVal);
8628           }
8629           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8630             // Okay, we know how many times the containing loop executes.  If
8631             // this is a constant evolving PHI node, get the final value at
8632             // the specified iteration number.
8633             Constant *RV = getConstantEvolutionLoopExitValue(
8634                 PN, BTCC->getAPInt(), CurrLoop);
8635             if (RV) return getSCEV(RV);
8636           }
8637         }
8638 
8639         // If there is a single-input Phi, evaluate it at our scope. If we can
8640         // prove that this replacement does not break LCSSA form, use new value.
8641         if (PN->getNumOperands() == 1) {
8642           const SCEV *Input = getSCEV(PN->getOperand(0));
8643           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8644           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8645           // for the simplest case just support constants.
8646           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8647         }
8648       }
8649 
8650       // Okay, this is an expression that we cannot symbolically evaluate
8651       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8652       // the arguments into constants, and if so, try to constant propagate the
8653       // result.  This is particularly useful for computing loop exit values.
8654       if (CanConstantFold(I)) {
8655         SmallVector<Constant *, 4> Operands;
8656         bool MadeImprovement = false;
8657         for (Value *Op : I->operands()) {
8658           if (Constant *C = dyn_cast<Constant>(Op)) {
8659             Operands.push_back(C);
8660             continue;
8661           }
8662 
8663           // If any of the operands is non-constant and if they are
8664           // non-integer and non-pointer, don't even try to analyze them
8665           // with scev techniques.
8666           if (!isSCEVable(Op->getType()))
8667             return V;
8668 
8669           const SCEV *OrigV = getSCEV(Op);
8670           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8671           MadeImprovement |= OrigV != OpV;
8672 
8673           Constant *C = BuildConstantFromSCEV(OpV);
8674           if (!C) return V;
8675           if (C->getType() != Op->getType())
8676             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8677                                                               Op->getType(),
8678                                                               false),
8679                                       C, Op->getType());
8680           Operands.push_back(C);
8681         }
8682 
8683         // Check to see if getSCEVAtScope actually made an improvement.
8684         if (MadeImprovement) {
8685           Constant *C = nullptr;
8686           const DataLayout &DL = getDataLayout();
8687           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8688             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8689                                                 Operands[1], DL, &TLI);
8690           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8691             if (!Load->isVolatile())
8692               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8693                                                DL);
8694           } else
8695             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8696           if (!C) return V;
8697           return getSCEV(C);
8698         }
8699       }
8700     }
8701 
8702     // This is some other type of SCEVUnknown, just return it.
8703     return V;
8704   }
8705 
8706   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8707     // Avoid performing the look-up in the common case where the specified
8708     // expression has no loop-variant portions.
8709     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8710       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8711       if (OpAtScope != Comm->getOperand(i)) {
8712         // Okay, at least one of these operands is loop variant but might be
8713         // foldable.  Build a new instance of the folded commutative expression.
8714         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8715                                             Comm->op_begin()+i);
8716         NewOps.push_back(OpAtScope);
8717 
8718         for (++i; i != e; ++i) {
8719           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8720           NewOps.push_back(OpAtScope);
8721         }
8722         if (isa<SCEVAddExpr>(Comm))
8723           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8724         if (isa<SCEVMulExpr>(Comm))
8725           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8726         if (isa<SCEVMinMaxExpr>(Comm))
8727           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8728         llvm_unreachable("Unknown commutative SCEV type!");
8729       }
8730     }
8731     // If we got here, all operands are loop invariant.
8732     return Comm;
8733   }
8734 
8735   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8736     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8737     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8738     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8739       return Div;   // must be loop invariant
8740     return getUDivExpr(LHS, RHS);
8741   }
8742 
8743   // If this is a loop recurrence for a loop that does not contain L, then we
8744   // are dealing with the final value computed by the loop.
8745   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8746     // First, attempt to evaluate each operand.
8747     // Avoid performing the look-up in the common case where the specified
8748     // expression has no loop-variant portions.
8749     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8750       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8751       if (OpAtScope == AddRec->getOperand(i))
8752         continue;
8753 
8754       // Okay, at least one of these operands is loop variant but might be
8755       // foldable.  Build a new instance of the folded commutative expression.
8756       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8757                                           AddRec->op_begin()+i);
8758       NewOps.push_back(OpAtScope);
8759       for (++i; i != e; ++i)
8760         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8761 
8762       const SCEV *FoldedRec =
8763         getAddRecExpr(NewOps, AddRec->getLoop(),
8764                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8765       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8766       // The addrec may be folded to a nonrecurrence, for example, if the
8767       // induction variable is multiplied by zero after constant folding. Go
8768       // ahead and return the folded value.
8769       if (!AddRec)
8770         return FoldedRec;
8771       break;
8772     }
8773 
8774     // If the scope is outside the addrec's loop, evaluate it by using the
8775     // loop exit value of the addrec.
8776     if (!AddRec->getLoop()->contains(L)) {
8777       // To evaluate this recurrence, we need to know how many times the AddRec
8778       // loop iterates.  Compute this now.
8779       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8780       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8781 
8782       // Then, evaluate the AddRec.
8783       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8784     }
8785 
8786     return AddRec;
8787   }
8788 
8789   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8790     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8791     if (Op == Cast->getOperand())
8792       return Cast;  // must be loop invariant
8793     return getZeroExtendExpr(Op, Cast->getType());
8794   }
8795 
8796   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8797     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8798     if (Op == Cast->getOperand())
8799       return Cast;  // must be loop invariant
8800     return getSignExtendExpr(Op, Cast->getType());
8801   }
8802 
8803   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8804     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8805     if (Op == Cast->getOperand())
8806       return Cast;  // must be loop invariant
8807     return getTruncateExpr(Op, Cast->getType());
8808   }
8809 
8810   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8811     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8812     if (Op == Cast->getOperand())
8813       return Cast; // must be loop invariant
8814     return getPtrToIntExpr(Op, Cast->getType());
8815   }
8816 
8817   llvm_unreachable("Unknown SCEV type!");
8818 }
8819 
8820 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8821   return getSCEVAtScope(getSCEV(V), L);
8822 }
8823 
8824 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8825   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8826     return stripInjectiveFunctions(ZExt->getOperand());
8827   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8828     return stripInjectiveFunctions(SExt->getOperand());
8829   return S;
8830 }
8831 
8832 /// Finds the minimum unsigned root of the following equation:
8833 ///
8834 ///     A * X = B (mod N)
8835 ///
8836 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8837 /// A and B isn't important.
8838 ///
8839 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8840 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8841                                                ScalarEvolution &SE) {
8842   uint32_t BW = A.getBitWidth();
8843   assert(BW == SE.getTypeSizeInBits(B->getType()));
8844   assert(A != 0 && "A must be non-zero.");
8845 
8846   // 1. D = gcd(A, N)
8847   //
8848   // The gcd of A and N may have only one prime factor: 2. The number of
8849   // trailing zeros in A is its multiplicity
8850   uint32_t Mult2 = A.countTrailingZeros();
8851   // D = 2^Mult2
8852 
8853   // 2. Check if B is divisible by D.
8854   //
8855   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8856   // is not less than multiplicity of this prime factor for D.
8857   if (SE.GetMinTrailingZeros(B) < Mult2)
8858     return SE.getCouldNotCompute();
8859 
8860   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8861   // modulo (N / D).
8862   //
8863   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8864   // (N / D) in general. The inverse itself always fits into BW bits, though,
8865   // so we immediately truncate it.
8866   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8867   APInt Mod(BW + 1, 0);
8868   Mod.setBit(BW - Mult2);  // Mod = N / D
8869   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8870 
8871   // 4. Compute the minimum unsigned root of the equation:
8872   // I * (B / D) mod (N / D)
8873   // To simplify the computation, we factor out the divide by D:
8874   // (I * B mod N) / D
8875   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8876   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8877 }
8878 
8879 /// For a given quadratic addrec, generate coefficients of the corresponding
8880 /// quadratic equation, multiplied by a common value to ensure that they are
8881 /// integers.
8882 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8883 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8884 /// were multiplied by, and BitWidth is the bit width of the original addrec
8885 /// coefficients.
8886 /// This function returns None if the addrec coefficients are not compile-
8887 /// time constants.
8888 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8889 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8890   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8891   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8892   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8893   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8894   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8895                     << *AddRec << '\n');
8896 
8897   // We currently can only solve this if the coefficients are constants.
8898   if (!LC || !MC || !NC) {
8899     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8900     return None;
8901   }
8902 
8903   APInt L = LC->getAPInt();
8904   APInt M = MC->getAPInt();
8905   APInt N = NC->getAPInt();
8906   assert(!N.isNullValue() && "This is not a quadratic addrec");
8907 
8908   unsigned BitWidth = LC->getAPInt().getBitWidth();
8909   unsigned NewWidth = BitWidth + 1;
8910   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8911                     << BitWidth << '\n');
8912   // The sign-extension (as opposed to a zero-extension) here matches the
8913   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8914   N = N.sext(NewWidth);
8915   M = M.sext(NewWidth);
8916   L = L.sext(NewWidth);
8917 
8918   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8919   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8920   //   L+M, L+2M+N, L+3M+3N, ...
8921   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8922   //
8923   // The equation Acc = 0 is then
8924   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8925   // In a quadratic form it becomes:
8926   //   N n^2 + (2M-N) n + 2L = 0.
8927 
8928   APInt A = N;
8929   APInt B = 2 * M - A;
8930   APInt C = 2 * L;
8931   APInt T = APInt(NewWidth, 2);
8932   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8933                     << "x + " << C << ", coeff bw: " << NewWidth
8934                     << ", multiplied by " << T << '\n');
8935   return std::make_tuple(A, B, C, T, BitWidth);
8936 }
8937 
8938 /// Helper function to compare optional APInts:
8939 /// (a) if X and Y both exist, return min(X, Y),
8940 /// (b) if neither X nor Y exist, return None,
8941 /// (c) if exactly one of X and Y exists, return that value.
8942 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8943   if (X.hasValue() && Y.hasValue()) {
8944     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8945     APInt XW = X->sextOrSelf(W);
8946     APInt YW = Y->sextOrSelf(W);
8947     return XW.slt(YW) ? *X : *Y;
8948   }
8949   if (!X.hasValue() && !Y.hasValue())
8950     return None;
8951   return X.hasValue() ? *X : *Y;
8952 }
8953 
8954 /// Helper function to truncate an optional APInt to a given BitWidth.
8955 /// When solving addrec-related equations, it is preferable to return a value
8956 /// that has the same bit width as the original addrec's coefficients. If the
8957 /// solution fits in the original bit width, truncate it (except for i1).
8958 /// Returning a value of a different bit width may inhibit some optimizations.
8959 ///
8960 /// In general, a solution to a quadratic equation generated from an addrec
8961 /// may require BW+1 bits, where BW is the bit width of the addrec's
8962 /// coefficients. The reason is that the coefficients of the quadratic
8963 /// equation are BW+1 bits wide (to avoid truncation when converting from
8964 /// the addrec to the equation).
8965 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8966   if (!X.hasValue())
8967     return None;
8968   unsigned W = X->getBitWidth();
8969   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8970     return X->trunc(BitWidth);
8971   return X;
8972 }
8973 
8974 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8975 /// iterations. The values L, M, N are assumed to be signed, and they
8976 /// should all have the same bit widths.
8977 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8978 /// where BW is the bit width of the addrec's coefficients.
8979 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8980 /// returned as such, otherwise the bit width of the returned value may
8981 /// be greater than BW.
8982 ///
8983 /// This function returns None if
8984 /// (a) the addrec coefficients are not constant, or
8985 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8986 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8987 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8988 static Optional<APInt>
8989 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8990   APInt A, B, C, M;
8991   unsigned BitWidth;
8992   auto T = GetQuadraticEquation(AddRec);
8993   if (!T.hasValue())
8994     return None;
8995 
8996   std::tie(A, B, C, M, BitWidth) = *T;
8997   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8998   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8999   if (!X.hasValue())
9000     return None;
9001 
9002   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9003   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9004   if (!V->isZero())
9005     return None;
9006 
9007   return TruncIfPossible(X, BitWidth);
9008 }
9009 
9010 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9011 /// iterations. The values M, N are assumed to be signed, and they
9012 /// should all have the same bit widths.
9013 /// Find the least n such that c(n) does not belong to the given range,
9014 /// while c(n-1) does.
9015 ///
9016 /// This function returns None if
9017 /// (a) the addrec coefficients are not constant, or
9018 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9019 ///     bounds of the range.
9020 static Optional<APInt>
9021 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9022                           const ConstantRange &Range, ScalarEvolution &SE) {
9023   assert(AddRec->getOperand(0)->isZero() &&
9024          "Starting value of addrec should be 0");
9025   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9026                     << Range << ", addrec " << *AddRec << '\n');
9027   // This case is handled in getNumIterationsInRange. Here we can assume that
9028   // we start in the range.
9029   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9030          "Addrec's initial value should be in range");
9031 
9032   APInt A, B, C, M;
9033   unsigned BitWidth;
9034   auto T = GetQuadraticEquation(AddRec);
9035   if (!T.hasValue())
9036     return None;
9037 
9038   // Be careful about the return value: there can be two reasons for not
9039   // returning an actual number. First, if no solutions to the equations
9040   // were found, and second, if the solutions don't leave the given range.
9041   // The first case means that the actual solution is "unknown", the second
9042   // means that it's known, but not valid. If the solution is unknown, we
9043   // cannot make any conclusions.
9044   // Return a pair: the optional solution and a flag indicating if the
9045   // solution was found.
9046   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9047     // Solve for signed overflow and unsigned overflow, pick the lower
9048     // solution.
9049     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9050                       << Bound << " (before multiplying by " << M << ")\n");
9051     Bound *= M; // The quadratic equation multiplier.
9052 
9053     Optional<APInt> SO = None;
9054     if (BitWidth > 1) {
9055       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9056                            "signed overflow\n");
9057       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9058     }
9059     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9060                          "unsigned overflow\n");
9061     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9062                                                               BitWidth+1);
9063 
9064     auto LeavesRange = [&] (const APInt &X) {
9065       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9066       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9067       if (Range.contains(V0->getValue()))
9068         return false;
9069       // X should be at least 1, so X-1 is non-negative.
9070       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9071       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9072       if (Range.contains(V1->getValue()))
9073         return true;
9074       return false;
9075     };
9076 
9077     // If SolveQuadraticEquationWrap returns None, it means that there can
9078     // be a solution, but the function failed to find it. We cannot treat it
9079     // as "no solution".
9080     if (!SO.hasValue() || !UO.hasValue())
9081       return { None, false };
9082 
9083     // Check the smaller value first to see if it leaves the range.
9084     // At this point, both SO and UO must have values.
9085     Optional<APInt> Min = MinOptional(SO, UO);
9086     if (LeavesRange(*Min))
9087       return { Min, true };
9088     Optional<APInt> Max = Min == SO ? UO : SO;
9089     if (LeavesRange(*Max))
9090       return { Max, true };
9091 
9092     // Solutions were found, but were eliminated, hence the "true".
9093     return { None, true };
9094   };
9095 
9096   std::tie(A, B, C, M, BitWidth) = *T;
9097   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9098   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9099   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9100   auto SL = SolveForBoundary(Lower);
9101   auto SU = SolveForBoundary(Upper);
9102   // If any of the solutions was unknown, no meaninigful conclusions can
9103   // be made.
9104   if (!SL.second || !SU.second)
9105     return None;
9106 
9107   // Claim: The correct solution is not some value between Min and Max.
9108   //
9109   // Justification: Assuming that Min and Max are different values, one of
9110   // them is when the first signed overflow happens, the other is when the
9111   // first unsigned overflow happens. Crossing the range boundary is only
9112   // possible via an overflow (treating 0 as a special case of it, modeling
9113   // an overflow as crossing k*2^W for some k).
9114   //
9115   // The interesting case here is when Min was eliminated as an invalid
9116   // solution, but Max was not. The argument is that if there was another
9117   // overflow between Min and Max, it would also have been eliminated if
9118   // it was considered.
9119   //
9120   // For a given boundary, it is possible to have two overflows of the same
9121   // type (signed/unsigned) without having the other type in between: this
9122   // can happen when the vertex of the parabola is between the iterations
9123   // corresponding to the overflows. This is only possible when the two
9124   // overflows cross k*2^W for the same k. In such case, if the second one
9125   // left the range (and was the first one to do so), the first overflow
9126   // would have to enter the range, which would mean that either we had left
9127   // the range before or that we started outside of it. Both of these cases
9128   // are contradictions.
9129   //
9130   // Claim: In the case where SolveForBoundary returns None, the correct
9131   // solution is not some value between the Max for this boundary and the
9132   // Min of the other boundary.
9133   //
9134   // Justification: Assume that we had such Max_A and Min_B corresponding
9135   // to range boundaries A and B and such that Max_A < Min_B. If there was
9136   // a solution between Max_A and Min_B, it would have to be caused by an
9137   // overflow corresponding to either A or B. It cannot correspond to B,
9138   // since Min_B is the first occurrence of such an overflow. If it
9139   // corresponded to A, it would have to be either a signed or an unsigned
9140   // overflow that is larger than both eliminated overflows for A. But
9141   // between the eliminated overflows and this overflow, the values would
9142   // cover the entire value space, thus crossing the other boundary, which
9143   // is a contradiction.
9144 
9145   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9146 }
9147 
9148 ScalarEvolution::ExitLimit
9149 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9150                               bool AllowPredicates) {
9151 
9152   // This is only used for loops with a "x != y" exit test. The exit condition
9153   // is now expressed as a single expression, V = x-y. So the exit test is
9154   // effectively V != 0.  We know and take advantage of the fact that this
9155   // expression only being used in a comparison by zero context.
9156 
9157   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9158   // If the value is a constant
9159   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9160     // If the value is already zero, the branch will execute zero times.
9161     if (C->getValue()->isZero()) return C;
9162     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9163   }
9164 
9165   const SCEVAddRecExpr *AddRec =
9166       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9167 
9168   if (!AddRec && AllowPredicates)
9169     // Try to make this an AddRec using runtime tests, in the first X
9170     // iterations of this loop, where X is the SCEV expression found by the
9171     // algorithm below.
9172     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9173 
9174   if (!AddRec || AddRec->getLoop() != L)
9175     return getCouldNotCompute();
9176 
9177   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9178   // the quadratic equation to solve it.
9179   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9180     // We can only use this value if the chrec ends up with an exact zero
9181     // value at this index.  When solving for "X*X != 5", for example, we
9182     // should not accept a root of 2.
9183     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9184       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9185       return ExitLimit(R, R, false, Predicates);
9186     }
9187     return getCouldNotCompute();
9188   }
9189 
9190   // Otherwise we can only handle this if it is affine.
9191   if (!AddRec->isAffine())
9192     return getCouldNotCompute();
9193 
9194   // If this is an affine expression, the execution count of this branch is
9195   // the minimum unsigned root of the following equation:
9196   //
9197   //     Start + Step*N = 0 (mod 2^BW)
9198   //
9199   // equivalent to:
9200   //
9201   //             Step*N = -Start (mod 2^BW)
9202   //
9203   // where BW is the common bit width of Start and Step.
9204 
9205   // Get the initial value for the loop.
9206   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9207   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9208 
9209   // For now we handle only constant steps.
9210   //
9211   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9212   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9213   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9214   // We have not yet seen any such cases.
9215   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9216   if (!StepC || StepC->getValue()->isZero())
9217     return getCouldNotCompute();
9218 
9219   // For positive steps (counting up until unsigned overflow):
9220   //   N = -Start/Step (as unsigned)
9221   // For negative steps (counting down to zero):
9222   //   N = Start/-Step
9223   // First compute the unsigned distance from zero in the direction of Step.
9224   bool CountDown = StepC->getAPInt().isNegative();
9225   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9226 
9227   // Handle unitary steps, which cannot wraparound.
9228   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9229   //   N = Distance (as unsigned)
9230   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9231     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9232     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9233     if (MaxBECountBase.ult(MaxBECount))
9234       MaxBECount = MaxBECountBase;
9235 
9236     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9237     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9238     // case, and see if we can improve the bound.
9239     //
9240     // Explicitly handling this here is necessary because getUnsignedRange
9241     // isn't context-sensitive; it doesn't know that we only care about the
9242     // range inside the loop.
9243     const SCEV *Zero = getZero(Distance->getType());
9244     const SCEV *One = getOne(Distance->getType());
9245     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9246     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9247       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9248       // as "unsigned_max(Distance + 1) - 1".
9249       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9250       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9251     }
9252     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9253   }
9254 
9255   // If the condition controls loop exit (the loop exits only if the expression
9256   // is true) and the addition is no-wrap we can use unsigned divide to
9257   // compute the backedge count.  In this case, the step may not divide the
9258   // distance, but we don't care because if the condition is "missed" the loop
9259   // will have undefined behavior due to wrapping.
9260   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9261       loopHasNoAbnormalExits(AddRec->getLoop())) {
9262     const SCEV *Exact =
9263         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9264     const SCEV *Max =
9265         Exact == getCouldNotCompute()
9266             ? Exact
9267             : getConstant(getUnsignedRangeMax(Exact));
9268     return ExitLimit(Exact, Max, false, Predicates);
9269   }
9270 
9271   // Solve the general equation.
9272   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9273                                                getNegativeSCEV(Start), *this);
9274   const SCEV *M = E == getCouldNotCompute()
9275                       ? E
9276                       : getConstant(getUnsignedRangeMax(E));
9277   return ExitLimit(E, M, false, Predicates);
9278 }
9279 
9280 ScalarEvolution::ExitLimit
9281 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9282   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9283   // handle them yet except for the trivial case.  This could be expanded in the
9284   // future as needed.
9285 
9286   // If the value is a constant, check to see if it is known to be non-zero
9287   // already.  If so, the backedge will execute zero times.
9288   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9289     if (!C->getValue()->isZero())
9290       return getZero(C->getType());
9291     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9292   }
9293 
9294   // We could implement others, but I really doubt anyone writes loops like
9295   // this, and if they did, they would already be constant folded.
9296   return getCouldNotCompute();
9297 }
9298 
9299 std::pair<const BasicBlock *, const BasicBlock *>
9300 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9301     const {
9302   // If the block has a unique predecessor, then there is no path from the
9303   // predecessor to the block that does not go through the direct edge
9304   // from the predecessor to the block.
9305   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9306     return {Pred, BB};
9307 
9308   // A loop's header is defined to be a block that dominates the loop.
9309   // If the header has a unique predecessor outside the loop, it must be
9310   // a block that has exactly one successor that can reach the loop.
9311   if (const Loop *L = LI.getLoopFor(BB))
9312     return {L->getLoopPredecessor(), L->getHeader()};
9313 
9314   return {nullptr, nullptr};
9315 }
9316 
9317 /// SCEV structural equivalence is usually sufficient for testing whether two
9318 /// expressions are equal, however for the purposes of looking for a condition
9319 /// guarding a loop, it can be useful to be a little more general, since a
9320 /// front-end may have replicated the controlling expression.
9321 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9322   // Quick check to see if they are the same SCEV.
9323   if (A == B) return true;
9324 
9325   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9326     // Not all instructions that are "identical" compute the same value.  For
9327     // instance, two distinct alloca instructions allocating the same type are
9328     // identical and do not read memory; but compute distinct values.
9329     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9330   };
9331 
9332   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9333   // two different instructions with the same value. Check for this case.
9334   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9335     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9336       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9337         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9338           if (ComputesEqualValues(AI, BI))
9339             return true;
9340 
9341   // Otherwise assume they may have a different value.
9342   return false;
9343 }
9344 
9345 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9346                                            const SCEV *&LHS, const SCEV *&RHS,
9347                                            unsigned Depth) {
9348   bool Changed = false;
9349   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9350   // '0 != 0'.
9351   auto TrivialCase = [&](bool TriviallyTrue) {
9352     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9353     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9354     return true;
9355   };
9356   // If we hit the max recursion limit bail out.
9357   if (Depth >= 3)
9358     return false;
9359 
9360   // Canonicalize a constant to the right side.
9361   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9362     // Check for both operands constant.
9363     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9364       if (ConstantExpr::getICmp(Pred,
9365                                 LHSC->getValue(),
9366                                 RHSC->getValue())->isNullValue())
9367         return TrivialCase(false);
9368       else
9369         return TrivialCase(true);
9370     }
9371     // Otherwise swap the operands to put the constant on the right.
9372     std::swap(LHS, RHS);
9373     Pred = ICmpInst::getSwappedPredicate(Pred);
9374     Changed = true;
9375   }
9376 
9377   // If we're comparing an addrec with a value which is loop-invariant in the
9378   // addrec's loop, put the addrec on the left. Also make a dominance check,
9379   // as both operands could be addrecs loop-invariant in each other's loop.
9380   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9381     const Loop *L = AR->getLoop();
9382     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9383       std::swap(LHS, RHS);
9384       Pred = ICmpInst::getSwappedPredicate(Pred);
9385       Changed = true;
9386     }
9387   }
9388 
9389   // If there's a constant operand, canonicalize comparisons with boundary
9390   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9391   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9392     const APInt &RA = RC->getAPInt();
9393 
9394     bool SimplifiedByConstantRange = false;
9395 
9396     if (!ICmpInst::isEquality(Pred)) {
9397       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9398       if (ExactCR.isFullSet())
9399         return TrivialCase(true);
9400       else if (ExactCR.isEmptySet())
9401         return TrivialCase(false);
9402 
9403       APInt NewRHS;
9404       CmpInst::Predicate NewPred;
9405       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9406           ICmpInst::isEquality(NewPred)) {
9407         // We were able to convert an inequality to an equality.
9408         Pred = NewPred;
9409         RHS = getConstant(NewRHS);
9410         Changed = SimplifiedByConstantRange = true;
9411       }
9412     }
9413 
9414     if (!SimplifiedByConstantRange) {
9415       switch (Pred) {
9416       default:
9417         break;
9418       case ICmpInst::ICMP_EQ:
9419       case ICmpInst::ICMP_NE:
9420         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9421         if (!RA)
9422           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9423             if (const SCEVMulExpr *ME =
9424                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9425               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9426                   ME->getOperand(0)->isAllOnesValue()) {
9427                 RHS = AE->getOperand(1);
9428                 LHS = ME->getOperand(1);
9429                 Changed = true;
9430               }
9431         break;
9432 
9433 
9434         // The "Should have been caught earlier!" messages refer to the fact
9435         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9436         // should have fired on the corresponding cases, and canonicalized the
9437         // check to trivial case.
9438 
9439       case ICmpInst::ICMP_UGE:
9440         assert(!RA.isMinValue() && "Should have been caught earlier!");
9441         Pred = ICmpInst::ICMP_UGT;
9442         RHS = getConstant(RA - 1);
9443         Changed = true;
9444         break;
9445       case ICmpInst::ICMP_ULE:
9446         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9447         Pred = ICmpInst::ICMP_ULT;
9448         RHS = getConstant(RA + 1);
9449         Changed = true;
9450         break;
9451       case ICmpInst::ICMP_SGE:
9452         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9453         Pred = ICmpInst::ICMP_SGT;
9454         RHS = getConstant(RA - 1);
9455         Changed = true;
9456         break;
9457       case ICmpInst::ICMP_SLE:
9458         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9459         Pred = ICmpInst::ICMP_SLT;
9460         RHS = getConstant(RA + 1);
9461         Changed = true;
9462         break;
9463       }
9464     }
9465   }
9466 
9467   // Check for obvious equality.
9468   if (HasSameValue(LHS, RHS)) {
9469     if (ICmpInst::isTrueWhenEqual(Pred))
9470       return TrivialCase(true);
9471     if (ICmpInst::isFalseWhenEqual(Pred))
9472       return TrivialCase(false);
9473   }
9474 
9475   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9476   // adding or subtracting 1 from one of the operands.
9477   switch (Pred) {
9478   case ICmpInst::ICMP_SLE:
9479     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9480       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9481                        SCEV::FlagNSW);
9482       Pred = ICmpInst::ICMP_SLT;
9483       Changed = true;
9484     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9485       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9486                        SCEV::FlagNSW);
9487       Pred = ICmpInst::ICMP_SLT;
9488       Changed = true;
9489     }
9490     break;
9491   case ICmpInst::ICMP_SGE:
9492     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9493       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9494                        SCEV::FlagNSW);
9495       Pred = ICmpInst::ICMP_SGT;
9496       Changed = true;
9497     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9498       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9499                        SCEV::FlagNSW);
9500       Pred = ICmpInst::ICMP_SGT;
9501       Changed = true;
9502     }
9503     break;
9504   case ICmpInst::ICMP_ULE:
9505     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9506       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9507                        SCEV::FlagNUW);
9508       Pred = ICmpInst::ICMP_ULT;
9509       Changed = true;
9510     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9511       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9512       Pred = ICmpInst::ICMP_ULT;
9513       Changed = true;
9514     }
9515     break;
9516   case ICmpInst::ICMP_UGE:
9517     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9518       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9519       Pred = ICmpInst::ICMP_UGT;
9520       Changed = true;
9521     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9522       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9523                        SCEV::FlagNUW);
9524       Pred = ICmpInst::ICMP_UGT;
9525       Changed = true;
9526     }
9527     break;
9528   default:
9529     break;
9530   }
9531 
9532   // TODO: More simplifications are possible here.
9533 
9534   // Recursively simplify until we either hit a recursion limit or nothing
9535   // changes.
9536   if (Changed)
9537     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9538 
9539   return Changed;
9540 }
9541 
9542 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9543   return getSignedRangeMax(S).isNegative();
9544 }
9545 
9546 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9547   return getSignedRangeMin(S).isStrictlyPositive();
9548 }
9549 
9550 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9551   return !getSignedRangeMin(S).isNegative();
9552 }
9553 
9554 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9555   return !getSignedRangeMax(S).isStrictlyPositive();
9556 }
9557 
9558 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9559   return isKnownNegative(S) || isKnownPositive(S);
9560 }
9561 
9562 std::pair<const SCEV *, const SCEV *>
9563 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9564   // Compute SCEV on entry of loop L.
9565   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9566   if (Start == getCouldNotCompute())
9567     return { Start, Start };
9568   // Compute post increment SCEV for loop L.
9569   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9570   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9571   return { Start, PostInc };
9572 }
9573 
9574 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9575                                           const SCEV *LHS, const SCEV *RHS) {
9576   // First collect all loops.
9577   SmallPtrSet<const Loop *, 8> LoopsUsed;
9578   getUsedLoops(LHS, LoopsUsed);
9579   getUsedLoops(RHS, LoopsUsed);
9580 
9581   if (LoopsUsed.empty())
9582     return false;
9583 
9584   // Domination relationship must be a linear order on collected loops.
9585 #ifndef NDEBUG
9586   for (auto *L1 : LoopsUsed)
9587     for (auto *L2 : LoopsUsed)
9588       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9589               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9590              "Domination relationship is not a linear order");
9591 #endif
9592 
9593   const Loop *MDL =
9594       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9595                         [&](const Loop *L1, const Loop *L2) {
9596          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9597        });
9598 
9599   // Get init and post increment value for LHS.
9600   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9601   // if LHS contains unknown non-invariant SCEV then bail out.
9602   if (SplitLHS.first == getCouldNotCompute())
9603     return false;
9604   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9605   // Get init and post increment value for RHS.
9606   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9607   // if RHS contains unknown non-invariant SCEV then bail out.
9608   if (SplitRHS.first == getCouldNotCompute())
9609     return false;
9610   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9611   // It is possible that init SCEV contains an invariant load but it does
9612   // not dominate MDL and is not available at MDL loop entry, so we should
9613   // check it here.
9614   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9615       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9616     return false;
9617 
9618   // It seems backedge guard check is faster than entry one so in some cases
9619   // it can speed up whole estimation by short circuit
9620   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9621                                      SplitRHS.second) &&
9622          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9623 }
9624 
9625 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9626                                        const SCEV *LHS, const SCEV *RHS) {
9627   // Canonicalize the inputs first.
9628   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9629 
9630   if (isKnownViaInduction(Pred, LHS, RHS))
9631     return true;
9632 
9633   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9634     return true;
9635 
9636   // Otherwise see what can be done with some simple reasoning.
9637   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9638 }
9639 
9640 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9641                                                   const SCEV *LHS,
9642                                                   const SCEV *RHS) {
9643   if (isKnownPredicate(Pred, LHS, RHS))
9644     return true;
9645   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9646     return false;
9647   return None;
9648 }
9649 
9650 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9651                                          const SCEV *LHS, const SCEV *RHS,
9652                                          const Instruction *Context) {
9653   // TODO: Analyze guards and assumes from Context's block.
9654   return isKnownPredicate(Pred, LHS, RHS) ||
9655          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9656 }
9657 
9658 Optional<bool>
9659 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9660                                      const SCEV *RHS,
9661                                      const Instruction *Context) {
9662   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9663   if (KnownWithoutContext)
9664     return KnownWithoutContext;
9665 
9666   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9667     return true;
9668   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9669                                           ICmpInst::getInversePredicate(Pred),
9670                                           LHS, RHS))
9671     return false;
9672   return None;
9673 }
9674 
9675 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9676                                               const SCEVAddRecExpr *LHS,
9677                                               const SCEV *RHS) {
9678   const Loop *L = LHS->getLoop();
9679   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9680          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9681 }
9682 
9683 Optional<ScalarEvolution::MonotonicPredicateType>
9684 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9685                                            ICmpInst::Predicate Pred) {
9686   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9687 
9688 #ifndef NDEBUG
9689   // Verify an invariant: inverting the predicate should turn a monotonically
9690   // increasing change to a monotonically decreasing one, and vice versa.
9691   if (Result) {
9692     auto ResultSwapped =
9693         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9694 
9695     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9696     assert(ResultSwapped.getValue() != Result.getValue() &&
9697            "monotonicity should flip as we flip the predicate");
9698   }
9699 #endif
9700 
9701   return Result;
9702 }
9703 
9704 Optional<ScalarEvolution::MonotonicPredicateType>
9705 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9706                                                ICmpInst::Predicate Pred) {
9707   // A zero step value for LHS means the induction variable is essentially a
9708   // loop invariant value. We don't really depend on the predicate actually
9709   // flipping from false to true (for increasing predicates, and the other way
9710   // around for decreasing predicates), all we care about is that *if* the
9711   // predicate changes then it only changes from false to true.
9712   //
9713   // A zero step value in itself is not very useful, but there may be places
9714   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9715   // as general as possible.
9716 
9717   // Only handle LE/LT/GE/GT predicates.
9718   if (!ICmpInst::isRelational(Pred))
9719     return None;
9720 
9721   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9722   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9723          "Should be greater or less!");
9724 
9725   // Check that AR does not wrap.
9726   if (ICmpInst::isUnsigned(Pred)) {
9727     if (!LHS->hasNoUnsignedWrap())
9728       return None;
9729     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9730   } else {
9731     assert(ICmpInst::isSigned(Pred) &&
9732            "Relational predicate is either signed or unsigned!");
9733     if (!LHS->hasNoSignedWrap())
9734       return None;
9735 
9736     const SCEV *Step = LHS->getStepRecurrence(*this);
9737 
9738     if (isKnownNonNegative(Step))
9739       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9740 
9741     if (isKnownNonPositive(Step))
9742       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9743 
9744     return None;
9745   }
9746 }
9747 
9748 Optional<ScalarEvolution::LoopInvariantPredicate>
9749 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9750                                            const SCEV *LHS, const SCEV *RHS,
9751                                            const Loop *L) {
9752 
9753   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9754   if (!isLoopInvariant(RHS, L)) {
9755     if (!isLoopInvariant(LHS, L))
9756       return None;
9757 
9758     std::swap(LHS, RHS);
9759     Pred = ICmpInst::getSwappedPredicate(Pred);
9760   }
9761 
9762   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9763   if (!ArLHS || ArLHS->getLoop() != L)
9764     return None;
9765 
9766   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9767   if (!MonotonicType)
9768     return None;
9769   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9770   // true as the loop iterates, and the backedge is control dependent on
9771   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9772   //
9773   //   * if the predicate was false in the first iteration then the predicate
9774   //     is never evaluated again, since the loop exits without taking the
9775   //     backedge.
9776   //   * if the predicate was true in the first iteration then it will
9777   //     continue to be true for all future iterations since it is
9778   //     monotonically increasing.
9779   //
9780   // For both the above possibilities, we can replace the loop varying
9781   // predicate with its value on the first iteration of the loop (which is
9782   // loop invariant).
9783   //
9784   // A similar reasoning applies for a monotonically decreasing predicate, by
9785   // replacing true with false and false with true in the above two bullets.
9786   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9787   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9788 
9789   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9790     return None;
9791 
9792   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9793 }
9794 
9795 Optional<ScalarEvolution::LoopInvariantPredicate>
9796 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9797     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9798     const Instruction *Context, const SCEV *MaxIter) {
9799   // Try to prove the following set of facts:
9800   // - The predicate is monotonic in the iteration space.
9801   // - If the check does not fail on the 1st iteration:
9802   //   - No overflow will happen during first MaxIter iterations;
9803   //   - It will not fail on the MaxIter'th iteration.
9804   // If the check does fail on the 1st iteration, we leave the loop and no
9805   // other checks matter.
9806 
9807   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9808   if (!isLoopInvariant(RHS, L)) {
9809     if (!isLoopInvariant(LHS, L))
9810       return None;
9811 
9812     std::swap(LHS, RHS);
9813     Pred = ICmpInst::getSwappedPredicate(Pred);
9814   }
9815 
9816   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9817   if (!AR || AR->getLoop() != L)
9818     return None;
9819 
9820   // The predicate must be relational (i.e. <, <=, >=, >).
9821   if (!ICmpInst::isRelational(Pred))
9822     return None;
9823 
9824   // TODO: Support steps other than +/- 1.
9825   const SCEV *Step = AR->getStepRecurrence(*this);
9826   auto *One = getOne(Step->getType());
9827   auto *MinusOne = getNegativeSCEV(One);
9828   if (Step != One && Step != MinusOne)
9829     return None;
9830 
9831   // Type mismatch here means that MaxIter is potentially larger than max
9832   // unsigned value in start type, which mean we cannot prove no wrap for the
9833   // indvar.
9834   if (AR->getType() != MaxIter->getType())
9835     return None;
9836 
9837   // Value of IV on suggested last iteration.
9838   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9839   // Does it still meet the requirement?
9840   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9841     return None;
9842   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9843   // not exceed max unsigned value of this type), this effectively proves
9844   // that there is no wrap during the iteration. To prove that there is no
9845   // signed/unsigned wrap, we need to check that
9846   // Start <= Last for step = 1 or Start >= Last for step = -1.
9847   ICmpInst::Predicate NoOverflowPred =
9848       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9849   if (Step == MinusOne)
9850     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9851   const SCEV *Start = AR->getStart();
9852   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9853     return None;
9854 
9855   // Everything is fine.
9856   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9857 }
9858 
9859 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9860     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9861   if (HasSameValue(LHS, RHS))
9862     return ICmpInst::isTrueWhenEqual(Pred);
9863 
9864   // This code is split out from isKnownPredicate because it is called from
9865   // within isLoopEntryGuardedByCond.
9866 
9867   auto CheckRanges = [&](const ConstantRange &RangeLHS,
9868                          const ConstantRange &RangeRHS) {
9869     return RangeLHS.icmp(Pred, RangeRHS);
9870   };
9871 
9872   // The check at the top of the function catches the case where the values are
9873   // known to be equal.
9874   if (Pred == CmpInst::ICMP_EQ)
9875     return false;
9876 
9877   if (Pred == CmpInst::ICMP_NE)
9878     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9879            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9880            isKnownNonZero(getMinusSCEV(LHS, RHS));
9881 
9882   if (CmpInst::isSigned(Pred))
9883     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9884 
9885   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9886 }
9887 
9888 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9889                                                     const SCEV *LHS,
9890                                                     const SCEV *RHS) {
9891   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9892   // Return Y via OutY.
9893   auto MatchBinaryAddToConst =
9894       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9895              SCEV::NoWrapFlags ExpectedFlags) {
9896     const SCEV *NonConstOp, *ConstOp;
9897     SCEV::NoWrapFlags FlagsPresent;
9898 
9899     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9900         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9901       return false;
9902 
9903     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9904     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9905   };
9906 
9907   APInt C;
9908 
9909   switch (Pred) {
9910   default:
9911     break;
9912 
9913   case ICmpInst::ICMP_SGE:
9914     std::swap(LHS, RHS);
9915     LLVM_FALLTHROUGH;
9916   case ICmpInst::ICMP_SLE:
9917     // X s<= (X + C)<nsw> if C >= 0
9918     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9919       return true;
9920 
9921     // (X + C)<nsw> s<= X if C <= 0
9922     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9923         !C.isStrictlyPositive())
9924       return true;
9925     break;
9926 
9927   case ICmpInst::ICMP_SGT:
9928     std::swap(LHS, RHS);
9929     LLVM_FALLTHROUGH;
9930   case ICmpInst::ICMP_SLT:
9931     // X s< (X + C)<nsw> if C > 0
9932     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9933         C.isStrictlyPositive())
9934       return true;
9935 
9936     // (X + C)<nsw> s< X if C < 0
9937     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9938       return true;
9939     break;
9940 
9941   case ICmpInst::ICMP_UGE:
9942     std::swap(LHS, RHS);
9943     LLVM_FALLTHROUGH;
9944   case ICmpInst::ICMP_ULE:
9945     // X u<= (X + C)<nuw> for any C
9946     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9947       return true;
9948     break;
9949 
9950   case ICmpInst::ICMP_UGT:
9951     std::swap(LHS, RHS);
9952     LLVM_FALLTHROUGH;
9953   case ICmpInst::ICMP_ULT:
9954     // X u< (X + C)<nuw> if C != 0
9955     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9956       return true;
9957     break;
9958   }
9959 
9960   return false;
9961 }
9962 
9963 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9964                                                    const SCEV *LHS,
9965                                                    const SCEV *RHS) {
9966   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9967     return false;
9968 
9969   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9970   // the stack can result in exponential time complexity.
9971   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9972 
9973   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9974   //
9975   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9976   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9977   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9978   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9979   // use isKnownPredicate later if needed.
9980   return isKnownNonNegative(RHS) &&
9981          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9982          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9983 }
9984 
9985 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9986                                         ICmpInst::Predicate Pred,
9987                                         const SCEV *LHS, const SCEV *RHS) {
9988   // No need to even try if we know the module has no guards.
9989   if (!HasGuards)
9990     return false;
9991 
9992   return any_of(*BB, [&](const Instruction &I) {
9993     using namespace llvm::PatternMatch;
9994 
9995     Value *Condition;
9996     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9997                          m_Value(Condition))) &&
9998            isImpliedCond(Pred, LHS, RHS, Condition, false);
9999   });
10000 }
10001 
10002 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10003 /// protected by a conditional between LHS and RHS.  This is used to
10004 /// to eliminate casts.
10005 bool
10006 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10007                                              ICmpInst::Predicate Pred,
10008                                              const SCEV *LHS, const SCEV *RHS) {
10009   // Interpret a null as meaning no loop, where there is obviously no guard
10010   // (interprocedural conditions notwithstanding).
10011   if (!L) return true;
10012 
10013   if (VerifyIR)
10014     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10015            "This cannot be done on broken IR!");
10016 
10017 
10018   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10019     return true;
10020 
10021   BasicBlock *Latch = L->getLoopLatch();
10022   if (!Latch)
10023     return false;
10024 
10025   BranchInst *LoopContinuePredicate =
10026     dyn_cast<BranchInst>(Latch->getTerminator());
10027   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10028       isImpliedCond(Pred, LHS, RHS,
10029                     LoopContinuePredicate->getCondition(),
10030                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10031     return true;
10032 
10033   // We don't want more than one activation of the following loops on the stack
10034   // -- that can lead to O(n!) time complexity.
10035   if (WalkingBEDominatingConds)
10036     return false;
10037 
10038   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10039 
10040   // See if we can exploit a trip count to prove the predicate.
10041   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10042   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10043   if (LatchBECount != getCouldNotCompute()) {
10044     // We know that Latch branches back to the loop header exactly
10045     // LatchBECount times.  This means the backdege condition at Latch is
10046     // equivalent to  "{0,+,1} u< LatchBECount".
10047     Type *Ty = LatchBECount->getType();
10048     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10049     const SCEV *LoopCounter =
10050       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10051     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10052                       LatchBECount))
10053       return true;
10054   }
10055 
10056   // Check conditions due to any @llvm.assume intrinsics.
10057   for (auto &AssumeVH : AC.assumptions()) {
10058     if (!AssumeVH)
10059       continue;
10060     auto *CI = cast<CallInst>(AssumeVH);
10061     if (!DT.dominates(CI, Latch->getTerminator()))
10062       continue;
10063 
10064     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10065       return true;
10066   }
10067 
10068   // If the loop is not reachable from the entry block, we risk running into an
10069   // infinite loop as we walk up into the dom tree.  These loops do not matter
10070   // anyway, so we just return a conservative answer when we see them.
10071   if (!DT.isReachableFromEntry(L->getHeader()))
10072     return false;
10073 
10074   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10075     return true;
10076 
10077   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10078        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10079     assert(DTN && "should reach the loop header before reaching the root!");
10080 
10081     BasicBlock *BB = DTN->getBlock();
10082     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10083       return true;
10084 
10085     BasicBlock *PBB = BB->getSinglePredecessor();
10086     if (!PBB)
10087       continue;
10088 
10089     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10090     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10091       continue;
10092 
10093     Value *Condition = ContinuePredicate->getCondition();
10094 
10095     // If we have an edge `E` within the loop body that dominates the only
10096     // latch, the condition guarding `E` also guards the backedge.  This
10097     // reasoning works only for loops with a single latch.
10098 
10099     BasicBlockEdge DominatingEdge(PBB, BB);
10100     if (DominatingEdge.isSingleEdge()) {
10101       // We're constructively (and conservatively) enumerating edges within the
10102       // loop body that dominate the latch.  The dominator tree better agree
10103       // with us on this:
10104       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10105 
10106       if (isImpliedCond(Pred, LHS, RHS, Condition,
10107                         BB != ContinuePredicate->getSuccessor(0)))
10108         return true;
10109     }
10110   }
10111 
10112   return false;
10113 }
10114 
10115 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10116                                                      ICmpInst::Predicate Pred,
10117                                                      const SCEV *LHS,
10118                                                      const SCEV *RHS) {
10119   if (VerifyIR)
10120     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10121            "This cannot be done on broken IR!");
10122 
10123   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10124   // the facts (a >= b && a != b) separately. A typical situation is when the
10125   // non-strict comparison is known from ranges and non-equality is known from
10126   // dominating predicates. If we are proving strict comparison, we always try
10127   // to prove non-equality and non-strict comparison separately.
10128   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10129   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10130   bool ProvedNonStrictComparison = false;
10131   bool ProvedNonEquality = false;
10132 
10133   auto SplitAndProve =
10134     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10135     if (!ProvedNonStrictComparison)
10136       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10137     if (!ProvedNonEquality)
10138       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10139     if (ProvedNonStrictComparison && ProvedNonEquality)
10140       return true;
10141     return false;
10142   };
10143 
10144   if (ProvingStrictComparison) {
10145     auto ProofFn = [&](ICmpInst::Predicate P) {
10146       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10147     };
10148     if (SplitAndProve(ProofFn))
10149       return true;
10150   }
10151 
10152   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10153   auto ProveViaGuard = [&](const BasicBlock *Block) {
10154     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10155       return true;
10156     if (ProvingStrictComparison) {
10157       auto ProofFn = [&](ICmpInst::Predicate P) {
10158         return isImpliedViaGuard(Block, P, LHS, RHS);
10159       };
10160       if (SplitAndProve(ProofFn))
10161         return true;
10162     }
10163     return false;
10164   };
10165 
10166   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10167   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10168     const Instruction *Context = &BB->front();
10169     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10170       return true;
10171     if (ProvingStrictComparison) {
10172       auto ProofFn = [&](ICmpInst::Predicate P) {
10173         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10174       };
10175       if (SplitAndProve(ProofFn))
10176         return true;
10177     }
10178     return false;
10179   };
10180 
10181   // Starting at the block's predecessor, climb up the predecessor chain, as long
10182   // as there are predecessors that can be found that have unique successors
10183   // leading to the original block.
10184   const Loop *ContainingLoop = LI.getLoopFor(BB);
10185   const BasicBlock *PredBB;
10186   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10187     PredBB = ContainingLoop->getLoopPredecessor();
10188   else
10189     PredBB = BB->getSinglePredecessor();
10190   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10191        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10192     if (ProveViaGuard(Pair.first))
10193       return true;
10194 
10195     const BranchInst *LoopEntryPredicate =
10196         dyn_cast<BranchInst>(Pair.first->getTerminator());
10197     if (!LoopEntryPredicate ||
10198         LoopEntryPredicate->isUnconditional())
10199       continue;
10200 
10201     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10202                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10203       return true;
10204   }
10205 
10206   // Check conditions due to any @llvm.assume intrinsics.
10207   for (auto &AssumeVH : AC.assumptions()) {
10208     if (!AssumeVH)
10209       continue;
10210     auto *CI = cast<CallInst>(AssumeVH);
10211     if (!DT.dominates(CI, BB))
10212       continue;
10213 
10214     if (ProveViaCond(CI->getArgOperand(0), false))
10215       return true;
10216   }
10217 
10218   return false;
10219 }
10220 
10221 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10222                                                ICmpInst::Predicate Pred,
10223                                                const SCEV *LHS,
10224                                                const SCEV *RHS) {
10225   // Interpret a null as meaning no loop, where there is obviously no guard
10226   // (interprocedural conditions notwithstanding).
10227   if (!L)
10228     return false;
10229 
10230   // Both LHS and RHS must be available at loop entry.
10231   assert(isAvailableAtLoopEntry(LHS, L) &&
10232          "LHS is not available at Loop Entry");
10233   assert(isAvailableAtLoopEntry(RHS, L) &&
10234          "RHS is not available at Loop Entry");
10235 
10236   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10237     return true;
10238 
10239   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10240 }
10241 
10242 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10243                                     const SCEV *RHS,
10244                                     const Value *FoundCondValue, bool Inverse,
10245                                     const Instruction *Context) {
10246   // False conditions implies anything. Do not bother analyzing it further.
10247   if (FoundCondValue ==
10248       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10249     return true;
10250 
10251   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10252     return false;
10253 
10254   auto ClearOnExit =
10255       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10256 
10257   // Recursively handle And and Or conditions.
10258   const Value *Op0, *Op1;
10259   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10260     if (!Inverse)
10261       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10262               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10263   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10264     if (Inverse)
10265       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10266               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10267   }
10268 
10269   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10270   if (!ICI) return false;
10271 
10272   // Now that we found a conditional branch that dominates the loop or controls
10273   // the loop latch. Check to see if it is the comparison we are looking for.
10274   ICmpInst::Predicate FoundPred;
10275   if (Inverse)
10276     FoundPred = ICI->getInversePredicate();
10277   else
10278     FoundPred = ICI->getPredicate();
10279 
10280   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10281   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10282 
10283   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10284 }
10285 
10286 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10287                                     const SCEV *RHS,
10288                                     ICmpInst::Predicate FoundPred,
10289                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10290                                     const Instruction *Context) {
10291   // Balance the types.
10292   if (getTypeSizeInBits(LHS->getType()) <
10293       getTypeSizeInBits(FoundLHS->getType())) {
10294     // For unsigned and equality predicates, try to prove that both found
10295     // operands fit into narrow unsigned range. If so, try to prove facts in
10296     // narrow types.
10297     if (!CmpInst::isSigned(FoundPred)) {
10298       auto *NarrowType = LHS->getType();
10299       auto *WideType = FoundLHS->getType();
10300       auto BitWidth = getTypeSizeInBits(NarrowType);
10301       const SCEV *MaxValue = getZeroExtendExpr(
10302           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10303       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10304           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10305         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10306         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10307         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10308                                        TruncFoundRHS, Context))
10309           return true;
10310       }
10311     }
10312 
10313     if (CmpInst::isSigned(Pred)) {
10314       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10315       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10316     } else {
10317       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10318       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10319     }
10320   } else if (getTypeSizeInBits(LHS->getType()) >
10321       getTypeSizeInBits(FoundLHS->getType())) {
10322     if (CmpInst::isSigned(FoundPred)) {
10323       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10324       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10325     } else {
10326       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10327       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10328     }
10329   }
10330   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10331                                     FoundRHS, Context);
10332 }
10333 
10334 bool ScalarEvolution::isImpliedCondBalancedTypes(
10335     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10336     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10337     const Instruction *Context) {
10338   assert(getTypeSizeInBits(LHS->getType()) ==
10339              getTypeSizeInBits(FoundLHS->getType()) &&
10340          "Types should be balanced!");
10341   // Canonicalize the query to match the way instcombine will have
10342   // canonicalized the comparison.
10343   if (SimplifyICmpOperands(Pred, LHS, RHS))
10344     if (LHS == RHS)
10345       return CmpInst::isTrueWhenEqual(Pred);
10346   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10347     if (FoundLHS == FoundRHS)
10348       return CmpInst::isFalseWhenEqual(FoundPred);
10349 
10350   // Check to see if we can make the LHS or RHS match.
10351   if (LHS == FoundRHS || RHS == FoundLHS) {
10352     if (isa<SCEVConstant>(RHS)) {
10353       std::swap(FoundLHS, FoundRHS);
10354       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10355     } else {
10356       std::swap(LHS, RHS);
10357       Pred = ICmpInst::getSwappedPredicate(Pred);
10358     }
10359   }
10360 
10361   // Check whether the found predicate is the same as the desired predicate.
10362   if (FoundPred == Pred)
10363     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10364 
10365   // Check whether swapping the found predicate makes it the same as the
10366   // desired predicate.
10367   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10368     // We can write the implication
10369     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10370     // using one of the following ways:
10371     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10372     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10373     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10374     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10375     // Forms 1. and 2. require swapping the operands of one condition. Don't
10376     // do this if it would break canonical constant/addrec ordering.
10377     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10378       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10379                                    Context);
10380     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10381       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10382 
10383     // There's no clear preference between forms 3. and 4., try both.
10384     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10385                                  FoundLHS, FoundRHS, Context) ||
10386            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10387                                  getNotSCEV(FoundRHS), Context);
10388   }
10389 
10390   // Unsigned comparison is the same as signed comparison when both the operands
10391   // are non-negative.
10392   if (CmpInst::isUnsigned(FoundPred) &&
10393       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10394       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10395     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10396 
10397   // Check if we can make progress by sharpening ranges.
10398   if (FoundPred == ICmpInst::ICMP_NE &&
10399       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10400 
10401     const SCEVConstant *C = nullptr;
10402     const SCEV *V = nullptr;
10403 
10404     if (isa<SCEVConstant>(FoundLHS)) {
10405       C = cast<SCEVConstant>(FoundLHS);
10406       V = FoundRHS;
10407     } else {
10408       C = cast<SCEVConstant>(FoundRHS);
10409       V = FoundLHS;
10410     }
10411 
10412     // The guarding predicate tells us that C != V. If the known range
10413     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10414     // range we consider has to correspond to same signedness as the
10415     // predicate we're interested in folding.
10416 
10417     APInt Min = ICmpInst::isSigned(Pred) ?
10418         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10419 
10420     if (Min == C->getAPInt()) {
10421       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10422       // This is true even if (Min + 1) wraps around -- in case of
10423       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10424 
10425       APInt SharperMin = Min + 1;
10426 
10427       switch (Pred) {
10428         case ICmpInst::ICMP_SGE:
10429         case ICmpInst::ICMP_UGE:
10430           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10431           // RHS, we're done.
10432           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10433                                     Context))
10434             return true;
10435           LLVM_FALLTHROUGH;
10436 
10437         case ICmpInst::ICMP_SGT:
10438         case ICmpInst::ICMP_UGT:
10439           // We know from the range information that (V `Pred` Min ||
10440           // V == Min).  We know from the guarding condition that !(V
10441           // == Min).  This gives us
10442           //
10443           //       V `Pred` Min || V == Min && !(V == Min)
10444           //   =>  V `Pred` Min
10445           //
10446           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10447 
10448           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10449                                     Context))
10450             return true;
10451           break;
10452 
10453         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10454         case ICmpInst::ICMP_SLE:
10455         case ICmpInst::ICMP_ULE:
10456           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10457                                     LHS, V, getConstant(SharperMin), Context))
10458             return true;
10459           LLVM_FALLTHROUGH;
10460 
10461         case ICmpInst::ICMP_SLT:
10462         case ICmpInst::ICMP_ULT:
10463           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10464                                     LHS, V, getConstant(Min), Context))
10465             return true;
10466           break;
10467 
10468         default:
10469           // No change
10470           break;
10471       }
10472     }
10473   }
10474 
10475   // Check whether the actual condition is beyond sufficient.
10476   if (FoundPred == ICmpInst::ICMP_EQ)
10477     if (ICmpInst::isTrueWhenEqual(Pred))
10478       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10479         return true;
10480   if (Pred == ICmpInst::ICMP_NE)
10481     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10482       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10483                                 Context))
10484         return true;
10485 
10486   // Otherwise assume the worst.
10487   return false;
10488 }
10489 
10490 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10491                                      const SCEV *&L, const SCEV *&R,
10492                                      SCEV::NoWrapFlags &Flags) {
10493   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10494   if (!AE || AE->getNumOperands() != 2)
10495     return false;
10496 
10497   L = AE->getOperand(0);
10498   R = AE->getOperand(1);
10499   Flags = AE->getNoWrapFlags();
10500   return true;
10501 }
10502 
10503 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10504                                                            const SCEV *Less) {
10505   // We avoid subtracting expressions here because this function is usually
10506   // fairly deep in the call stack (i.e. is called many times).
10507 
10508   // X - X = 0.
10509   if (More == Less)
10510     return APInt(getTypeSizeInBits(More->getType()), 0);
10511 
10512   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10513     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10514     const auto *MAR = cast<SCEVAddRecExpr>(More);
10515 
10516     if (LAR->getLoop() != MAR->getLoop())
10517       return None;
10518 
10519     // We look at affine expressions only; not for correctness but to keep
10520     // getStepRecurrence cheap.
10521     if (!LAR->isAffine() || !MAR->isAffine())
10522       return None;
10523 
10524     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10525       return None;
10526 
10527     Less = LAR->getStart();
10528     More = MAR->getStart();
10529 
10530     // fall through
10531   }
10532 
10533   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10534     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10535     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10536     return M - L;
10537   }
10538 
10539   SCEV::NoWrapFlags Flags;
10540   const SCEV *LLess = nullptr, *RLess = nullptr;
10541   const SCEV *LMore = nullptr, *RMore = nullptr;
10542   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10543   // Compare (X + C1) vs X.
10544   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10545     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10546       if (RLess == More)
10547         return -(C1->getAPInt());
10548 
10549   // Compare X vs (X + C2).
10550   if (splitBinaryAdd(More, LMore, RMore, Flags))
10551     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10552       if (RMore == Less)
10553         return C2->getAPInt();
10554 
10555   // Compare (X + C1) vs (X + C2).
10556   if (C1 && C2 && RLess == RMore)
10557     return C2->getAPInt() - C1->getAPInt();
10558 
10559   return None;
10560 }
10561 
10562 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10563     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10564     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10565   // Try to recognize the following pattern:
10566   //
10567   //   FoundRHS = ...
10568   // ...
10569   // loop:
10570   //   FoundLHS = {Start,+,W}
10571   // context_bb: // Basic block from the same loop
10572   //   known(Pred, FoundLHS, FoundRHS)
10573   //
10574   // If some predicate is known in the context of a loop, it is also known on
10575   // each iteration of this loop, including the first iteration. Therefore, in
10576   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10577   // prove the original pred using this fact.
10578   if (!Context)
10579     return false;
10580   const BasicBlock *ContextBB = Context->getParent();
10581   // Make sure AR varies in the context block.
10582   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10583     const Loop *L = AR->getLoop();
10584     // Make sure that context belongs to the loop and executes on 1st iteration
10585     // (if it ever executes at all).
10586     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10587       return false;
10588     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10589       return false;
10590     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10591   }
10592 
10593   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10594     const Loop *L = AR->getLoop();
10595     // Make sure that context belongs to the loop and executes on 1st iteration
10596     // (if it ever executes at all).
10597     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10598       return false;
10599     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10600       return false;
10601     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10602   }
10603 
10604   return false;
10605 }
10606 
10607 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10608     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10609     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10610   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10611     return false;
10612 
10613   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10614   if (!AddRecLHS)
10615     return false;
10616 
10617   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10618   if (!AddRecFoundLHS)
10619     return false;
10620 
10621   // We'd like to let SCEV reason about control dependencies, so we constrain
10622   // both the inequalities to be about add recurrences on the same loop.  This
10623   // way we can use isLoopEntryGuardedByCond later.
10624 
10625   const Loop *L = AddRecFoundLHS->getLoop();
10626   if (L != AddRecLHS->getLoop())
10627     return false;
10628 
10629   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10630   //
10631   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10632   //                                                                  ... (2)
10633   //
10634   // Informal proof for (2), assuming (1) [*]:
10635   //
10636   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10637   //
10638   // Then
10639   //
10640   //       FoundLHS s< FoundRHS s< INT_MIN - C
10641   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10642   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10643   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10644   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10645   // <=>  FoundLHS + C s< FoundRHS + C
10646   //
10647   // [*]: (1) can be proved by ruling out overflow.
10648   //
10649   // [**]: This can be proved by analyzing all the four possibilities:
10650   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10651   //    (A s>= 0, B s>= 0).
10652   //
10653   // Note:
10654   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10655   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10656   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10657   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10658   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10659   // C)".
10660 
10661   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10662   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10663   if (!LDiff || !RDiff || *LDiff != *RDiff)
10664     return false;
10665 
10666   if (LDiff->isMinValue())
10667     return true;
10668 
10669   APInt FoundRHSLimit;
10670 
10671   if (Pred == CmpInst::ICMP_ULT) {
10672     FoundRHSLimit = -(*RDiff);
10673   } else {
10674     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10675     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10676   }
10677 
10678   // Try to prove (1) or (2), as needed.
10679   return isAvailableAtLoopEntry(FoundRHS, L) &&
10680          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10681                                   getConstant(FoundRHSLimit));
10682 }
10683 
10684 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10685                                         const SCEV *LHS, const SCEV *RHS,
10686                                         const SCEV *FoundLHS,
10687                                         const SCEV *FoundRHS, unsigned Depth) {
10688   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10689 
10690   auto ClearOnExit = make_scope_exit([&]() {
10691     if (LPhi) {
10692       bool Erased = PendingMerges.erase(LPhi);
10693       assert(Erased && "Failed to erase LPhi!");
10694       (void)Erased;
10695     }
10696     if (RPhi) {
10697       bool Erased = PendingMerges.erase(RPhi);
10698       assert(Erased && "Failed to erase RPhi!");
10699       (void)Erased;
10700     }
10701   });
10702 
10703   // Find respective Phis and check that they are not being pending.
10704   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10705     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10706       if (!PendingMerges.insert(Phi).second)
10707         return false;
10708       LPhi = Phi;
10709     }
10710   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10711     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10712       // If we detect a loop of Phi nodes being processed by this method, for
10713       // example:
10714       //
10715       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10716       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10717       //
10718       // we don't want to deal with a case that complex, so return conservative
10719       // answer false.
10720       if (!PendingMerges.insert(Phi).second)
10721         return false;
10722       RPhi = Phi;
10723     }
10724 
10725   // If none of LHS, RHS is a Phi, nothing to do here.
10726   if (!LPhi && !RPhi)
10727     return false;
10728 
10729   // If there is a SCEVUnknown Phi we are interested in, make it left.
10730   if (!LPhi) {
10731     std::swap(LHS, RHS);
10732     std::swap(FoundLHS, FoundRHS);
10733     std::swap(LPhi, RPhi);
10734     Pred = ICmpInst::getSwappedPredicate(Pred);
10735   }
10736 
10737   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10738   const BasicBlock *LBB = LPhi->getParent();
10739   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10740 
10741   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10742     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10743            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10744            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10745   };
10746 
10747   if (RPhi && RPhi->getParent() == LBB) {
10748     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10749     // If we compare two Phis from the same block, and for each entry block
10750     // the predicate is true for incoming values from this block, then the
10751     // predicate is also true for the Phis.
10752     for (const BasicBlock *IncBB : predecessors(LBB)) {
10753       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10754       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10755       if (!ProvedEasily(L, R))
10756         return false;
10757     }
10758   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10759     // Case two: RHS is also a Phi from the same basic block, and it is an
10760     // AddRec. It means that there is a loop which has both AddRec and Unknown
10761     // PHIs, for it we can compare incoming values of AddRec from above the loop
10762     // and latch with their respective incoming values of LPhi.
10763     // TODO: Generalize to handle loops with many inputs in a header.
10764     if (LPhi->getNumIncomingValues() != 2) return false;
10765 
10766     auto *RLoop = RAR->getLoop();
10767     auto *Predecessor = RLoop->getLoopPredecessor();
10768     assert(Predecessor && "Loop with AddRec with no predecessor?");
10769     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10770     if (!ProvedEasily(L1, RAR->getStart()))
10771       return false;
10772     auto *Latch = RLoop->getLoopLatch();
10773     assert(Latch && "Loop with AddRec with no latch?");
10774     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10775     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10776       return false;
10777   } else {
10778     // In all other cases go over inputs of LHS and compare each of them to RHS,
10779     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10780     // At this point RHS is either a non-Phi, or it is a Phi from some block
10781     // different from LBB.
10782     for (const BasicBlock *IncBB : predecessors(LBB)) {
10783       // Check that RHS is available in this block.
10784       if (!dominates(RHS, IncBB))
10785         return false;
10786       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10787       if (!ProvedEasily(L, RHS))
10788         return false;
10789     }
10790   }
10791   return true;
10792 }
10793 
10794 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10795                                             const SCEV *LHS, const SCEV *RHS,
10796                                             const SCEV *FoundLHS,
10797                                             const SCEV *FoundRHS,
10798                                             const Instruction *Context) {
10799   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10800     return true;
10801 
10802   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10803     return true;
10804 
10805   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10806                                           Context))
10807     return true;
10808 
10809   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10810                                      FoundLHS, FoundRHS);
10811 }
10812 
10813 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10814 template <typename MinMaxExprType>
10815 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10816                                  const SCEV *Candidate) {
10817   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10818   if (!MinMaxExpr)
10819     return false;
10820 
10821   return is_contained(MinMaxExpr->operands(), Candidate);
10822 }
10823 
10824 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10825                                            ICmpInst::Predicate Pred,
10826                                            const SCEV *LHS, const SCEV *RHS) {
10827   // If both sides are affine addrecs for the same loop, with equal
10828   // steps, and we know the recurrences don't wrap, then we only
10829   // need to check the predicate on the starting values.
10830 
10831   if (!ICmpInst::isRelational(Pred))
10832     return false;
10833 
10834   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10835   if (!LAR)
10836     return false;
10837   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10838   if (!RAR)
10839     return false;
10840   if (LAR->getLoop() != RAR->getLoop())
10841     return false;
10842   if (!LAR->isAffine() || !RAR->isAffine())
10843     return false;
10844 
10845   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10846     return false;
10847 
10848   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10849                          SCEV::FlagNSW : SCEV::FlagNUW;
10850   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10851     return false;
10852 
10853   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10854 }
10855 
10856 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10857 /// expression?
10858 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10859                                         ICmpInst::Predicate Pred,
10860                                         const SCEV *LHS, const SCEV *RHS) {
10861   switch (Pred) {
10862   default:
10863     return false;
10864 
10865   case ICmpInst::ICMP_SGE:
10866     std::swap(LHS, RHS);
10867     LLVM_FALLTHROUGH;
10868   case ICmpInst::ICMP_SLE:
10869     return
10870         // min(A, ...) <= A
10871         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10872         // A <= max(A, ...)
10873         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10874 
10875   case ICmpInst::ICMP_UGE:
10876     std::swap(LHS, RHS);
10877     LLVM_FALLTHROUGH;
10878   case ICmpInst::ICMP_ULE:
10879     return
10880         // min(A, ...) <= A
10881         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10882         // A <= max(A, ...)
10883         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10884   }
10885 
10886   llvm_unreachable("covered switch fell through?!");
10887 }
10888 
10889 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10890                                              const SCEV *LHS, const SCEV *RHS,
10891                                              const SCEV *FoundLHS,
10892                                              const SCEV *FoundRHS,
10893                                              unsigned Depth) {
10894   assert(getTypeSizeInBits(LHS->getType()) ==
10895              getTypeSizeInBits(RHS->getType()) &&
10896          "LHS and RHS have different sizes?");
10897   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10898              getTypeSizeInBits(FoundRHS->getType()) &&
10899          "FoundLHS and FoundRHS have different sizes?");
10900   // We want to avoid hurting the compile time with analysis of too big trees.
10901   if (Depth > MaxSCEVOperationsImplicationDepth)
10902     return false;
10903 
10904   // We only want to work with GT comparison so far.
10905   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10906     Pred = CmpInst::getSwappedPredicate(Pred);
10907     std::swap(LHS, RHS);
10908     std::swap(FoundLHS, FoundRHS);
10909   }
10910 
10911   // For unsigned, try to reduce it to corresponding signed comparison.
10912   if (Pred == ICmpInst::ICMP_UGT)
10913     // We can replace unsigned predicate with its signed counterpart if all
10914     // involved values are non-negative.
10915     // TODO: We could have better support for unsigned.
10916     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10917       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10918       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10919       // use this fact to prove that LHS and RHS are non-negative.
10920       const SCEV *MinusOne = getMinusOne(LHS->getType());
10921       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10922                                 FoundRHS) &&
10923           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10924                                 FoundRHS))
10925         Pred = ICmpInst::ICMP_SGT;
10926     }
10927 
10928   if (Pred != ICmpInst::ICMP_SGT)
10929     return false;
10930 
10931   auto GetOpFromSExt = [&](const SCEV *S) {
10932     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10933       return Ext->getOperand();
10934     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10935     // the constant in some cases.
10936     return S;
10937   };
10938 
10939   // Acquire values from extensions.
10940   auto *OrigLHS = LHS;
10941   auto *OrigFoundLHS = FoundLHS;
10942   LHS = GetOpFromSExt(LHS);
10943   FoundLHS = GetOpFromSExt(FoundLHS);
10944 
10945   // Is the SGT predicate can be proved trivially or using the found context.
10946   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10947     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10948            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10949                                   FoundRHS, Depth + 1);
10950   };
10951 
10952   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10953     // We want to avoid creation of any new non-constant SCEV. Since we are
10954     // going to compare the operands to RHS, we should be certain that we don't
10955     // need any size extensions for this. So let's decline all cases when the
10956     // sizes of types of LHS and RHS do not match.
10957     // TODO: Maybe try to get RHS from sext to catch more cases?
10958     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10959       return false;
10960 
10961     // Should not overflow.
10962     if (!LHSAddExpr->hasNoSignedWrap())
10963       return false;
10964 
10965     auto *LL = LHSAddExpr->getOperand(0);
10966     auto *LR = LHSAddExpr->getOperand(1);
10967     auto *MinusOne = getMinusOne(RHS->getType());
10968 
10969     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10970     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10971       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10972     };
10973     // Try to prove the following rule:
10974     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10975     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10976     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10977       return true;
10978   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10979     Value *LL, *LR;
10980     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10981 
10982     using namespace llvm::PatternMatch;
10983 
10984     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10985       // Rules for division.
10986       // We are going to perform some comparisons with Denominator and its
10987       // derivative expressions. In general case, creating a SCEV for it may
10988       // lead to a complex analysis of the entire graph, and in particular it
10989       // can request trip count recalculation for the same loop. This would
10990       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10991       // this, we only want to create SCEVs that are constants in this section.
10992       // So we bail if Denominator is not a constant.
10993       if (!isa<ConstantInt>(LR))
10994         return false;
10995 
10996       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10997 
10998       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10999       // then a SCEV for the numerator already exists and matches with FoundLHS.
11000       auto *Numerator = getExistingSCEV(LL);
11001       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11002         return false;
11003 
11004       // Make sure that the numerator matches with FoundLHS and the denominator
11005       // is positive.
11006       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11007         return false;
11008 
11009       auto *DTy = Denominator->getType();
11010       auto *FRHSTy = FoundRHS->getType();
11011       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11012         // One of types is a pointer and another one is not. We cannot extend
11013         // them properly to a wider type, so let us just reject this case.
11014         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11015         // to avoid this check.
11016         return false;
11017 
11018       // Given that:
11019       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11020       auto *WTy = getWiderType(DTy, FRHSTy);
11021       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11022       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11023 
11024       // Try to prove the following rule:
11025       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11026       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11027       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11028       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11029       if (isKnownNonPositive(RHS) &&
11030           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11031         return true;
11032 
11033       // Try to prove the following rule:
11034       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11035       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11036       // If we divide it by Denominator > 2, then:
11037       // 1. If FoundLHS is negative, then the result is 0.
11038       // 2. If FoundLHS is non-negative, then the result is non-negative.
11039       // Anyways, the result is non-negative.
11040       auto *MinusOne = getMinusOne(WTy);
11041       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11042       if (isKnownNegative(RHS) &&
11043           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11044         return true;
11045     }
11046   }
11047 
11048   // If our expression contained SCEVUnknown Phis, and we split it down and now
11049   // need to prove something for them, try to prove the predicate for every
11050   // possible incoming values of those Phis.
11051   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11052     return true;
11053 
11054   return false;
11055 }
11056 
11057 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11058                                         const SCEV *LHS, const SCEV *RHS) {
11059   // zext x u<= sext x, sext x s<= zext x
11060   switch (Pred) {
11061   case ICmpInst::ICMP_SGE:
11062     std::swap(LHS, RHS);
11063     LLVM_FALLTHROUGH;
11064   case ICmpInst::ICMP_SLE: {
11065     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11066     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11067     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11068     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11069       return true;
11070     break;
11071   }
11072   case ICmpInst::ICMP_UGE:
11073     std::swap(LHS, RHS);
11074     LLVM_FALLTHROUGH;
11075   case ICmpInst::ICMP_ULE: {
11076     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11077     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11078     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11079     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11080       return true;
11081     break;
11082   }
11083   default:
11084     break;
11085   };
11086   return false;
11087 }
11088 
11089 bool
11090 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11091                                            const SCEV *LHS, const SCEV *RHS) {
11092   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11093          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11094          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11095          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11096          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11097 }
11098 
11099 bool
11100 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11101                                              const SCEV *LHS, const SCEV *RHS,
11102                                              const SCEV *FoundLHS,
11103                                              const SCEV *FoundRHS) {
11104   switch (Pred) {
11105   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11106   case ICmpInst::ICMP_EQ:
11107   case ICmpInst::ICMP_NE:
11108     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11109       return true;
11110     break;
11111   case ICmpInst::ICMP_SLT:
11112   case ICmpInst::ICMP_SLE:
11113     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11114         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11115       return true;
11116     break;
11117   case ICmpInst::ICMP_SGT:
11118   case ICmpInst::ICMP_SGE:
11119     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11120         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11121       return true;
11122     break;
11123   case ICmpInst::ICMP_ULT:
11124   case ICmpInst::ICMP_ULE:
11125     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11126         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11127       return true;
11128     break;
11129   case ICmpInst::ICMP_UGT:
11130   case ICmpInst::ICMP_UGE:
11131     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11132         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11133       return true;
11134     break;
11135   }
11136 
11137   // Maybe it can be proved via operations?
11138   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11139     return true;
11140 
11141   return false;
11142 }
11143 
11144 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11145                                                      const SCEV *LHS,
11146                                                      const SCEV *RHS,
11147                                                      const SCEV *FoundLHS,
11148                                                      const SCEV *FoundRHS) {
11149   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11150     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11151     // reduce the compile time impact of this optimization.
11152     return false;
11153 
11154   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11155   if (!Addend)
11156     return false;
11157 
11158   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11159 
11160   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11161   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11162   ConstantRange FoundLHSRange =
11163       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
11164 
11165   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11166   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11167 
11168   // We can also compute the range of values for `LHS` that satisfy the
11169   // consequent, "`LHS` `Pred` `RHS`":
11170   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11171   // The antecedent implies the consequent if every value of `LHS` that
11172   // satisfies the antecedent also satisfies the consequent.
11173   return LHSRange.icmp(Pred, ConstRHS);
11174 }
11175 
11176 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11177                                          bool IsSigned, bool NoWrap) {
11178   assert(isKnownPositive(Stride) && "Positive stride expected!");
11179 
11180   if (NoWrap) return false;
11181 
11182   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11183   const SCEV *One = getOne(Stride->getType());
11184 
11185   if (IsSigned) {
11186     APInt MaxRHS = getSignedRangeMax(RHS);
11187     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11188     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11189 
11190     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11191     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11192   }
11193 
11194   APInt MaxRHS = getUnsignedRangeMax(RHS);
11195   APInt MaxValue = APInt::getMaxValue(BitWidth);
11196   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11197 
11198   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11199   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11200 }
11201 
11202 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11203                                          bool IsSigned, bool NoWrap) {
11204   if (NoWrap) return false;
11205 
11206   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11207   const SCEV *One = getOne(Stride->getType());
11208 
11209   if (IsSigned) {
11210     APInt MinRHS = getSignedRangeMin(RHS);
11211     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11212     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11213 
11214     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11215     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11216   }
11217 
11218   APInt MinRHS = getUnsignedRangeMin(RHS);
11219   APInt MinValue = APInt::getMinValue(BitWidth);
11220   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11221 
11222   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11223   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11224 }
11225 
11226 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11227                                             bool Equality) {
11228   const SCEV *One = getOne(Step->getType());
11229   Delta = Equality ? getAddExpr(Delta, Step)
11230                    : getAddExpr(Delta, getMinusSCEV(Step, One));
11231   return getUDivExpr(Delta, Step);
11232 }
11233 
11234 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11235                                                     const SCEV *Stride,
11236                                                     const SCEV *End,
11237                                                     unsigned BitWidth,
11238                                                     bool IsSigned) {
11239 
11240   assert(!isKnownNonPositive(Stride) &&
11241          "Stride is expected strictly positive!");
11242   // Calculate the maximum backedge count based on the range of values
11243   // permitted by Start, End, and Stride.
11244   const SCEV *MaxBECount;
11245   APInt MinStart =
11246       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11247 
11248   APInt StrideForMaxBECount =
11249       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11250 
11251   // We already know that the stride is positive, so we paper over conservatism
11252   // in our range computation by forcing StrideForMaxBECount to be at least one.
11253   // In theory this is unnecessary, but we expect MaxBECount to be a
11254   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11255   // is nothing to constant fold it to).
11256   APInt One(BitWidth, 1, IsSigned);
11257   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11258 
11259   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11260                             : APInt::getMaxValue(BitWidth);
11261   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11262 
11263   // Although End can be a MAX expression we estimate MaxEnd considering only
11264   // the case End = RHS of the loop termination condition. This is safe because
11265   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11266   // taken count.
11267   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11268                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11269 
11270   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11271                               getConstant(StrideForMaxBECount) /* Step */,
11272                               false /* Equality */);
11273 
11274   return MaxBECount;
11275 }
11276 
11277 ScalarEvolution::ExitLimit
11278 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11279                                   const Loop *L, bool IsSigned,
11280                                   bool ControlsExit, bool AllowPredicates) {
11281   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11282 
11283   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11284   bool PredicatedIV = false;
11285 
11286   if (!IV && AllowPredicates) {
11287     // Try to make this an AddRec using runtime tests, in the first X
11288     // iterations of this loop, where X is the SCEV expression found by the
11289     // algorithm below.
11290     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11291     PredicatedIV = true;
11292   }
11293 
11294   // Avoid weird loops
11295   if (!IV || IV->getLoop() != L || !IV->isAffine())
11296     return getCouldNotCompute();
11297 
11298   bool NoWrap = ControlsExit &&
11299                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11300 
11301   const SCEV *Stride = IV->getStepRecurrence(*this);
11302 
11303   bool PositiveStride = isKnownPositive(Stride);
11304 
11305   // Avoid negative or zero stride values.
11306   if (!PositiveStride) {
11307     // We can compute the correct backedge taken count for loops with unknown
11308     // strides if we can prove that the loop is not an infinite loop with side
11309     // effects. Here's the loop structure we are trying to handle -
11310     //
11311     // i = start
11312     // do {
11313     //   A[i] = i;
11314     //   i += s;
11315     // } while (i < end);
11316     //
11317     // The backedge taken count for such loops is evaluated as -
11318     // (max(end, start + stride) - start - 1) /u stride
11319     //
11320     // The additional preconditions that we need to check to prove correctness
11321     // of the above formula is as follows -
11322     //
11323     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11324     //    NoWrap flag).
11325     // b) loop is single exit with no side effects.
11326     //
11327     //
11328     // Precondition a) implies that if the stride is negative, this is a single
11329     // trip loop. The backedge taken count formula reduces to zero in this case.
11330     //
11331     // Precondition b) implies that the unknown stride cannot be zero otherwise
11332     // we have UB.
11333     //
11334     // The positive stride case is the same as isKnownPositive(Stride) returning
11335     // true (original behavior of the function).
11336     //
11337     // We want to make sure that the stride is truly unknown as there are edge
11338     // cases where ScalarEvolution propagates no wrap flags to the
11339     // post-increment/decrement IV even though the increment/decrement operation
11340     // itself is wrapping. The computed backedge taken count may be wrong in
11341     // such cases. This is prevented by checking that the stride is not known to
11342     // be either positive or non-positive. For example, no wrap flags are
11343     // propagated to the post-increment IV of this loop with a trip count of 2 -
11344     //
11345     // unsigned char i;
11346     // for(i=127; i<128; i+=129)
11347     //   A[i] = i;
11348     //
11349     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11350         !loopHasNoSideEffects(L))
11351       return getCouldNotCompute();
11352   } else if (!Stride->isOne() &&
11353              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11354     // Avoid proven overflow cases: this will ensure that the backedge taken
11355     // count will not generate any unsigned overflow. Relaxed no-overflow
11356     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11357     // undefined behaviors like the case of C language.
11358     return getCouldNotCompute();
11359 
11360   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11361                                       : ICmpInst::ICMP_ULT;
11362   const SCEV *Start = IV->getStart();
11363   const SCEV *End = RHS;
11364   // When the RHS is not invariant, we do not know the end bound of the loop and
11365   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11366   // calculate the MaxBECount, given the start, stride and max value for the end
11367   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11368   // checked above).
11369   if (!isLoopInvariant(RHS, L)) {
11370     const SCEV *MaxBECount = computeMaxBECountForLT(
11371         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11372     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11373                      false /*MaxOrZero*/, Predicates);
11374   }
11375   // If the backedge is taken at least once, then it will be taken
11376   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11377   // is the LHS value of the less-than comparison the first time it is evaluated
11378   // and End is the RHS.
11379   const SCEV *BECountIfBackedgeTaken =
11380     computeBECount(getMinusSCEV(End, Start), Stride, false);
11381   // If the loop entry is guarded by the result of the backedge test of the
11382   // first loop iteration, then we know the backedge will be taken at least
11383   // once and so the backedge taken count is as above. If not then we use the
11384   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11385   // as if the backedge is taken at least once max(End,Start) is End and so the
11386   // result is as above, and if not max(End,Start) is Start so we get a backedge
11387   // count of zero.
11388   const SCEV *BECount;
11389   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11390     BECount = BECountIfBackedgeTaken;
11391   else {
11392     // If we know that RHS >= Start in the context of loop, then we know that
11393     // max(RHS, Start) = RHS at this point.
11394     if (isLoopEntryGuardedByCond(
11395             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11396       End = RHS;
11397     else
11398       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11399     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11400   }
11401 
11402   const SCEV *MaxBECount;
11403   bool MaxOrZero = false;
11404   if (isa<SCEVConstant>(BECount))
11405     MaxBECount = BECount;
11406   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11407     // If we know exactly how many times the backedge will be taken if it's
11408     // taken at least once, then the backedge count will either be that or
11409     // zero.
11410     MaxBECount = BECountIfBackedgeTaken;
11411     MaxOrZero = true;
11412   } else {
11413     MaxBECount = computeMaxBECountForLT(
11414         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11415   }
11416 
11417   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11418       !isa<SCEVCouldNotCompute>(BECount))
11419     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11420 
11421   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11422 }
11423 
11424 ScalarEvolution::ExitLimit
11425 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11426                                      const Loop *L, bool IsSigned,
11427                                      bool ControlsExit, bool AllowPredicates) {
11428   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11429   // We handle only IV > Invariant
11430   if (!isLoopInvariant(RHS, L))
11431     return getCouldNotCompute();
11432 
11433   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11434   if (!IV && AllowPredicates)
11435     // Try to make this an AddRec using runtime tests, in the first X
11436     // iterations of this loop, where X is the SCEV expression found by the
11437     // algorithm below.
11438     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11439 
11440   // Avoid weird loops
11441   if (!IV || IV->getLoop() != L || !IV->isAffine())
11442     return getCouldNotCompute();
11443 
11444   bool NoWrap = ControlsExit &&
11445                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11446 
11447   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11448 
11449   // Avoid negative or zero stride values
11450   if (!isKnownPositive(Stride))
11451     return getCouldNotCompute();
11452 
11453   // Avoid proven overflow cases: this will ensure that the backedge taken count
11454   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11455   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11456   // behaviors like the case of C language.
11457   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11458     return getCouldNotCompute();
11459 
11460   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11461                                       : ICmpInst::ICMP_UGT;
11462 
11463   const SCEV *Start = IV->getStart();
11464   const SCEV *End = RHS;
11465   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11466     // If we know that Start >= RHS in the context of loop, then we know that
11467     // min(RHS, Start) = RHS at this point.
11468     if (isLoopEntryGuardedByCond(
11469             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11470       End = RHS;
11471     else
11472       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11473   }
11474 
11475   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11476 
11477   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11478                             : getUnsignedRangeMax(Start);
11479 
11480   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11481                              : getUnsignedRangeMin(Stride);
11482 
11483   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11484   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11485                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11486 
11487   // Although End can be a MIN expression we estimate MinEnd considering only
11488   // the case End = RHS. This is safe because in the other case (Start - End)
11489   // is zero, leading to a zero maximum backedge taken count.
11490   APInt MinEnd =
11491     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11492              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11493 
11494   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11495                                ? BECount
11496                                : computeBECount(getConstant(MaxStart - MinEnd),
11497                                                 getConstant(MinStride), false);
11498 
11499   if (isa<SCEVCouldNotCompute>(MaxBECount))
11500     MaxBECount = BECount;
11501 
11502   return ExitLimit(BECount, MaxBECount, false, Predicates);
11503 }
11504 
11505 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11506                                                     ScalarEvolution &SE) const {
11507   if (Range.isFullSet())  // Infinite loop.
11508     return SE.getCouldNotCompute();
11509 
11510   // If the start is a non-zero constant, shift the range to simplify things.
11511   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11512     if (!SC->getValue()->isZero()) {
11513       SmallVector<const SCEV *, 4> Operands(operands());
11514       Operands[0] = SE.getZero(SC->getType());
11515       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11516                                              getNoWrapFlags(FlagNW));
11517       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11518         return ShiftedAddRec->getNumIterationsInRange(
11519             Range.subtract(SC->getAPInt()), SE);
11520       // This is strange and shouldn't happen.
11521       return SE.getCouldNotCompute();
11522     }
11523 
11524   // The only time we can solve this is when we have all constant indices.
11525   // Otherwise, we cannot determine the overflow conditions.
11526   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11527     return SE.getCouldNotCompute();
11528 
11529   // Okay at this point we know that all elements of the chrec are constants and
11530   // that the start element is zero.
11531 
11532   // First check to see if the range contains zero.  If not, the first
11533   // iteration exits.
11534   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11535   if (!Range.contains(APInt(BitWidth, 0)))
11536     return SE.getZero(getType());
11537 
11538   if (isAffine()) {
11539     // If this is an affine expression then we have this situation:
11540     //   Solve {0,+,A} in Range  ===  Ax in Range
11541 
11542     // We know that zero is in the range.  If A is positive then we know that
11543     // the upper value of the range must be the first possible exit value.
11544     // If A is negative then the lower of the range is the last possible loop
11545     // value.  Also note that we already checked for a full range.
11546     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11547     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11548 
11549     // The exit value should be (End+A)/A.
11550     APInt ExitVal = (End + A).udiv(A);
11551     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11552 
11553     // Evaluate at the exit value.  If we really did fall out of the valid
11554     // range, then we computed our trip count, otherwise wrap around or other
11555     // things must have happened.
11556     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11557     if (Range.contains(Val->getValue()))
11558       return SE.getCouldNotCompute();  // Something strange happened
11559 
11560     // Ensure that the previous value is in the range.  This is a sanity check.
11561     assert(Range.contains(
11562            EvaluateConstantChrecAtConstant(this,
11563            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11564            "Linear scev computation is off in a bad way!");
11565     return SE.getConstant(ExitValue);
11566   }
11567 
11568   if (isQuadratic()) {
11569     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11570       return SE.getConstant(S.getValue());
11571   }
11572 
11573   return SE.getCouldNotCompute();
11574 }
11575 
11576 const SCEVAddRecExpr *
11577 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11578   assert(getNumOperands() > 1 && "AddRec with zero step?");
11579   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11580   // but in this case we cannot guarantee that the value returned will be an
11581   // AddRec because SCEV does not have a fixed point where it stops
11582   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11583   // may happen if we reach arithmetic depth limit while simplifying. So we
11584   // construct the returned value explicitly.
11585   SmallVector<const SCEV *, 3> Ops;
11586   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11587   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11588   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11589     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11590   // We know that the last operand is not a constant zero (otherwise it would
11591   // have been popped out earlier). This guarantees us that if the result has
11592   // the same last operand, then it will also not be popped out, meaning that
11593   // the returned value will be an AddRec.
11594   const SCEV *Last = getOperand(getNumOperands() - 1);
11595   assert(!Last->isZero() && "Recurrency with zero step?");
11596   Ops.push_back(Last);
11597   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11598                                                SCEV::FlagAnyWrap));
11599 }
11600 
11601 // Return true when S contains at least an undef value.
11602 static inline bool containsUndefs(const SCEV *S) {
11603   return SCEVExprContains(S, [](const SCEV *S) {
11604     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11605       return isa<UndefValue>(SU->getValue());
11606     return false;
11607   });
11608 }
11609 
11610 namespace {
11611 
11612 // Collect all steps of SCEV expressions.
11613 struct SCEVCollectStrides {
11614   ScalarEvolution &SE;
11615   SmallVectorImpl<const SCEV *> &Strides;
11616 
11617   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11618       : SE(SE), Strides(S) {}
11619 
11620   bool follow(const SCEV *S) {
11621     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11622       Strides.push_back(AR->getStepRecurrence(SE));
11623     return true;
11624   }
11625 
11626   bool isDone() const { return false; }
11627 };
11628 
11629 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11630 struct SCEVCollectTerms {
11631   SmallVectorImpl<const SCEV *> &Terms;
11632 
11633   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11634 
11635   bool follow(const SCEV *S) {
11636     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11637         isa<SCEVSignExtendExpr>(S)) {
11638       if (!containsUndefs(S))
11639         Terms.push_back(S);
11640 
11641       // Stop recursion: once we collected a term, do not walk its operands.
11642       return false;
11643     }
11644 
11645     // Keep looking.
11646     return true;
11647   }
11648 
11649   bool isDone() const { return false; }
11650 };
11651 
11652 // Check if a SCEV contains an AddRecExpr.
11653 struct SCEVHasAddRec {
11654   bool &ContainsAddRec;
11655 
11656   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11657     ContainsAddRec = false;
11658   }
11659 
11660   bool follow(const SCEV *S) {
11661     if (isa<SCEVAddRecExpr>(S)) {
11662       ContainsAddRec = true;
11663 
11664       // Stop recursion: once we collected a term, do not walk its operands.
11665       return false;
11666     }
11667 
11668     // Keep looking.
11669     return true;
11670   }
11671 
11672   bool isDone() const { return false; }
11673 };
11674 
11675 // Find factors that are multiplied with an expression that (possibly as a
11676 // subexpression) contains an AddRecExpr. In the expression:
11677 //
11678 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11679 //
11680 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11681 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11682 // parameters as they form a product with an induction variable.
11683 //
11684 // This collector expects all array size parameters to be in the same MulExpr.
11685 // It might be necessary to later add support for collecting parameters that are
11686 // spread over different nested MulExpr.
11687 struct SCEVCollectAddRecMultiplies {
11688   SmallVectorImpl<const SCEV *> &Terms;
11689   ScalarEvolution &SE;
11690 
11691   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11692       : Terms(T), SE(SE) {}
11693 
11694   bool follow(const SCEV *S) {
11695     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11696       bool HasAddRec = false;
11697       SmallVector<const SCEV *, 0> Operands;
11698       for (auto Op : Mul->operands()) {
11699         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11700         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11701           Operands.push_back(Op);
11702         } else if (Unknown) {
11703           HasAddRec = true;
11704         } else {
11705           bool ContainsAddRec = false;
11706           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11707           visitAll(Op, ContiansAddRec);
11708           HasAddRec |= ContainsAddRec;
11709         }
11710       }
11711       if (Operands.size() == 0)
11712         return true;
11713 
11714       if (!HasAddRec)
11715         return false;
11716 
11717       Terms.push_back(SE.getMulExpr(Operands));
11718       // Stop recursion: once we collected a term, do not walk its operands.
11719       return false;
11720     }
11721 
11722     // Keep looking.
11723     return true;
11724   }
11725 
11726   bool isDone() const { return false; }
11727 };
11728 
11729 } // end anonymous namespace
11730 
11731 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11732 /// two places:
11733 ///   1) The strides of AddRec expressions.
11734 ///   2) Unknowns that are multiplied with AddRec expressions.
11735 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11736     SmallVectorImpl<const SCEV *> &Terms) {
11737   SmallVector<const SCEV *, 4> Strides;
11738   SCEVCollectStrides StrideCollector(*this, Strides);
11739   visitAll(Expr, StrideCollector);
11740 
11741   LLVM_DEBUG({
11742     dbgs() << "Strides:\n";
11743     for (const SCEV *S : Strides)
11744       dbgs() << *S << "\n";
11745   });
11746 
11747   for (const SCEV *S : Strides) {
11748     SCEVCollectTerms TermCollector(Terms);
11749     visitAll(S, TermCollector);
11750   }
11751 
11752   LLVM_DEBUG({
11753     dbgs() << "Terms:\n";
11754     for (const SCEV *T : Terms)
11755       dbgs() << *T << "\n";
11756   });
11757 
11758   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11759   visitAll(Expr, MulCollector);
11760 }
11761 
11762 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11763                                    SmallVectorImpl<const SCEV *> &Terms,
11764                                    SmallVectorImpl<const SCEV *> &Sizes) {
11765   int Last = Terms.size() - 1;
11766   const SCEV *Step = Terms[Last];
11767 
11768   // End of recursion.
11769   if (Last == 0) {
11770     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11771       SmallVector<const SCEV *, 2> Qs;
11772       for (const SCEV *Op : M->operands())
11773         if (!isa<SCEVConstant>(Op))
11774           Qs.push_back(Op);
11775 
11776       Step = SE.getMulExpr(Qs);
11777     }
11778 
11779     Sizes.push_back(Step);
11780     return true;
11781   }
11782 
11783   for (const SCEV *&Term : Terms) {
11784     // Normalize the terms before the next call to findArrayDimensionsRec.
11785     const SCEV *Q, *R;
11786     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11787 
11788     // Bail out when GCD does not evenly divide one of the terms.
11789     if (!R->isZero())
11790       return false;
11791 
11792     Term = Q;
11793   }
11794 
11795   // Remove all SCEVConstants.
11796   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
11797 
11798   if (Terms.size() > 0)
11799     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11800       return false;
11801 
11802   Sizes.push_back(Step);
11803   return true;
11804 }
11805 
11806 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11807 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11808   for (const SCEV *T : Terms)
11809     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11810       return true;
11811 
11812   return false;
11813 }
11814 
11815 // Return the number of product terms in S.
11816 static inline int numberOfTerms(const SCEV *S) {
11817   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11818     return Expr->getNumOperands();
11819   return 1;
11820 }
11821 
11822 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11823   if (isa<SCEVConstant>(T))
11824     return nullptr;
11825 
11826   if (isa<SCEVUnknown>(T))
11827     return T;
11828 
11829   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11830     SmallVector<const SCEV *, 2> Factors;
11831     for (const SCEV *Op : M->operands())
11832       if (!isa<SCEVConstant>(Op))
11833         Factors.push_back(Op);
11834 
11835     return SE.getMulExpr(Factors);
11836   }
11837 
11838   return T;
11839 }
11840 
11841 /// Return the size of an element read or written by Inst.
11842 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11843   Type *Ty;
11844   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11845     Ty = Store->getValueOperand()->getType();
11846   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11847     Ty = Load->getType();
11848   else
11849     return nullptr;
11850 
11851   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11852   return getSizeOfExpr(ETy, Ty);
11853 }
11854 
11855 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11856                                           SmallVectorImpl<const SCEV *> &Sizes,
11857                                           const SCEV *ElementSize) {
11858   if (Terms.size() < 1 || !ElementSize)
11859     return;
11860 
11861   // Early return when Terms do not contain parameters: we do not delinearize
11862   // non parametric SCEVs.
11863   if (!containsParameters(Terms))
11864     return;
11865 
11866   LLVM_DEBUG({
11867     dbgs() << "Terms:\n";
11868     for (const SCEV *T : Terms)
11869       dbgs() << *T << "\n";
11870   });
11871 
11872   // Remove duplicates.
11873   array_pod_sort(Terms.begin(), Terms.end());
11874   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11875 
11876   // Put larger terms first.
11877   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11878     return numberOfTerms(LHS) > numberOfTerms(RHS);
11879   });
11880 
11881   // Try to divide all terms by the element size. If term is not divisible by
11882   // element size, proceed with the original term.
11883   for (const SCEV *&Term : Terms) {
11884     const SCEV *Q, *R;
11885     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11886     if (!Q->isZero())
11887       Term = Q;
11888   }
11889 
11890   SmallVector<const SCEV *, 4> NewTerms;
11891 
11892   // Remove constant factors.
11893   for (const SCEV *T : Terms)
11894     if (const SCEV *NewT = removeConstantFactors(*this, T))
11895       NewTerms.push_back(NewT);
11896 
11897   LLVM_DEBUG({
11898     dbgs() << "Terms after sorting:\n";
11899     for (const SCEV *T : NewTerms)
11900       dbgs() << *T << "\n";
11901   });
11902 
11903   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11904     Sizes.clear();
11905     return;
11906   }
11907 
11908   // The last element to be pushed into Sizes is the size of an element.
11909   Sizes.push_back(ElementSize);
11910 
11911   LLVM_DEBUG({
11912     dbgs() << "Sizes:\n";
11913     for (const SCEV *S : Sizes)
11914       dbgs() << *S << "\n";
11915   });
11916 }
11917 
11918 void ScalarEvolution::computeAccessFunctions(
11919     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11920     SmallVectorImpl<const SCEV *> &Sizes) {
11921   // Early exit in case this SCEV is not an affine multivariate function.
11922   if (Sizes.empty())
11923     return;
11924 
11925   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11926     if (!AR->isAffine())
11927       return;
11928 
11929   const SCEV *Res = Expr;
11930   int Last = Sizes.size() - 1;
11931   for (int i = Last; i >= 0; i--) {
11932     const SCEV *Q, *R;
11933     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11934 
11935     LLVM_DEBUG({
11936       dbgs() << "Res: " << *Res << "\n";
11937       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11938       dbgs() << "Res divided by Sizes[i]:\n";
11939       dbgs() << "Quotient: " << *Q << "\n";
11940       dbgs() << "Remainder: " << *R << "\n";
11941     });
11942 
11943     Res = Q;
11944 
11945     // Do not record the last subscript corresponding to the size of elements in
11946     // the array.
11947     if (i == Last) {
11948 
11949       // Bail out if the remainder is too complex.
11950       if (isa<SCEVAddRecExpr>(R)) {
11951         Subscripts.clear();
11952         Sizes.clear();
11953         return;
11954       }
11955 
11956       continue;
11957     }
11958 
11959     // Record the access function for the current subscript.
11960     Subscripts.push_back(R);
11961   }
11962 
11963   // Also push in last position the remainder of the last division: it will be
11964   // the access function of the innermost dimension.
11965   Subscripts.push_back(Res);
11966 
11967   std::reverse(Subscripts.begin(), Subscripts.end());
11968 
11969   LLVM_DEBUG({
11970     dbgs() << "Subscripts:\n";
11971     for (const SCEV *S : Subscripts)
11972       dbgs() << *S << "\n";
11973   });
11974 }
11975 
11976 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11977 /// sizes of an array access. Returns the remainder of the delinearization that
11978 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11979 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11980 /// expressions in the stride and base of a SCEV corresponding to the
11981 /// computation of a GCD (greatest common divisor) of base and stride.  When
11982 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11983 ///
11984 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11985 ///
11986 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11987 ///
11988 ///    for (long i = 0; i < n; i++)
11989 ///      for (long j = 0; j < m; j++)
11990 ///        for (long k = 0; k < o; k++)
11991 ///          A[i][j][k] = 1.0;
11992 ///  }
11993 ///
11994 /// the delinearization input is the following AddRec SCEV:
11995 ///
11996 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11997 ///
11998 /// From this SCEV, we are able to say that the base offset of the access is %A
11999 /// because it appears as an offset that does not divide any of the strides in
12000 /// the loops:
12001 ///
12002 ///  CHECK: Base offset: %A
12003 ///
12004 /// and then SCEV->delinearize determines the size of some of the dimensions of
12005 /// the array as these are the multiples by which the strides are happening:
12006 ///
12007 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
12008 ///
12009 /// Note that the outermost dimension remains of UnknownSize because there are
12010 /// no strides that would help identifying the size of the last dimension: when
12011 /// the array has been statically allocated, one could compute the size of that
12012 /// dimension by dividing the overall size of the array by the size of the known
12013 /// dimensions: %m * %o * 8.
12014 ///
12015 /// Finally delinearize provides the access functions for the array reference
12016 /// that does correspond to A[i][j][k] of the above C testcase:
12017 ///
12018 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
12019 ///
12020 /// The testcases are checking the output of a function pass:
12021 /// DelinearizationPass that walks through all loads and stores of a function
12022 /// asking for the SCEV of the memory access with respect to all enclosing
12023 /// loops, calling SCEV->delinearize on that and printing the results.
12024 void ScalarEvolution::delinearize(const SCEV *Expr,
12025                                  SmallVectorImpl<const SCEV *> &Subscripts,
12026                                  SmallVectorImpl<const SCEV *> &Sizes,
12027                                  const SCEV *ElementSize) {
12028   // First step: collect parametric terms.
12029   SmallVector<const SCEV *, 4> Terms;
12030   collectParametricTerms(Expr, Terms);
12031 
12032   if (Terms.empty())
12033     return;
12034 
12035   // Second step: find subscript sizes.
12036   findArrayDimensions(Terms, Sizes, ElementSize);
12037 
12038   if (Sizes.empty())
12039     return;
12040 
12041   // Third step: compute the access functions for each subscript.
12042   computeAccessFunctions(Expr, Subscripts, Sizes);
12043 
12044   if (Subscripts.empty())
12045     return;
12046 
12047   LLVM_DEBUG({
12048     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12049     dbgs() << "ArrayDecl[UnknownSize]";
12050     for (const SCEV *S : Sizes)
12051       dbgs() << "[" << *S << "]";
12052 
12053     dbgs() << "\nArrayRef";
12054     for (const SCEV *S : Subscripts)
12055       dbgs() << "[" << *S << "]";
12056     dbgs() << "\n";
12057   });
12058 }
12059 
12060 bool ScalarEvolution::getIndexExpressionsFromGEP(
12061     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12062     SmallVectorImpl<int> &Sizes) {
12063   assert(Subscripts.empty() && Sizes.empty() &&
12064          "Expected output lists to be empty on entry to this function.");
12065   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12066   Type *Ty = GEP->getPointerOperandType();
12067   bool DroppedFirstDim = false;
12068   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12069     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12070     if (i == 1) {
12071       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12072         Ty = PtrTy->getElementType();
12073       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12074         Ty = ArrayTy->getElementType();
12075       } else {
12076         Subscripts.clear();
12077         Sizes.clear();
12078         return false;
12079       }
12080       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12081         if (Const->getValue()->isZero()) {
12082           DroppedFirstDim = true;
12083           continue;
12084         }
12085       Subscripts.push_back(Expr);
12086       continue;
12087     }
12088 
12089     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12090     if (!ArrayTy) {
12091       Subscripts.clear();
12092       Sizes.clear();
12093       return false;
12094     }
12095 
12096     Subscripts.push_back(Expr);
12097     if (!(DroppedFirstDim && i == 2))
12098       Sizes.push_back(ArrayTy->getNumElements());
12099 
12100     Ty = ArrayTy->getElementType();
12101   }
12102   return !Subscripts.empty();
12103 }
12104 
12105 //===----------------------------------------------------------------------===//
12106 //                   SCEVCallbackVH Class Implementation
12107 //===----------------------------------------------------------------------===//
12108 
12109 void ScalarEvolution::SCEVCallbackVH::deleted() {
12110   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12111   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12112     SE->ConstantEvolutionLoopExitValue.erase(PN);
12113   SE->eraseValueFromMap(getValPtr());
12114   // this now dangles!
12115 }
12116 
12117 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12118   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12119 
12120   // Forget all the expressions associated with users of the old value,
12121   // so that future queries will recompute the expressions using the new
12122   // value.
12123   Value *Old = getValPtr();
12124   SmallVector<User *, 16> Worklist(Old->users());
12125   SmallPtrSet<User *, 8> Visited;
12126   while (!Worklist.empty()) {
12127     User *U = Worklist.pop_back_val();
12128     // Deleting the Old value will cause this to dangle. Postpone
12129     // that until everything else is done.
12130     if (U == Old)
12131       continue;
12132     if (!Visited.insert(U).second)
12133       continue;
12134     if (PHINode *PN = dyn_cast<PHINode>(U))
12135       SE->ConstantEvolutionLoopExitValue.erase(PN);
12136     SE->eraseValueFromMap(U);
12137     llvm::append_range(Worklist, U->users());
12138   }
12139   // Delete the Old value.
12140   if (PHINode *PN = dyn_cast<PHINode>(Old))
12141     SE->ConstantEvolutionLoopExitValue.erase(PN);
12142   SE->eraseValueFromMap(Old);
12143   // this now dangles!
12144 }
12145 
12146 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12147   : CallbackVH(V), SE(se) {}
12148 
12149 //===----------------------------------------------------------------------===//
12150 //                   ScalarEvolution Class Implementation
12151 //===----------------------------------------------------------------------===//
12152 
12153 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12154                                  AssumptionCache &AC, DominatorTree &DT,
12155                                  LoopInfo &LI)
12156     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12157       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12158       LoopDispositions(64), BlockDispositions(64) {
12159   // To use guards for proving predicates, we need to scan every instruction in
12160   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12161   // time if the IR does not actually contain any calls to
12162   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12163   //
12164   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12165   // to _add_ guards to the module when there weren't any before, and wants
12166   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12167   // efficient in lieu of being smart in that rather obscure case.
12168 
12169   auto *GuardDecl = F.getParent()->getFunction(
12170       Intrinsic::getName(Intrinsic::experimental_guard));
12171   HasGuards = GuardDecl && !GuardDecl->use_empty();
12172 }
12173 
12174 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12175     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12176       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12177       ValueExprMap(std::move(Arg.ValueExprMap)),
12178       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12179       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12180       PendingMerges(std::move(Arg.PendingMerges)),
12181       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12182       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12183       PredicatedBackedgeTakenCounts(
12184           std::move(Arg.PredicatedBackedgeTakenCounts)),
12185       ConstantEvolutionLoopExitValue(
12186           std::move(Arg.ConstantEvolutionLoopExitValue)),
12187       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12188       LoopDispositions(std::move(Arg.LoopDispositions)),
12189       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12190       BlockDispositions(std::move(Arg.BlockDispositions)),
12191       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12192       SignedRanges(std::move(Arg.SignedRanges)),
12193       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12194       UniquePreds(std::move(Arg.UniquePreds)),
12195       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12196       LoopUsers(std::move(Arg.LoopUsers)),
12197       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12198       FirstUnknown(Arg.FirstUnknown) {
12199   Arg.FirstUnknown = nullptr;
12200 }
12201 
12202 ScalarEvolution::~ScalarEvolution() {
12203   // Iterate through all the SCEVUnknown instances and call their
12204   // destructors, so that they release their references to their values.
12205   for (SCEVUnknown *U = FirstUnknown; U;) {
12206     SCEVUnknown *Tmp = U;
12207     U = U->Next;
12208     Tmp->~SCEVUnknown();
12209   }
12210   FirstUnknown = nullptr;
12211 
12212   ExprValueMap.clear();
12213   ValueExprMap.clear();
12214   HasRecMap.clear();
12215 
12216   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12217   // that a loop had multiple computable exits.
12218   for (auto &BTCI : BackedgeTakenCounts)
12219     BTCI.second.clear();
12220   for (auto &BTCI : PredicatedBackedgeTakenCounts)
12221     BTCI.second.clear();
12222 
12223   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12224   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12225   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12226   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12227   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12228 }
12229 
12230 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12231   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12232 }
12233 
12234 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12235                           const Loop *L) {
12236   // Print all inner loops first
12237   for (Loop *I : *L)
12238     PrintLoopInfo(OS, SE, I);
12239 
12240   OS << "Loop ";
12241   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12242   OS << ": ";
12243 
12244   SmallVector<BasicBlock *, 8> ExitingBlocks;
12245   L->getExitingBlocks(ExitingBlocks);
12246   if (ExitingBlocks.size() != 1)
12247     OS << "<multiple exits> ";
12248 
12249   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12250     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12251   else
12252     OS << "Unpredictable backedge-taken count.\n";
12253 
12254   if (ExitingBlocks.size() > 1)
12255     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12256       OS << "  exit count for " << ExitingBlock->getName() << ": "
12257          << *SE->getExitCount(L, ExitingBlock) << "\n";
12258     }
12259 
12260   OS << "Loop ";
12261   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12262   OS << ": ";
12263 
12264   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12265     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12266     if (SE->isBackedgeTakenCountMaxOrZero(L))
12267       OS << ", actual taken count either this or zero.";
12268   } else {
12269     OS << "Unpredictable max backedge-taken count. ";
12270   }
12271 
12272   OS << "\n"
12273         "Loop ";
12274   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12275   OS << ": ";
12276 
12277   SCEVUnionPredicate Pred;
12278   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12279   if (!isa<SCEVCouldNotCompute>(PBT)) {
12280     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12281     OS << " Predicates:\n";
12282     Pred.print(OS, 4);
12283   } else {
12284     OS << "Unpredictable predicated backedge-taken count. ";
12285   }
12286   OS << "\n";
12287 
12288   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12289     OS << "Loop ";
12290     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12291     OS << ": ";
12292     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12293   }
12294 }
12295 
12296 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12297   switch (LD) {
12298   case ScalarEvolution::LoopVariant:
12299     return "Variant";
12300   case ScalarEvolution::LoopInvariant:
12301     return "Invariant";
12302   case ScalarEvolution::LoopComputable:
12303     return "Computable";
12304   }
12305   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12306 }
12307 
12308 void ScalarEvolution::print(raw_ostream &OS) const {
12309   // ScalarEvolution's implementation of the print method is to print
12310   // out SCEV values of all instructions that are interesting. Doing
12311   // this potentially causes it to create new SCEV objects though,
12312   // which technically conflicts with the const qualifier. This isn't
12313   // observable from outside the class though, so casting away the
12314   // const isn't dangerous.
12315   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12316 
12317   if (ClassifyExpressions) {
12318     OS << "Classifying expressions for: ";
12319     F.printAsOperand(OS, /*PrintType=*/false);
12320     OS << "\n";
12321     for (Instruction &I : instructions(F))
12322       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12323         OS << I << '\n';
12324         OS << "  -->  ";
12325         const SCEV *SV = SE.getSCEV(&I);
12326         SV->print(OS);
12327         if (!isa<SCEVCouldNotCompute>(SV)) {
12328           OS << " U: ";
12329           SE.getUnsignedRange(SV).print(OS);
12330           OS << " S: ";
12331           SE.getSignedRange(SV).print(OS);
12332         }
12333 
12334         const Loop *L = LI.getLoopFor(I.getParent());
12335 
12336         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12337         if (AtUse != SV) {
12338           OS << "  -->  ";
12339           AtUse->print(OS);
12340           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12341             OS << " U: ";
12342             SE.getUnsignedRange(AtUse).print(OS);
12343             OS << " S: ";
12344             SE.getSignedRange(AtUse).print(OS);
12345           }
12346         }
12347 
12348         if (L) {
12349           OS << "\t\t" "Exits: ";
12350           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12351           if (!SE.isLoopInvariant(ExitValue, L)) {
12352             OS << "<<Unknown>>";
12353           } else {
12354             OS << *ExitValue;
12355           }
12356 
12357           bool First = true;
12358           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12359             if (First) {
12360               OS << "\t\t" "LoopDispositions: { ";
12361               First = false;
12362             } else {
12363               OS << ", ";
12364             }
12365 
12366             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12367             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12368           }
12369 
12370           for (auto *InnerL : depth_first(L)) {
12371             if (InnerL == L)
12372               continue;
12373             if (First) {
12374               OS << "\t\t" "LoopDispositions: { ";
12375               First = false;
12376             } else {
12377               OS << ", ";
12378             }
12379 
12380             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12381             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12382           }
12383 
12384           OS << " }";
12385         }
12386 
12387         OS << "\n";
12388       }
12389   }
12390 
12391   OS << "Determining loop execution counts for: ";
12392   F.printAsOperand(OS, /*PrintType=*/false);
12393   OS << "\n";
12394   for (Loop *I : LI)
12395     PrintLoopInfo(OS, &SE, I);
12396 }
12397 
12398 ScalarEvolution::LoopDisposition
12399 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12400   auto &Values = LoopDispositions[S];
12401   for (auto &V : Values) {
12402     if (V.getPointer() == L)
12403       return V.getInt();
12404   }
12405   Values.emplace_back(L, LoopVariant);
12406   LoopDisposition D = computeLoopDisposition(S, L);
12407   auto &Values2 = LoopDispositions[S];
12408   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12409     if (V.getPointer() == L) {
12410       V.setInt(D);
12411       break;
12412     }
12413   }
12414   return D;
12415 }
12416 
12417 ScalarEvolution::LoopDisposition
12418 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12419   switch (S->getSCEVType()) {
12420   case scConstant:
12421     return LoopInvariant;
12422   case scPtrToInt:
12423   case scTruncate:
12424   case scZeroExtend:
12425   case scSignExtend:
12426     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12427   case scAddRecExpr: {
12428     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12429 
12430     // If L is the addrec's loop, it's computable.
12431     if (AR->getLoop() == L)
12432       return LoopComputable;
12433 
12434     // Add recurrences are never invariant in the function-body (null loop).
12435     if (!L)
12436       return LoopVariant;
12437 
12438     // Everything that is not defined at loop entry is variant.
12439     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12440       return LoopVariant;
12441     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12442            " dominate the contained loop's header?");
12443 
12444     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12445     if (AR->getLoop()->contains(L))
12446       return LoopInvariant;
12447 
12448     // This recurrence is variant w.r.t. L if any of its operands
12449     // are variant.
12450     for (auto *Op : AR->operands())
12451       if (!isLoopInvariant(Op, L))
12452         return LoopVariant;
12453 
12454     // Otherwise it's loop-invariant.
12455     return LoopInvariant;
12456   }
12457   case scAddExpr:
12458   case scMulExpr:
12459   case scUMaxExpr:
12460   case scSMaxExpr:
12461   case scUMinExpr:
12462   case scSMinExpr: {
12463     bool HasVarying = false;
12464     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12465       LoopDisposition D = getLoopDisposition(Op, L);
12466       if (D == LoopVariant)
12467         return LoopVariant;
12468       if (D == LoopComputable)
12469         HasVarying = true;
12470     }
12471     return HasVarying ? LoopComputable : LoopInvariant;
12472   }
12473   case scUDivExpr: {
12474     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12475     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12476     if (LD == LoopVariant)
12477       return LoopVariant;
12478     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12479     if (RD == LoopVariant)
12480       return LoopVariant;
12481     return (LD == LoopInvariant && RD == LoopInvariant) ?
12482            LoopInvariant : LoopComputable;
12483   }
12484   case scUnknown:
12485     // All non-instruction values are loop invariant.  All instructions are loop
12486     // invariant if they are not contained in the specified loop.
12487     // Instructions are never considered invariant in the function body
12488     // (null loop) because they are defined within the "loop".
12489     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12490       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12491     return LoopInvariant;
12492   case scCouldNotCompute:
12493     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12494   }
12495   llvm_unreachable("Unknown SCEV kind!");
12496 }
12497 
12498 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12499   return getLoopDisposition(S, L) == LoopInvariant;
12500 }
12501 
12502 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12503   return getLoopDisposition(S, L) == LoopComputable;
12504 }
12505 
12506 ScalarEvolution::BlockDisposition
12507 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12508   auto &Values = BlockDispositions[S];
12509   for (auto &V : Values) {
12510     if (V.getPointer() == BB)
12511       return V.getInt();
12512   }
12513   Values.emplace_back(BB, DoesNotDominateBlock);
12514   BlockDisposition D = computeBlockDisposition(S, BB);
12515   auto &Values2 = BlockDispositions[S];
12516   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12517     if (V.getPointer() == BB) {
12518       V.setInt(D);
12519       break;
12520     }
12521   }
12522   return D;
12523 }
12524 
12525 ScalarEvolution::BlockDisposition
12526 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12527   switch (S->getSCEVType()) {
12528   case scConstant:
12529     return ProperlyDominatesBlock;
12530   case scPtrToInt:
12531   case scTruncate:
12532   case scZeroExtend:
12533   case scSignExtend:
12534     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12535   case scAddRecExpr: {
12536     // This uses a "dominates" query instead of "properly dominates" query
12537     // to test for proper dominance too, because the instruction which
12538     // produces the addrec's value is a PHI, and a PHI effectively properly
12539     // dominates its entire containing block.
12540     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12541     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12542       return DoesNotDominateBlock;
12543 
12544     // Fall through into SCEVNAryExpr handling.
12545     LLVM_FALLTHROUGH;
12546   }
12547   case scAddExpr:
12548   case scMulExpr:
12549   case scUMaxExpr:
12550   case scSMaxExpr:
12551   case scUMinExpr:
12552   case scSMinExpr: {
12553     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12554     bool Proper = true;
12555     for (const SCEV *NAryOp : NAry->operands()) {
12556       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12557       if (D == DoesNotDominateBlock)
12558         return DoesNotDominateBlock;
12559       if (D == DominatesBlock)
12560         Proper = false;
12561     }
12562     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12563   }
12564   case scUDivExpr: {
12565     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12566     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12567     BlockDisposition LD = getBlockDisposition(LHS, BB);
12568     if (LD == DoesNotDominateBlock)
12569       return DoesNotDominateBlock;
12570     BlockDisposition RD = getBlockDisposition(RHS, BB);
12571     if (RD == DoesNotDominateBlock)
12572       return DoesNotDominateBlock;
12573     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12574       ProperlyDominatesBlock : DominatesBlock;
12575   }
12576   case scUnknown:
12577     if (Instruction *I =
12578           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12579       if (I->getParent() == BB)
12580         return DominatesBlock;
12581       if (DT.properlyDominates(I->getParent(), BB))
12582         return ProperlyDominatesBlock;
12583       return DoesNotDominateBlock;
12584     }
12585     return ProperlyDominatesBlock;
12586   case scCouldNotCompute:
12587     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12588   }
12589   llvm_unreachable("Unknown SCEV kind!");
12590 }
12591 
12592 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12593   return getBlockDisposition(S, BB) >= DominatesBlock;
12594 }
12595 
12596 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12597   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12598 }
12599 
12600 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12601   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12602 }
12603 
12604 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12605   auto IsS = [&](const SCEV *X) { return S == X; };
12606   auto ContainsS = [&](const SCEV *X) {
12607     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12608   };
12609   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12610 }
12611 
12612 void
12613 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12614   ValuesAtScopes.erase(S);
12615   LoopDispositions.erase(S);
12616   BlockDispositions.erase(S);
12617   UnsignedRanges.erase(S);
12618   SignedRanges.erase(S);
12619   ExprValueMap.erase(S);
12620   HasRecMap.erase(S);
12621   MinTrailingZerosCache.erase(S);
12622 
12623   for (auto I = PredicatedSCEVRewrites.begin();
12624        I != PredicatedSCEVRewrites.end();) {
12625     std::pair<const SCEV *, const Loop *> Entry = I->first;
12626     if (Entry.first == S)
12627       PredicatedSCEVRewrites.erase(I++);
12628     else
12629       ++I;
12630   }
12631 
12632   auto RemoveSCEVFromBackedgeMap =
12633       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12634         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12635           BackedgeTakenInfo &BEInfo = I->second;
12636           if (BEInfo.hasOperand(S, this)) {
12637             BEInfo.clear();
12638             Map.erase(I++);
12639           } else
12640             ++I;
12641         }
12642       };
12643 
12644   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12645   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12646 }
12647 
12648 void
12649 ScalarEvolution::getUsedLoops(const SCEV *S,
12650                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12651   struct FindUsedLoops {
12652     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12653         : LoopsUsed(LoopsUsed) {}
12654     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12655     bool follow(const SCEV *S) {
12656       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12657         LoopsUsed.insert(AR->getLoop());
12658       return true;
12659     }
12660 
12661     bool isDone() const { return false; }
12662   };
12663 
12664   FindUsedLoops F(LoopsUsed);
12665   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12666 }
12667 
12668 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12669   SmallPtrSet<const Loop *, 8> LoopsUsed;
12670   getUsedLoops(S, LoopsUsed);
12671   for (auto *L : LoopsUsed)
12672     LoopUsers[L].push_back(S);
12673 }
12674 
12675 void ScalarEvolution::verify() const {
12676   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12677   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12678 
12679   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12680 
12681   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12682   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12683     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12684 
12685     const SCEV *visitConstant(const SCEVConstant *Constant) {
12686       return SE.getConstant(Constant->getAPInt());
12687     }
12688 
12689     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12690       return SE.getUnknown(Expr->getValue());
12691     }
12692 
12693     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12694       return SE.getCouldNotCompute();
12695     }
12696   };
12697 
12698   SCEVMapper SCM(SE2);
12699 
12700   while (!LoopStack.empty()) {
12701     auto *L = LoopStack.pop_back_val();
12702     llvm::append_range(LoopStack, *L);
12703 
12704     auto *CurBECount = SCM.visit(
12705         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12706     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12707 
12708     if (CurBECount == SE2.getCouldNotCompute() ||
12709         NewBECount == SE2.getCouldNotCompute()) {
12710       // NB! This situation is legal, but is very suspicious -- whatever pass
12711       // change the loop to make a trip count go from could not compute to
12712       // computable or vice-versa *should have* invalidated SCEV.  However, we
12713       // choose not to assert here (for now) since we don't want false
12714       // positives.
12715       continue;
12716     }
12717 
12718     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12719       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12720       // not propagate undef aggressively).  This means we can (and do) fail
12721       // verification in cases where a transform makes the trip count of a loop
12722       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12723       // both cases the loop iterates "undef" times, but SCEV thinks we
12724       // increased the trip count of the loop by 1 incorrectly.
12725       continue;
12726     }
12727 
12728     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12729         SE.getTypeSizeInBits(NewBECount->getType()))
12730       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12731     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12732              SE.getTypeSizeInBits(NewBECount->getType()))
12733       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12734 
12735     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12736 
12737     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12738     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12739       dbgs() << "Trip Count for " << *L << " Changed!\n";
12740       dbgs() << "Old: " << *CurBECount << "\n";
12741       dbgs() << "New: " << *NewBECount << "\n";
12742       dbgs() << "Delta: " << *Delta << "\n";
12743       std::abort();
12744     }
12745   }
12746 
12747   // Collect all valid loops currently in LoopInfo.
12748   SmallPtrSet<Loop *, 32> ValidLoops;
12749   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12750   while (!Worklist.empty()) {
12751     Loop *L = Worklist.pop_back_val();
12752     if (ValidLoops.contains(L))
12753       continue;
12754     ValidLoops.insert(L);
12755     Worklist.append(L->begin(), L->end());
12756   }
12757   // Check for SCEV expressions referencing invalid/deleted loops.
12758   for (auto &KV : ValueExprMap) {
12759     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12760     if (!AR)
12761       continue;
12762     assert(ValidLoops.contains(AR->getLoop()) &&
12763            "AddRec references invalid loop");
12764   }
12765 }
12766 
12767 bool ScalarEvolution::invalidate(
12768     Function &F, const PreservedAnalyses &PA,
12769     FunctionAnalysisManager::Invalidator &Inv) {
12770   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12771   // of its dependencies is invalidated.
12772   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12773   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12774          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12775          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12776          Inv.invalidate<LoopAnalysis>(F, PA);
12777 }
12778 
12779 AnalysisKey ScalarEvolutionAnalysis::Key;
12780 
12781 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12782                                              FunctionAnalysisManager &AM) {
12783   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12784                          AM.getResult<AssumptionAnalysis>(F),
12785                          AM.getResult<DominatorTreeAnalysis>(F),
12786                          AM.getResult<LoopAnalysis>(F));
12787 }
12788 
12789 PreservedAnalyses
12790 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12791   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12792   return PreservedAnalyses::all();
12793 }
12794 
12795 PreservedAnalyses
12796 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12797   // For compatibility with opt's -analyze feature under legacy pass manager
12798   // which was not ported to NPM. This keeps tests using
12799   // update_analyze_test_checks.py working.
12800   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12801      << F.getName() << "':\n";
12802   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12803   return PreservedAnalyses::all();
12804 }
12805 
12806 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12807                       "Scalar Evolution Analysis", false, true)
12808 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12809 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12810 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12811 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12812 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12813                     "Scalar Evolution Analysis", false, true)
12814 
12815 char ScalarEvolutionWrapperPass::ID = 0;
12816 
12817 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12818   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12819 }
12820 
12821 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12822   SE.reset(new ScalarEvolution(
12823       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12824       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12825       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12826       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12827   return false;
12828 }
12829 
12830 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12831 
12832 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12833   SE->print(OS);
12834 }
12835 
12836 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12837   if (!VerifySCEV)
12838     return;
12839 
12840   SE->verify();
12841 }
12842 
12843 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12844   AU.setPreservesAll();
12845   AU.addRequiredTransitive<AssumptionCacheTracker>();
12846   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12847   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12848   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12849 }
12850 
12851 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12852                                                         const SCEV *RHS) {
12853   FoldingSetNodeID ID;
12854   assert(LHS->getType() == RHS->getType() &&
12855          "Type mismatch between LHS and RHS");
12856   // Unique this node based on the arguments
12857   ID.AddInteger(SCEVPredicate::P_Equal);
12858   ID.AddPointer(LHS);
12859   ID.AddPointer(RHS);
12860   void *IP = nullptr;
12861   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12862     return S;
12863   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12864       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12865   UniquePreds.InsertNode(Eq, IP);
12866   return Eq;
12867 }
12868 
12869 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12870     const SCEVAddRecExpr *AR,
12871     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12872   FoldingSetNodeID ID;
12873   // Unique this node based on the arguments
12874   ID.AddInteger(SCEVPredicate::P_Wrap);
12875   ID.AddPointer(AR);
12876   ID.AddInteger(AddedFlags);
12877   void *IP = nullptr;
12878   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12879     return S;
12880   auto *OF = new (SCEVAllocator)
12881       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12882   UniquePreds.InsertNode(OF, IP);
12883   return OF;
12884 }
12885 
12886 namespace {
12887 
12888 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12889 public:
12890 
12891   /// Rewrites \p S in the context of a loop L and the SCEV predication
12892   /// infrastructure.
12893   ///
12894   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12895   /// equivalences present in \p Pred.
12896   ///
12897   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12898   /// \p NewPreds such that the result will be an AddRecExpr.
12899   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12900                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12901                              SCEVUnionPredicate *Pred) {
12902     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12903     return Rewriter.visit(S);
12904   }
12905 
12906   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12907     if (Pred) {
12908       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12909       for (auto *Pred : ExprPreds)
12910         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12911           if (IPred->getLHS() == Expr)
12912             return IPred->getRHS();
12913     }
12914     return convertToAddRecWithPreds(Expr);
12915   }
12916 
12917   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12918     const SCEV *Operand = visit(Expr->getOperand());
12919     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12920     if (AR && AR->getLoop() == L && AR->isAffine()) {
12921       // This couldn't be folded because the operand didn't have the nuw
12922       // flag. Add the nusw flag as an assumption that we could make.
12923       const SCEV *Step = AR->getStepRecurrence(SE);
12924       Type *Ty = Expr->getType();
12925       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12926         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12927                                 SE.getSignExtendExpr(Step, Ty), L,
12928                                 AR->getNoWrapFlags());
12929     }
12930     return SE.getZeroExtendExpr(Operand, Expr->getType());
12931   }
12932 
12933   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12934     const SCEV *Operand = visit(Expr->getOperand());
12935     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12936     if (AR && AR->getLoop() == L && AR->isAffine()) {
12937       // This couldn't be folded because the operand didn't have the nsw
12938       // flag. Add the nssw flag as an assumption that we could make.
12939       const SCEV *Step = AR->getStepRecurrence(SE);
12940       Type *Ty = Expr->getType();
12941       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12942         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12943                                 SE.getSignExtendExpr(Step, Ty), L,
12944                                 AR->getNoWrapFlags());
12945     }
12946     return SE.getSignExtendExpr(Operand, Expr->getType());
12947   }
12948 
12949 private:
12950   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12951                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12952                         SCEVUnionPredicate *Pred)
12953       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12954 
12955   bool addOverflowAssumption(const SCEVPredicate *P) {
12956     if (!NewPreds) {
12957       // Check if we've already made this assumption.
12958       return Pred && Pred->implies(P);
12959     }
12960     NewPreds->insert(P);
12961     return true;
12962   }
12963 
12964   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12965                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12966     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12967     return addOverflowAssumption(A);
12968   }
12969 
12970   // If \p Expr represents a PHINode, we try to see if it can be represented
12971   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12972   // to add this predicate as a runtime overflow check, we return the AddRec.
12973   // If \p Expr does not meet these conditions (is not a PHI node, or we
12974   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12975   // return \p Expr.
12976   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12977     if (!isa<PHINode>(Expr->getValue()))
12978       return Expr;
12979     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12980     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12981     if (!PredicatedRewrite)
12982       return Expr;
12983     for (auto *P : PredicatedRewrite->second){
12984       // Wrap predicates from outer loops are not supported.
12985       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12986         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12987         if (L != AR->getLoop())
12988           return Expr;
12989       }
12990       if (!addOverflowAssumption(P))
12991         return Expr;
12992     }
12993     return PredicatedRewrite->first;
12994   }
12995 
12996   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12997   SCEVUnionPredicate *Pred;
12998   const Loop *L;
12999 };
13000 
13001 } // end anonymous namespace
13002 
13003 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13004                                                    SCEVUnionPredicate &Preds) {
13005   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13006 }
13007 
13008 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13009     const SCEV *S, const Loop *L,
13010     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13011   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13012   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13013   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13014 
13015   if (!AddRec)
13016     return nullptr;
13017 
13018   // Since the transformation was successful, we can now transfer the SCEV
13019   // predicates.
13020   for (auto *P : TransformPreds)
13021     Preds.insert(P);
13022 
13023   return AddRec;
13024 }
13025 
13026 /// SCEV predicates
13027 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13028                              SCEVPredicateKind Kind)
13029     : FastID(ID), Kind(Kind) {}
13030 
13031 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
13032                                        const SCEV *LHS, const SCEV *RHS)
13033     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
13034   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13035   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13036 }
13037 
13038 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13039   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13040 
13041   if (!Op)
13042     return false;
13043 
13044   return Op->LHS == LHS && Op->RHS == RHS;
13045 }
13046 
13047 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13048 
13049 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13050 
13051 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13052   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13053 }
13054 
13055 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13056                                      const SCEVAddRecExpr *AR,
13057                                      IncrementWrapFlags Flags)
13058     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13059 
13060 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13061 
13062 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13063   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13064 
13065   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13066 }
13067 
13068 bool SCEVWrapPredicate::isAlwaysTrue() const {
13069   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13070   IncrementWrapFlags IFlags = Flags;
13071 
13072   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13073     IFlags = clearFlags(IFlags, IncrementNSSW);
13074 
13075   return IFlags == IncrementAnyWrap;
13076 }
13077 
13078 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13079   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13080   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13081     OS << "<nusw>";
13082   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13083     OS << "<nssw>";
13084   OS << "\n";
13085 }
13086 
13087 SCEVWrapPredicate::IncrementWrapFlags
13088 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13089                                    ScalarEvolution &SE) {
13090   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13091   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13092 
13093   // We can safely transfer the NSW flag as NSSW.
13094   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13095     ImpliedFlags = IncrementNSSW;
13096 
13097   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13098     // If the increment is positive, the SCEV NUW flag will also imply the
13099     // WrapPredicate NUSW flag.
13100     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13101       if (Step->getValue()->getValue().isNonNegative())
13102         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13103   }
13104 
13105   return ImpliedFlags;
13106 }
13107 
13108 /// Union predicates don't get cached so create a dummy set ID for it.
13109 SCEVUnionPredicate::SCEVUnionPredicate()
13110     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13111 
13112 bool SCEVUnionPredicate::isAlwaysTrue() const {
13113   return all_of(Preds,
13114                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13115 }
13116 
13117 ArrayRef<const SCEVPredicate *>
13118 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13119   auto I = SCEVToPreds.find(Expr);
13120   if (I == SCEVToPreds.end())
13121     return ArrayRef<const SCEVPredicate *>();
13122   return I->second;
13123 }
13124 
13125 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13126   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13127     return all_of(Set->Preds,
13128                   [this](const SCEVPredicate *I) { return this->implies(I); });
13129 
13130   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13131   if (ScevPredsIt == SCEVToPreds.end())
13132     return false;
13133   auto &SCEVPreds = ScevPredsIt->second;
13134 
13135   return any_of(SCEVPreds,
13136                 [N](const SCEVPredicate *I) { return I->implies(N); });
13137 }
13138 
13139 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13140 
13141 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13142   for (auto Pred : Preds)
13143     Pred->print(OS, Depth);
13144 }
13145 
13146 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13147   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13148     for (auto Pred : Set->Preds)
13149       add(Pred);
13150     return;
13151   }
13152 
13153   if (implies(N))
13154     return;
13155 
13156   const SCEV *Key = N->getExpr();
13157   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13158                 " associated expression!");
13159 
13160   SCEVToPreds[Key].push_back(N);
13161   Preds.push_back(N);
13162 }
13163 
13164 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13165                                                      Loop &L)
13166     : SE(SE), L(L) {}
13167 
13168 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13169   const SCEV *Expr = SE.getSCEV(V);
13170   RewriteEntry &Entry = RewriteMap[Expr];
13171 
13172   // If we already have an entry and the version matches, return it.
13173   if (Entry.second && Generation == Entry.first)
13174     return Entry.second;
13175 
13176   // We found an entry but it's stale. Rewrite the stale entry
13177   // according to the current predicate.
13178   if (Entry.second)
13179     Expr = Entry.second;
13180 
13181   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13182   Entry = {Generation, NewSCEV};
13183 
13184   return NewSCEV;
13185 }
13186 
13187 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13188   if (!BackedgeCount) {
13189     SCEVUnionPredicate BackedgePred;
13190     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13191     addPredicate(BackedgePred);
13192   }
13193   return BackedgeCount;
13194 }
13195 
13196 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13197   if (Preds.implies(&Pred))
13198     return;
13199   Preds.add(&Pred);
13200   updateGeneration();
13201 }
13202 
13203 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13204   return Preds;
13205 }
13206 
13207 void PredicatedScalarEvolution::updateGeneration() {
13208   // If the generation number wrapped recompute everything.
13209   if (++Generation == 0) {
13210     for (auto &II : RewriteMap) {
13211       const SCEV *Rewritten = II.second.second;
13212       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13213     }
13214   }
13215 }
13216 
13217 void PredicatedScalarEvolution::setNoOverflow(
13218     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13219   const SCEV *Expr = getSCEV(V);
13220   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13221 
13222   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13223 
13224   // Clear the statically implied flags.
13225   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13226   addPredicate(*SE.getWrapPredicate(AR, Flags));
13227 
13228   auto II = FlagsMap.insert({V, Flags});
13229   if (!II.second)
13230     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13231 }
13232 
13233 bool PredicatedScalarEvolution::hasNoOverflow(
13234     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13235   const SCEV *Expr = getSCEV(V);
13236   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13237 
13238   Flags = SCEVWrapPredicate::clearFlags(
13239       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13240 
13241   auto II = FlagsMap.find(V);
13242 
13243   if (II != FlagsMap.end())
13244     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13245 
13246   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13247 }
13248 
13249 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13250   const SCEV *Expr = this->getSCEV(V);
13251   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13252   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13253 
13254   if (!New)
13255     return nullptr;
13256 
13257   for (auto *P : NewPreds)
13258     Preds.add(P);
13259 
13260   updateGeneration();
13261   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13262   return New;
13263 }
13264 
13265 PredicatedScalarEvolution::PredicatedScalarEvolution(
13266     const PredicatedScalarEvolution &Init)
13267     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13268       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13269   for (auto I : Init.FlagsMap)
13270     FlagsMap.insert(I);
13271 }
13272 
13273 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13274   // For each block.
13275   for (auto *BB : L.getBlocks())
13276     for (auto &I : *BB) {
13277       if (!SE.isSCEVable(I.getType()))
13278         continue;
13279 
13280       auto *Expr = SE.getSCEV(&I);
13281       auto II = RewriteMap.find(Expr);
13282 
13283       if (II == RewriteMap.end())
13284         continue;
13285 
13286       // Don't print things that are not interesting.
13287       if (II->second.second == Expr)
13288         continue;
13289 
13290       OS.indent(Depth) << "[PSE]" << I << ":\n";
13291       OS.indent(Depth + 2) << *Expr << "\n";
13292       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13293     }
13294 }
13295 
13296 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13297 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13298 // for URem with constant power-of-2 second operands.
13299 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13300 // 4, A / B becomes X / 8).
13301 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13302                                 const SCEV *&RHS) {
13303   // Try to match 'zext (trunc A to iB) to iY', which is used
13304   // for URem with constant power-of-2 second operands. Make sure the size of
13305   // the operand A matches the size of the whole expressions.
13306   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13307     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13308       LHS = Trunc->getOperand();
13309       // Bail out if the type of the LHS is larger than the type of the
13310       // expression for now.
13311       if (getTypeSizeInBits(LHS->getType()) >
13312           getTypeSizeInBits(Expr->getType()))
13313         return false;
13314       if (LHS->getType() != Expr->getType())
13315         LHS = getZeroExtendExpr(LHS, Expr->getType());
13316       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13317                         << getTypeSizeInBits(Trunc->getType()));
13318       return true;
13319     }
13320   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13321   if (Add == nullptr || Add->getNumOperands() != 2)
13322     return false;
13323 
13324   const SCEV *A = Add->getOperand(1);
13325   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13326 
13327   if (Mul == nullptr)
13328     return false;
13329 
13330   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13331     // (SomeExpr + (-(SomeExpr / B) * B)).
13332     if (Expr == getURemExpr(A, B)) {
13333       LHS = A;
13334       RHS = B;
13335       return true;
13336     }
13337     return false;
13338   };
13339 
13340   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13341   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13342     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13343            MatchURemWithDivisor(Mul->getOperand(2));
13344 
13345   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13346   if (Mul->getNumOperands() == 2)
13347     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13348            MatchURemWithDivisor(Mul->getOperand(0)) ||
13349            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13350            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13351   return false;
13352 }
13353 
13354 const SCEV *
13355 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13356   SmallVector<BasicBlock*, 16> ExitingBlocks;
13357   L->getExitingBlocks(ExitingBlocks);
13358 
13359   // Form an expression for the maximum exit count possible for this loop. We
13360   // merge the max and exact information to approximate a version of
13361   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13362   SmallVector<const SCEV*, 4> ExitCounts;
13363   for (BasicBlock *ExitingBB : ExitingBlocks) {
13364     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13365     if (isa<SCEVCouldNotCompute>(ExitCount))
13366       ExitCount = getExitCount(L, ExitingBB,
13367                                   ScalarEvolution::ConstantMaximum);
13368     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13369       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13370              "We should only have known counts for exiting blocks that "
13371              "dominate latch!");
13372       ExitCounts.push_back(ExitCount);
13373     }
13374   }
13375   if (ExitCounts.empty())
13376     return getCouldNotCompute();
13377   return getUMinFromMismatchedTypes(ExitCounts);
13378 }
13379 
13380 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13381 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13382 /// we cannot guarantee that the replacement is loop invariant in the loop of
13383 /// the AddRec.
13384 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13385   ValueToSCEVMapTy &Map;
13386 
13387 public:
13388   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13389       : SCEVRewriteVisitor(SE), Map(M) {}
13390 
13391   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13392 
13393   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13394     auto I = Map.find(Expr->getValue());
13395     if (I == Map.end())
13396       return Expr;
13397     return I->second;
13398   }
13399 };
13400 
13401 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13402   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13403                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13404     // If we have LHS == 0, check if LHS is computing a property of some unknown
13405     // SCEV %v which we can rewrite %v to express explicitly.
13406     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13407     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13408         RHSC->getValue()->isNullValue()) {
13409       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13410       // explicitly express that.
13411       const SCEV *URemLHS = nullptr;
13412       const SCEV *URemRHS = nullptr;
13413       if (matchURem(LHS, URemLHS, URemRHS)) {
13414         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13415           Value *V = LHSUnknown->getValue();
13416           auto Multiple =
13417               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13418                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13419           RewriteMap[V] = Multiple;
13420           return;
13421         }
13422       }
13423     }
13424 
13425     if (!isa<SCEVUnknown>(LHS)) {
13426       std::swap(LHS, RHS);
13427       Predicate = CmpInst::getSwappedPredicate(Predicate);
13428     }
13429 
13430     // For now, limit to conditions that provide information about unknown
13431     // expressions.
13432     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13433     if (!LHSUnknown)
13434       return;
13435 
13436     // TODO: use information from more predicates.
13437     switch (Predicate) {
13438     case CmpInst::ICMP_ULT: {
13439       if (!containsAddRecurrence(RHS)) {
13440         const SCEV *Base = LHS;
13441         auto I = RewriteMap.find(LHSUnknown->getValue());
13442         if (I != RewriteMap.end())
13443           Base = I->second;
13444 
13445         RewriteMap[LHSUnknown->getValue()] =
13446             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13447       }
13448       break;
13449     }
13450     case CmpInst::ICMP_ULE: {
13451       if (!containsAddRecurrence(RHS)) {
13452         const SCEV *Base = LHS;
13453         auto I = RewriteMap.find(LHSUnknown->getValue());
13454         if (I != RewriteMap.end())
13455           Base = I->second;
13456         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13457       }
13458       break;
13459     }
13460     case CmpInst::ICMP_EQ:
13461       if (isa<SCEVConstant>(RHS))
13462         RewriteMap[LHSUnknown->getValue()] = RHS;
13463       break;
13464     case CmpInst::ICMP_NE:
13465       if (isa<SCEVConstant>(RHS) &&
13466           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13467         RewriteMap[LHSUnknown->getValue()] =
13468             getUMaxExpr(LHS, getOne(RHS->getType()));
13469       break;
13470     default:
13471       break;
13472     }
13473   };
13474   // Starting at the loop predecessor, climb up the predecessor chain, as long
13475   // as there are predecessors that can be found that have unique successors
13476   // leading to the original header.
13477   // TODO: share this logic with isLoopEntryGuardedByCond.
13478   ValueToSCEVMapTy RewriteMap;
13479   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13480            L->getLoopPredecessor(), L->getHeader());
13481        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13482 
13483     const BranchInst *LoopEntryPredicate =
13484         dyn_cast<BranchInst>(Pair.first->getTerminator());
13485     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13486       continue;
13487 
13488     // TODO: use information from more complex conditions, e.g. AND expressions.
13489     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13490     if (!Cmp)
13491       continue;
13492 
13493     auto Predicate = Cmp->getPredicate();
13494     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13495       Predicate = CmpInst::getInversePredicate(Predicate);
13496     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13497                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13498   }
13499 
13500   // Also collect information from assumptions dominating the loop.
13501   for (auto &AssumeVH : AC.assumptions()) {
13502     if (!AssumeVH)
13503       continue;
13504     auto *AssumeI = cast<CallInst>(AssumeVH);
13505     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13506     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13507       continue;
13508     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13509                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13510   }
13511 
13512   if (RewriteMap.empty())
13513     return Expr;
13514   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13515   return Rewriter.visit(Expr);
13516 }
13517