LLVM  7.0.0svn
ScalarEvolution.cpp
Go to the documentation of this file.
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression. These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 // Chains of recurrences -- a method to expedite the evaluation
43 // of closed-form functions
44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 // On computational properties of chains of recurrences
47 // Eugene V. Zima
48 //
49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 // Robert A. van Engelen
51 //
52 // Efficient Symbolic Analysis for Optimizing Compilers
53 // Robert A. van Engelen
54 //
55 // Using the chains of recurrences algebra for data dependence testing and
56 // induction variable substitution
57 // MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
82 #include "llvm/Analysis/LoopInfo.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.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/Pass.h"
115 #include "llvm/Support/Casting.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
120 #include "llvm/Support/KnownBits.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <climits>
126 #include <cstddef>
127 #include <cstdint>
128 #include <cstdlib>
129 #include <map>
130 #include <memory>
131 #include <tuple>
132 #include <utility>
133 #include <vector>
134 
135 using namespace llvm;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumArrayLenItCounts,
140  "Number of trip counts computed with array length");
141 STATISTIC(NumTripCountsComputed,
142  "Number of loops with predictable loop counts");
143 STATISTIC(NumTripCountsNotComputed,
144  "Number of loops without predictable loop counts");
145 STATISTIC(NumBruteForceTripCountsComputed,
146  "Number of loops with trip counts computed by force");
147 
148 static cl::opt<unsigned>
149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150  cl::desc("Maximum number of iterations SCEV will "
151  "symbolically execute a constant "
152  "derived loop"),
153  cl::init(100));
154 
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157  "verify-scev", cl::Hidden,
158  cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool>
160  VerifySCEVMap("verify-scev-maps", cl::Hidden,
161  cl::desc("Verify no dangling value in ScalarEvolution's "
162  "ExprValueMap (slow)"));
163 
165  "scev-mulops-inline-threshold", cl::Hidden,
166  cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167  cl::init(32));
168 
170  "scev-addops-inline-threshold", cl::Hidden,
171  cl::desc("Threshold for inlining addition operands into a SCEV"),
172  cl::init(500));
173 
175  "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176  cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177  cl::init(32));
178 
180  "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181  cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182  cl::init(2));
183 
185  "scalar-evolution-max-value-compare-depth", cl::Hidden,
186  cl::desc("Maximum depth of recursive value complexity comparisons"),
187  cl::init(2));
188 
189 static cl::opt<unsigned>
190  MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191  cl::desc("Maximum depth of recursive arithmetics"),
192  cl::init(32));
193 
195  "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196  cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197 
198 static cl::opt<unsigned>
199  MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200  cl::desc("Maximum depth of recursive SExt/ZExt"),
201  cl::init(8));
202 
203 static cl::opt<unsigned>
204  MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205  cl::desc("Max coefficients in AddRec during evolving"),
206  cl::init(16));
207 
208 //===----------------------------------------------------------------------===//
209 // SCEV class definitions
210 //===----------------------------------------------------------------------===//
211 
212 //===----------------------------------------------------------------------===//
213 // Implementation of the SCEV class.
214 //
215 
216 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218  print(dbgs());
219  dbgs() << '\n';
220 }
221 #endif
222 
223 void SCEV::print(raw_ostream &OS) const {
224  switch (static_cast<SCEVTypes>(getSCEVType())) {
225  case scConstant:
226  cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
227  return;
228  case scTruncate: {
229  const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
230  const SCEV *Op = Trunc->getOperand();
231  OS << "(trunc " << *Op->getType() << " " << *Op << " to "
232  << *Trunc->getType() << ")";
233  return;
234  }
235  case scZeroExtend: {
236  const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
237  const SCEV *Op = ZExt->getOperand();
238  OS << "(zext " << *Op->getType() << " " << *Op << " to "
239  << *ZExt->getType() << ")";
240  return;
241  }
242  case scSignExtend: {
243  const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
244  const SCEV *Op = SExt->getOperand();
245  OS << "(sext " << *Op->getType() << " " << *Op << " to "
246  << *SExt->getType() << ")";
247  return;
248  }
249  case scAddRecExpr: {
250  const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
251  OS << "{" << *AR->getOperand(0);
252  for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
253  OS << ",+," << *AR->getOperand(i);
254  OS << "}<";
255  if (AR->hasNoUnsignedWrap())
256  OS << "nuw><";
257  if (AR->hasNoSignedWrap())
258  OS << "nsw><";
259  if (AR->hasNoSelfWrap() &&
261  OS << "nw><";
262  AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
263  OS << ">";
264  return;
265  }
266  case scAddExpr:
267  case scMulExpr:
268  case scUMaxExpr:
269  case scSMaxExpr: {
270  const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
271  const char *OpStr = nullptr;
272  switch (NAry->getSCEVType()) {
273  case scAddExpr: OpStr = " + "; break;
274  case scMulExpr: OpStr = " * "; break;
275  case scUMaxExpr: OpStr = " umax "; break;
276  case scSMaxExpr: OpStr = " smax "; break;
277  }
278  OS << "(";
279  for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
280  I != E; ++I) {
281  OS << **I;
282  if (std::next(I) != E)
283  OS << OpStr;
284  }
285  OS << ")";
286  switch (NAry->getSCEVType()) {
287  case scAddExpr:
288  case scMulExpr:
289  if (NAry->hasNoUnsignedWrap())
290  OS << "<nuw>";
291  if (NAry->hasNoSignedWrap())
292  OS << "<nsw>";
293  }
294  return;
295  }
296  case scUDivExpr: {
297  const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
298  OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
299  return;
300  }
301  case scUnknown: {
302  const SCEVUnknown *U = cast<SCEVUnknown>(this);
303  Type *AllocTy;
304  if (U->isSizeOf(AllocTy)) {
305  OS << "sizeof(" << *AllocTy << ")";
306  return;
307  }
308  if (U->isAlignOf(AllocTy)) {
309  OS << "alignof(" << *AllocTy << ")";
310  return;
311  }
312 
313  Type *CTy;
314  Constant *FieldNo;
315  if (U->isOffsetOf(CTy, FieldNo)) {
316  OS << "offsetof(" << *CTy << ", ";
317  FieldNo->printAsOperand(OS, false);
318  OS << ")";
319  return;
320  }
321 
322  // Otherwise just print it normally.
323  U->getValue()->printAsOperand(OS, false);
324  return;
325  }
326  case scCouldNotCompute:
327  OS << "***COULDNOTCOMPUTE***";
328  return;
329  }
330  llvm_unreachable("Unknown SCEV kind!");
331 }
332 
333 Type *SCEV::getType() const {
334  switch (static_cast<SCEVTypes>(getSCEVType())) {
335  case scConstant:
336  return cast<SCEVConstant>(this)->getType();
337  case scTruncate:
338  case scZeroExtend:
339  case scSignExtend:
340  return cast<SCEVCastExpr>(this)->getType();
341  case scAddRecExpr:
342  case scMulExpr:
343  case scUMaxExpr:
344  case scSMaxExpr:
345  return cast<SCEVNAryExpr>(this)->getType();
346  case scAddExpr:
347  return cast<SCEVAddExpr>(this)->getType();
348  case scUDivExpr:
349  return cast<SCEVUDivExpr>(this)->getType();
350  case scUnknown:
351  return cast<SCEVUnknown>(this)->getType();
352  case scCouldNotCompute:
353  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
354  }
355  llvm_unreachable("Unknown SCEV kind!");
356 }
357 
358 bool SCEV::isZero() const {
359  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
360  return SC->getValue()->isZero();
361  return false;
362 }
363 
364 bool SCEV::isOne() const {
365  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
366  return SC->getValue()->isOne();
367  return false;
368 }
369 
370 bool SCEV::isAllOnesValue() const {
371  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
372  return SC->getValue()->isMinusOne();
373  return false;
374 }
375 
377  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
378  if (!Mul) return false;
379 
380  // If there is a constant factor, it will be first.
381  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
382  if (!SC) return false;
383 
384  // Return true if the value is negative, this matches things like (-42 * V).
385  return SC->getAPInt().isNegative();
386 }
387 
390 
392  return S->getSCEVType() == scCouldNotCompute;
393 }
394 
398  ID.AddPointer(V);
399  void *IP = nullptr;
400  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
401  SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
402  UniqueSCEVs.InsertNode(S, IP);
403  return S;
404 }
405 
407  return getConstant(ConstantInt::get(getContext(), Val));
408 }
409 
410 const SCEV *
411 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
412  IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
413  return getConstant(ConstantInt::get(ITy, V, isSigned));
414 }
415 
417  unsigned SCEVTy, const SCEV *op, Type *ty)
418  : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
419 
420 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
421  const SCEV *op, Type *ty)
422  : SCEVCastExpr(ID, scTruncate, op, ty) {
423  assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
424  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
425  "Cannot truncate non-integer value!");
426 }
427 
428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429  const SCEV *op, Type *ty)
430  : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431  assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
432  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
433  "Cannot zero extend non-integer value!");
434 }
435 
436 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
437  const SCEV *op, Type *ty)
438  : SCEVCastExpr(ID, scSignExtend, op, ty) {
439  assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
440  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
441  "Cannot sign extend non-integer value!");
442 }
443 
444 void SCEVUnknown::deleted() {
445  // Clear this SCEVUnknown from various maps.
446  SE->forgetMemoizedResults(this);
447 
448  // Remove this SCEVUnknown from the uniquing map.
449  SE->UniqueSCEVs.RemoveNode(this);
450 
451  // Release the value.
452  setValPtr(nullptr);
453 }
454 
455 void SCEVUnknown::allUsesReplacedWith(Value *New) {
456  // Remove this SCEVUnknown from the uniquing map.
457  SE->UniqueSCEVs.RemoveNode(this);
458 
459  // Update this SCEVUnknown to point to the new value. This is needed
460  // because there may still be outstanding SCEVs which still point to
461  // this SCEVUnknown.
462  setValPtr(New);
463 }
464 
465 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
466  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
467  if (VCE->getOpcode() == Instruction::PtrToInt)
468  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
469  if (CE->getOpcode() == Instruction::GetElementPtr &&
470  CE->getOperand(0)->isNullValue() &&
471  CE->getNumOperands() == 2)
472  if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
473  if (CI->isOne()) {
474  AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
475  ->getElementType();
476  return true;
477  }
478 
479  return false;
480 }
481 
482 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
483  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
484  if (VCE->getOpcode() == Instruction::PtrToInt)
485  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
486  if (CE->getOpcode() == Instruction::GetElementPtr &&
487  CE->getOperand(0)->isNullValue()) {
488  Type *Ty =
489  cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
490  if (StructType *STy = dyn_cast<StructType>(Ty))
491  if (!STy->isPacked() &&
492  CE->getNumOperands() == 3 &&
493  CE->getOperand(1)->isNullValue()) {
494  if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
495  if (CI->isOne() &&
496  STy->getNumElements() == 2 &&
497  STy->getElementType(0)->isIntegerTy(1)) {
498  AllocTy = STy->getElementType(1);
499  return true;
500  }
501  }
502  }
503 
504  return false;
505 }
506 
507 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
508  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
509  if (VCE->getOpcode() == Instruction::PtrToInt)
510  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
511  if (CE->getOpcode() == Instruction::GetElementPtr &&
512  CE->getNumOperands() == 3 &&
513  CE->getOperand(0)->isNullValue() &&
514  CE->getOperand(1)->isNullValue()) {
515  Type *Ty =
516  cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
517  // Ignore vector types here so that ScalarEvolutionExpander doesn't
518  // emit getelementptrs that index into vectors.
519  if (Ty->isStructTy() || Ty->isArrayTy()) {
520  CTy = Ty;
521  FieldNo = CE->getOperand(2);
522  return true;
523  }
524  }
525 
526  return false;
527 }
528 
529 //===----------------------------------------------------------------------===//
530 // SCEV Utilities
531 //===----------------------------------------------------------------------===//
532 
533 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
534 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
535 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
536 /// have been previously deemed to be "equally complex" by this routine. It is
537 /// intended to avoid exponential time complexity in cases like:
538 ///
539 /// %a = f(%x, %y)
540 /// %b = f(%a, %a)
541 /// %c = f(%b, %b)
542 ///
543 /// %d = f(%x, %y)
544 /// %e = f(%d, %d)
545 /// %f = f(%e, %e)
546 ///
547 /// CompareValueComplexity(%f, %c)
548 ///
549 /// Since we do not continue running this routine on expression trees once we
550 /// have seen unequal values, there is no need to track them in the cache.
551 static int
553  const LoopInfo *const LI, Value *LV, Value *RV,
554  unsigned Depth) {
555  if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
556  return 0;
557 
558  // Order pointer values after integer values. This helps SCEVExpander form
559  // GEPs.
560  bool LIsPointer = LV->getType()->isPointerTy(),
561  RIsPointer = RV->getType()->isPointerTy();
562  if (LIsPointer != RIsPointer)
563  return (int)LIsPointer - (int)RIsPointer;
564 
565  // Compare getValueID values.
566  unsigned LID = LV->getValueID(), RID = RV->getValueID();
567  if (LID != RID)
568  return (int)LID - (int)RID;
569 
570  // Sort arguments by their position.
571  if (const auto *LA = dyn_cast<Argument>(LV)) {
572  const auto *RA = cast<Argument>(RV);
573  unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
574  return (int)LArgNo - (int)RArgNo;
575  }
576 
577  if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
578  const auto *RGV = cast<GlobalValue>(RV);
579 
580  const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
581  auto LT = GV->getLinkage();
582  return !(GlobalValue::isPrivateLinkage(LT) ||
584  };
585 
586  // Use the names to distinguish the two values, but only if the
587  // names are semantically important.
588  if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
589  return LGV->getName().compare(RGV->getName());
590  }
591 
592  // For instructions, compare their loop depth, and their operand count. This
593  // is pretty loose.
594  if (const auto *LInst = dyn_cast<Instruction>(LV)) {
595  const auto *RInst = cast<Instruction>(RV);
596 
597  // Compare loop depths.
598  const BasicBlock *LParent = LInst->getParent(),
599  *RParent = RInst->getParent();
600  if (LParent != RParent) {
601  unsigned LDepth = LI->getLoopDepth(LParent),
602  RDepth = LI->getLoopDepth(RParent);
603  if (LDepth != RDepth)
604  return (int)LDepth - (int)RDepth;
605  }
606 
607  // Compare the number of operands.
608  unsigned LNumOps = LInst->getNumOperands(),
609  RNumOps = RInst->getNumOperands();
610  if (LNumOps != RNumOps)
611  return (int)LNumOps - (int)RNumOps;
612 
613  for (unsigned Idx : seq(0u, LNumOps)) {
614  int Result =
615  CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
616  RInst->getOperand(Idx), Depth + 1);
617  if (Result != 0)
618  return Result;
619  }
620  }
621 
622  EqCacheValue.unionSets(LV, RV);
623  return 0;
624 }
625 
626 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
627 // than RHS, respectively. A three-way result allows recursive comparisons to be
628 // more efficient.
631  EquivalenceClasses<const Value *> &EqCacheValue,
632  const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
633  DominatorTree &DT, unsigned Depth = 0) {
634  // Fast-path: SCEVs are uniqued so we can do a quick equality check.
635  if (LHS == RHS)
636  return 0;
637 
638  // Primarily, sort the SCEVs by their getSCEVType().
639  unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
640  if (LType != RType)
641  return (int)LType - (int)RType;
642 
643  if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
644  return 0;
645  // Aside from the getSCEVType() ordering, the particular ordering
646  // isn't very important except that it's beneficial to be consistent,
647  // so that (a + b) and (b + a) don't end up as different expressions.
648  switch (static_cast<SCEVTypes>(LType)) {
649  case scUnknown: {
650  const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
651  const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
652 
653  int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
654  RU->getValue(), Depth + 1);
655  if (X == 0)
656  EqCacheSCEV.unionSets(LHS, RHS);
657  return X;
658  }
659 
660  case scConstant: {
661  const SCEVConstant *LC = cast<SCEVConstant>(LHS);
662  const SCEVConstant *RC = cast<SCEVConstant>(RHS);
663 
664  // Compare constant values.
665  const APInt &LA = LC->getAPInt();
666  const APInt &RA = RC->getAPInt();
667  unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
668  if (LBitWidth != RBitWidth)
669  return (int)LBitWidth - (int)RBitWidth;
670  return LA.ult(RA) ? -1 : 1;
671  }
672 
673  case scAddRecExpr: {
674  const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
675  const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
676 
677  // There is always a dominance between two recs that are used by one SCEV,
678  // so we can safely sort recs by loop header dominance. We require such
679  // order in getAddExpr.
680  const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
681  if (LLoop != RLoop) {
682  const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
683  assert(LHead != RHead && "Two loops share the same header?");
684  if (DT.dominates(LHead, RHead))
685  return 1;
686  else
687  assert(DT.dominates(RHead, LHead) &&
688  "No dominance between recurrences used by one SCEV?");
689  return -1;
690  }
691 
692  // Addrec complexity grows with operand count.
693  unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
694  if (LNumOps != RNumOps)
695  return (int)LNumOps - (int)RNumOps;
696 
697  // Compare NoWrap flags.
698  if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
699  return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
700 
701  // Lexicographically compare.
702  for (unsigned i = 0; i != LNumOps; ++i) {
703  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
704  LA->getOperand(i), RA->getOperand(i), DT,
705  Depth + 1);
706  if (X != 0)
707  return X;
708  }
709  EqCacheSCEV.unionSets(LHS, RHS);
710  return 0;
711  }
712 
713  case scAddExpr:
714  case scMulExpr:
715  case scSMaxExpr:
716  case scUMaxExpr: {
717  const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
718  const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
719 
720  // Lexicographically compare n-ary expressions.
721  unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
722  if (LNumOps != RNumOps)
723  return (int)LNumOps - (int)RNumOps;
724 
725  // Compare NoWrap flags.
726  if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
727  return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
728 
729  for (unsigned i = 0; i != LNumOps; ++i) {
730  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
731  LC->getOperand(i), RC->getOperand(i), DT,
732  Depth + 1);
733  if (X != 0)
734  return X;
735  }
736  EqCacheSCEV.unionSets(LHS, RHS);
737  return 0;
738  }
739 
740  case scUDivExpr: {
741  const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
742  const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
743 
744  // Lexicographically compare udiv expressions.
745  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
746  RC->getLHS(), DT, Depth + 1);
747  if (X != 0)
748  return X;
749  X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
750  RC->getRHS(), DT, Depth + 1);
751  if (X == 0)
752  EqCacheSCEV.unionSets(LHS, RHS);
753  return X;
754  }
755 
756  case scTruncate:
757  case scZeroExtend:
758  case scSignExtend: {
759  const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
760  const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
761 
762  // Compare cast expressions by operand.
763  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
764  LC->getOperand(), RC->getOperand(), DT,
765  Depth + 1);
766  if (X == 0)
767  EqCacheSCEV.unionSets(LHS, RHS);
768  return X;
769  }
770 
771  case scCouldNotCompute:
772  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
773  }
774  llvm_unreachable("Unknown SCEV kind!");
775 }
776 
777 /// Given a list of SCEV objects, order them by their complexity, and group
778 /// objects of the same complexity together by value. When this routine is
779 /// finished, we know that any duplicates in the vector are consecutive and that
780 /// complexity is monotonically increasing.
781 ///
782 /// Note that we go take special precautions to ensure that we get deterministic
783 /// results from this routine. In other words, we don't want the results of
784 /// this to depend on where the addresses of various SCEV objects happened to
785 /// land in memory.
787  LoopInfo *LI, DominatorTree &DT) {
788  if (Ops.size() < 2) return; // Noop
789 
792  if (Ops.size() == 2) {
793  // This is the common case, which also happens to be trivially simple.
794  // Special case it.
795  const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
796  if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
797  std::swap(LHS, RHS);
798  return;
799  }
800 
801  // Do the rough sort by complexity.
802  std::stable_sort(Ops.begin(), Ops.end(),
803  [&](const SCEV *LHS, const SCEV *RHS) {
804  return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
805  LHS, RHS, DT) < 0;
806  });
807 
808  // Now that we are sorted by complexity, group elements of the same
809  // complexity. Note that this is, at worst, N^2, but the vector is likely to
810  // be extremely short in practice. Note that we take this approach because we
811  // do not want to depend on the addresses of the objects we are grouping.
812  for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
813  const SCEV *S = Ops[i];
814  unsigned Complexity = S->getSCEVType();
815 
816  // If there are any objects of the same complexity and same value as this
817  // one, group them.
818  for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
819  if (Ops[j] == S) { // Found a duplicate.
820  // Move it to immediately after i'th element.
821  std::swap(Ops[i+1], Ops[j]);
822  ++i; // no need to rescan it.
823  if (i == e-2) return; // Done!
824  }
825  }
826  }
827 }
828 
829 // Returns the size of the SCEV S.
830 static inline int sizeOfSCEV(const SCEV *S) {
831  struct FindSCEVSize {
832  int Size = 0;
833 
834  FindSCEVSize() = default;
835 
836  bool follow(const SCEV *S) {
837  ++Size;
838  // Keep looking at all operands of S.
839  return true;
840  }
841 
842  bool isDone() const {
843  return false;
844  }
845  };
846 
847  FindSCEVSize F;
849  ST.visitAll(S);
850  return F.Size;
851 }
852 
853 namespace {
854 
855 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
856 public:
857  // Computes the Quotient and Remainder of the division of Numerator by
858  // Denominator.
859  static void divide(ScalarEvolution &SE, const SCEV *Numerator,
860  const SCEV *Denominator, const SCEV **Quotient,
861  const SCEV **Remainder) {
862  assert(Numerator && Denominator && "Uninitialized SCEV");
863 
864  SCEVDivision D(SE, Numerator, Denominator);
865 
866  // Check for the trivial case here to avoid having to check for it in the
867  // rest of the code.
868  if (Numerator == Denominator) {
869  *Quotient = D.One;
870  *Remainder = D.Zero;
871  return;
872  }
873 
874  if (Numerator->isZero()) {
875  *Quotient = D.Zero;
876  *Remainder = D.Zero;
877  return;
878  }
879 
880  // A simple case when N/1. The quotient is N.
881  if (Denominator->isOne()) {
882  *Quotient = Numerator;
883  *Remainder = D.Zero;
884  return;
885  }
886 
887  // Split the Denominator when it is a product.
888  if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
889  const SCEV *Q, *R;
890  *Quotient = Numerator;
891  for (const SCEV *Op : T->operands()) {
892  divide(SE, *Quotient, Op, &Q, &R);
893  *Quotient = Q;
894 
895  // Bail out when the Numerator is not divisible by one of the terms of
896  // the Denominator.
897  if (!R->isZero()) {
898  *Quotient = D.Zero;
899  *Remainder = Numerator;
900  return;
901  }
902  }
903  *Remainder = D.Zero;
904  return;
905  }
906 
907  D.visit(Numerator);
908  *Quotient = D.Quotient;
909  *Remainder = D.Remainder;
910  }
911 
912  // Except in the trivial case described above, we do not know how to divide
913  // Expr by Denominator for the following functions with empty implementation.
914  void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
915  void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
916  void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
917  void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
918  void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
919  void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
920  void visitUnknown(const SCEVUnknown *Numerator) {}
921  void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
922 
923  void visitConstant(const SCEVConstant *Numerator) {
924  if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
925  APInt NumeratorVal = Numerator->getAPInt();
926  APInt DenominatorVal = D->getAPInt();
927  uint32_t NumeratorBW = NumeratorVal.getBitWidth();
928  uint32_t DenominatorBW = DenominatorVal.getBitWidth();
929 
930  if (NumeratorBW > DenominatorBW)
931  DenominatorVal = DenominatorVal.sext(NumeratorBW);
932  else if (NumeratorBW < DenominatorBW)
933  NumeratorVal = NumeratorVal.sext(DenominatorBW);
934 
935  APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
936  APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
937  APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
938  Quotient = SE.getConstant(QuotientVal);
939  Remainder = SE.getConstant(RemainderVal);
940  return;
941  }
942  }
943 
944  void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
945  const SCEV *StartQ, *StartR, *StepQ, *StepR;
946  if (!Numerator->isAffine())
947  return cannotDivide(Numerator);
948  divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
949  divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
950  // Bail out if the types do not match.
951  Type *Ty = Denominator->getType();
952  if (Ty != StartQ->getType() || Ty != StartR->getType() ||
953  Ty != StepQ->getType() || Ty != StepR->getType())
954  return cannotDivide(Numerator);
955  Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
956  Numerator->getNoWrapFlags());
957  Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
958  Numerator->getNoWrapFlags());
959  }
960 
961  void visitAddExpr(const SCEVAddExpr *Numerator) {
963  Type *Ty = Denominator->getType();
964 
965  for (const SCEV *Op : Numerator->operands()) {
966  const SCEV *Q, *R;
967  divide(SE, Op, Denominator, &Q, &R);
968 
969  // Bail out if types do not match.
970  if (Ty != Q->getType() || Ty != R->getType())
971  return cannotDivide(Numerator);
972 
973  Qs.push_back(Q);
974  Rs.push_back(R);
975  }
976 
977  if (Qs.size() == 1) {
978  Quotient = Qs[0];
979  Remainder = Rs[0];
980  return;
981  }
982 
983  Quotient = SE.getAddExpr(Qs);
984  Remainder = SE.getAddExpr(Rs);
985  }
986 
987  void visitMulExpr(const SCEVMulExpr *Numerator) {
989  Type *Ty = Denominator->getType();
990 
991  bool FoundDenominatorTerm = false;
992  for (const SCEV *Op : Numerator->operands()) {
993  // Bail out if types do not match.
994  if (Ty != Op->getType())
995  return cannotDivide(Numerator);
996 
997  if (FoundDenominatorTerm) {
998  Qs.push_back(Op);
999  continue;
1000  }
1001 
1002  // Check whether Denominator divides one of the product operands.
1003  const SCEV *Q, *R;
1004  divide(SE, Op, Denominator, &Q, &R);
1005  if (!R->isZero()) {
1006  Qs.push_back(Op);
1007  continue;
1008  }
1009 
1010  // Bail out if types do not match.
1011  if (Ty != Q->getType())
1012  return cannotDivide(Numerator);
1013 
1014  FoundDenominatorTerm = true;
1015  Qs.push_back(Q);
1016  }
1017 
1018  if (FoundDenominatorTerm) {
1019  Remainder = Zero;
1020  if (Qs.size() == 1)
1021  Quotient = Qs[0];
1022  else
1023  Quotient = SE.getMulExpr(Qs);
1024  return;
1025  }
1026 
1027  if (!isa<SCEVUnknown>(Denominator))
1028  return cannotDivide(Numerator);
1029 
1030  // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1031  ValueToValueMap RewriteMap;
1032  RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1033  cast<SCEVConstant>(Zero)->getValue();
1034  Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1035 
1036  if (Remainder->isZero()) {
1037  // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1038  RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1039  cast<SCEVConstant>(One)->getValue();
1040  Quotient =
1041  SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1042  return;
1043  }
1044 
1045  // Quotient is (Numerator - Remainder) divided by Denominator.
1046  const SCEV *Q, *R;
1047  const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1048  // This SCEV does not seem to simplify: fail the division here.
1049  if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1050  return cannotDivide(Numerator);
1051  divide(SE, Diff, Denominator, &Q, &R);
1052  if (R != Zero)
1053  return cannotDivide(Numerator);
1054  Quotient = Q;
1055  }
1056 
1057 private:
1058  SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1059  const SCEV *Denominator)
1060  : SE(S), Denominator(Denominator) {
1061  Zero = SE.getZero(Denominator->getType());
1062  One = SE.getOne(Denominator->getType());
1063 
1064  // We generally do not know how to divide Expr by Denominator. We
1065  // initialize the division to a "cannot divide" state to simplify the rest
1066  // of the code.
1067  cannotDivide(Numerator);
1068  }
1069 
1070  // Convenience function for giving up on the division. We set the quotient to
1071  // be equal to zero and the remainder to be equal to the numerator.
1072  void cannotDivide(const SCEV *Numerator) {
1073  Quotient = Zero;
1074  Remainder = Numerator;
1075  }
1076 
1077  ScalarEvolution &SE;
1078  const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1079 };
1080 
1081 } // end anonymous namespace
1082 
1083 //===----------------------------------------------------------------------===//
1084 // Simple SCEV method implementations
1085 //===----------------------------------------------------------------------===//
1086 
1087 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1088 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1089  ScalarEvolution &SE,
1090  Type *ResultTy) {
1091  // Handle the simplest case efficiently.
1092  if (K == 1)
1093  return SE.getTruncateOrZeroExtend(It, ResultTy);
1094 
1095  // We are using the following formula for BC(It, K):
1096  //
1097  // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1098  //
1099  // Suppose, W is the bitwidth of the return value. We must be prepared for
1100  // overflow. Hence, we must assure that the result of our computation is
1101  // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1102  // safe in modular arithmetic.
1103  //
1104  // However, this code doesn't use exactly that formula; the formula it uses
1105  // is something like the following, where T is the number of factors of 2 in
1106  // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1107  // exponentiation:
1108  //
1109  // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1110  //
1111  // This formula is trivially equivalent to the previous formula. However,
1112  // this formula can be implemented much more efficiently. The trick is that
1113  // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1114  // arithmetic. To do exact division in modular arithmetic, all we have
1115  // to do is multiply by the inverse. Therefore, this step can be done at
1116  // width W.
1117  //
1118  // The next issue is how to safely do the division by 2^T. The way this
1119  // is done is by doing the multiplication step at a width of at least W + T
1120  // bits. This way, the bottom W+T bits of the product are accurate. Then,
1121  // when we perform the division by 2^T (which is equivalent to a right shift
1122  // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1123  // truncated out after the division by 2^T.
1124  //
1125  // In comparison to just directly using the first formula, this technique
1126  // is much more efficient; using the first formula requires W * K bits,
1127  // but this formula less than W + K bits. Also, the first formula requires
1128  // a division step, whereas this formula only requires multiplies and shifts.
1129  //
1130  // It doesn't matter whether the subtraction step is done in the calculation
1131  // width or the input iteration count's width; if the subtraction overflows,
1132  // the result must be zero anyway. We prefer here to do it in the width of
1133  // the induction variable because it helps a lot for certain cases; CodeGen
1134  // isn't smart enough to ignore the overflow, which leads to much less
1135  // efficient code if the width of the subtraction is wider than the native
1136  // register width.
1137  //
1138  // (It's possible to not widen at all by pulling out factors of 2 before
1139  // the multiplication; for example, K=2 can be calculated as
1140  // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1141  // extra arithmetic, so it's not an obvious win, and it gets
1142  // much more complicated for K > 3.)
1143 
1144  // Protection from insane SCEVs; this bound is conservative,
1145  // but it probably doesn't matter.
1146  if (K > 1000)
1147  return SE.getCouldNotCompute();
1148 
1149  unsigned W = SE.getTypeSizeInBits(ResultTy);
1150 
1151  // Calculate K! / 2^T and T; we divide out the factors of two before
1152  // multiplying for calculating K! / 2^T to avoid overflow.
1153  // Other overflow doesn't matter because we only care about the bottom
1154  // W bits of the result.
1155  APInt OddFactorial(W, 1);
1156  unsigned T = 1;
1157  for (unsigned i = 3; i <= K; ++i) {
1158  APInt Mult(W, i);
1159  unsigned TwoFactors = Mult.countTrailingZeros();
1160  T += TwoFactors;
1161  Mult.lshrInPlace(TwoFactors);
1162  OddFactorial *= Mult;
1163  }
1164 
1165  // We need at least W + T bits for the multiplication step
1166  unsigned CalculationBits = W + T;
1167 
1168  // Calculate 2^T, at width T+W.
1169  APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1170 
1171  // Calculate the multiplicative inverse of K! / 2^T;
1172  // this multiplication factor will perform the exact division by
1173  // K! / 2^T.
1175  APInt MultiplyFactor = OddFactorial.zext(W+1);
1176  MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1177  MultiplyFactor = MultiplyFactor.trunc(W);
1178 
1179  // Calculate the product, at width T+W
1180  IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1181  CalculationBits);
1182  const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1183  for (unsigned i = 1; i != K; ++i) {
1184  const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1185  Dividend = SE.getMulExpr(Dividend,
1186  SE.getTruncateOrZeroExtend(S, CalculationTy));
1187  }
1188 
1189  // Divide by 2^T
1190  const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1191 
1192  // Truncate the result, and divide by K! / 2^T.
1193 
1194  return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1195  SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1196 }
1197 
1198 /// Return the value of this chain of recurrences at the specified iteration
1199 /// number. We can evaluate this recurrence by multiplying each element in the
1200 /// chain by the binomial coefficient corresponding to it. In other words, we
1201 /// can evaluate {A,+,B,+,C,+,D} as:
1202 ///
1203 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1204 ///
1205 /// where BC(It, k) stands for binomial coefficient.
1207  ScalarEvolution &SE) const {
1208  const SCEV *Result = getStart();
1209  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1210  // The computation is correct in the face of overflow provided that the
1211  // multiplication is performed _after_ the evaluation of the binomial
1212  // coefficient.
1213  const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1214  if (isa<SCEVCouldNotCompute>(Coeff))
1215  return Coeff;
1216 
1217  Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1218  }
1219  return Result;
1220 }
1221 
1222 //===----------------------------------------------------------------------===//
1223 // SCEV Expression folder implementations
1224 //===----------------------------------------------------------------------===//
1225 
1227  Type *Ty) {
1228  assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1229  "This is not a truncating conversion!");
1230  assert(isSCEVable(Ty) &&
1231  "This is not a conversion to a SCEVable type!");
1232  Ty = getEffectiveSCEVType(Ty);
1233 
1235  ID.AddInteger(scTruncate);
1236  ID.AddPointer(Op);
1237  ID.AddPointer(Ty);
1238  void *IP = nullptr;
1239  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1240 
1241  // Fold if the operand is constant.
1242  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1243  return getConstant(
1244  cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1245 
1246  // trunc(trunc(x)) --> trunc(x)
1247  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1248  return getTruncateExpr(ST->getOperand(), Ty);
1249 
1250  // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1251  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1252  return getTruncateOrSignExtend(SS->getOperand(), Ty);
1253 
1254  // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1255  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1256  return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1257 
1258  // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1259  // eliminate all the truncates, or we replace other casts with truncates.
1260  if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1262  bool hasTrunc = false;
1263  for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1264  const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1265  if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1266  hasTrunc = isa<SCEVTruncateExpr>(S);
1267  Operands.push_back(S);
1268  }
1269  if (!hasTrunc)
1270  return getAddExpr(Operands);
1271  // In spite we checked in the beginning that ID is not in the cache,
1272  // it is possible that during recursion and different modification
1273  // ID came to cache, so if we found it, just return it.
1274  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1275  return S;
1276  }
1277 
1278  // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1279  // eliminate all the truncates, or we replace other casts with truncates.
1280  if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1282  bool hasTrunc = false;
1283  for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1284  const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1285  if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1286  hasTrunc = isa<SCEVTruncateExpr>(S);
1287  Operands.push_back(S);
1288  }
1289  if (!hasTrunc)
1290  return getMulExpr(Operands);
1291  // In spite we checked in the beginning that ID is not in the cache,
1292  // it is possible that during recursion and different modification
1293  // ID came to cache, so if we found it, just return it.
1294  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1295  return S;
1296  }
1297 
1298  // If the input value is a chrec scev, truncate the chrec's operands.
1299  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1301  for (const SCEV *Op : AddRec->operands())
1302  Operands.push_back(getTruncateExpr(Op, Ty));
1303  return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1304  }
1305 
1306  // The cast wasn't folded; create an explicit cast node. We can reuse
1307  // the existing insert position since if we get here, we won't have
1308  // made any changes which would invalidate it.
1309  SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1310  Op, Ty);
1311  UniqueSCEVs.InsertNode(S, IP);
1312  addToLoopUseLists(S);
1313  return S;
1314 }
1315 
1316 // Get the limit of a recurrence such that incrementing by Step cannot cause
1317 // signed overflow as long as the value of the recurrence within the
1318 // loop does not exceed this limit before incrementing.
1319 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1320  ICmpInst::Predicate *Pred,
1321  ScalarEvolution *SE) {
1322  unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1323  if (SE->isKnownPositive(Step)) {
1324  *Pred = ICmpInst::ICMP_SLT;
1325  return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1326  SE->getSignedRangeMax(Step));
1327  }
1328  if (SE->isKnownNegative(Step)) {
1329  *Pred = ICmpInst::ICMP_SGT;
1330  return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1331  SE->getSignedRangeMin(Step));
1332  }
1333  return nullptr;
1334 }
1335 
1336 // Get the limit of a recurrence such that incrementing by Step cannot cause
1337 // unsigned overflow as long as the value of the recurrence within the loop does
1338 // not exceed this limit before incrementing.
1339 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1340  ICmpInst::Predicate *Pred,
1341  ScalarEvolution *SE) {
1342  unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1343  *Pred = ICmpInst::ICMP_ULT;
1344 
1345  return SE->getConstant(APInt::getMinValue(BitWidth) -
1346  SE->getUnsignedRangeMax(Step));
1347 }
1348 
1349 namespace {
1350 
1351 struct ExtendOpTraitsBase {
1352  typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1353  unsigned);
1354 };
1355 
1356 // Used to make code generic over signed and unsigned overflow.
1357 template <typename ExtendOp> struct ExtendOpTraits {
1358  // Members present:
1359  //
1360  // static const SCEV::NoWrapFlags WrapType;
1361  //
1362  // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1363  //
1364  // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1365  // ICmpInst::Predicate *Pred,
1366  // ScalarEvolution *SE);
1367 };
1368 
1369 template <>
1370 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1371  static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1372 
1373  static const GetExtendExprTy GetExtendExpr;
1374 
1375  static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1376  ICmpInst::Predicate *Pred,
1377  ScalarEvolution *SE) {
1378  return getSignedOverflowLimitForStep(Step, Pred, SE);
1379  }
1380 };
1381 
1382 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1383  SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1384 
1385 template <>
1386 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1387  static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1388 
1389  static const GetExtendExprTy GetExtendExpr;
1390 
1391  static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1392  ICmpInst::Predicate *Pred,
1393  ScalarEvolution *SE) {
1394  return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1395  }
1396 };
1397 
1398 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1399  SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1400 
1401 } // end anonymous namespace
1402 
1403 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1404 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1405 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1406 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1407 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1408 // expression "Step + sext/zext(PreIncAR)" is congruent with
1409 // "sext/zext(PostIncAR)"
1410 template <typename ExtendOpTy>
1411 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1412  ScalarEvolution *SE, unsigned Depth) {
1413  auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1414  auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1415 
1416  const Loop *L = AR->getLoop();
1417  const SCEV *Start = AR->getStart();
1418  const SCEV *Step = AR->getStepRecurrence(*SE);
1419 
1420  // Check for a simple looking step prior to loop entry.
1421  const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1422  if (!SA)
1423  return nullptr;
1424 
1425  // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1426  // subtraction is expensive. For this purpose, perform a quick and dirty
1427  // difference, by checking for Step in the operand list.
1429  for (const SCEV *Op : SA->operands())
1430  if (Op != Step)
1431  DiffOps.push_back(Op);
1432 
1433  if (DiffOps.size() == SA->getNumOperands())
1434  return nullptr;
1435 
1436  // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1437  // `Step`:
1438 
1439  // 1. NSW/NUW flags on the step increment.
1440  auto PreStartFlags =
1442  const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1443  const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1444  SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1445 
1446  // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1447  // "S+X does not sign/unsign-overflow".
1448  //
1449 
1450  const SCEV *BECount = SE->getBackedgeTakenCount(L);
1451  if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1452  !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1453  return PreStart;
1454 
1455  // 2. Direct overflow check on the step operation's expression.
1456  unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1457  Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1458  const SCEV *OperandExtendedStart =
1459  SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1460  (SE->*GetExtendExpr)(Step, WideTy, Depth));
1461  if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1462  if (PreAR && AR->getNoWrapFlags(WrapType)) {
1463  // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1464  // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1465  // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1466  const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1467  }
1468  return PreStart;
1469  }
1470 
1471  // 3. Loop precondition.
1472  ICmpInst::Predicate Pred;
1473  const SCEV *OverflowLimit =
1474  ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1475 
1476  if (OverflowLimit &&
1477  SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1478  return PreStart;
1479 
1480  return nullptr;
1481 }
1482 
1483 // Get the normalized zero or sign extended expression for this AddRec's Start.
1484 template <typename ExtendOpTy>
1485 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1486  ScalarEvolution *SE,
1487  unsigned Depth) {
1488  auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1489 
1490  const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1491  if (!PreStart)
1492  return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1493 
1494  return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1495  Depth),
1496  (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1497 }
1498 
1499 // Try to prove away overflow by looking at "nearby" add recurrences. A
1500 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1501 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1502 //
1503 // Formally:
1504 //
1505 // {S,+,X} == {S-T,+,X} + T
1506 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1507 //
1508 // If ({S-T,+,X} + T) does not overflow ... (1)
1509 //
1510 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1511 //
1512 // If {S-T,+,X} does not overflow ... (2)
1513 //
1514 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1515 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1516 //
1517 // If (S-T)+T does not overflow ... (3)
1518 //
1519 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1520 // == {Ext(S),+,Ext(X)} == LHS
1521 //
1522 // Thus, if (1), (2) and (3) are true for some T, then
1523 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1524 //
1525 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1526 // does not overflow" restricted to the 0th iteration. Therefore we only need
1527 // to check for (1) and (2).
1528 //
1529 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1530 // is `Delta` (defined below).
1531 template <typename ExtendOpTy>
1532 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1533  const SCEV *Step,
1534  const Loop *L) {
1535  auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1536 
1537  // We restrict `Start` to a constant to prevent SCEV from spending too much
1538  // time here. It is correct (but more expensive) to continue with a
1539  // non-constant `Start` and do a general SCEV subtraction to compute
1540  // `PreStart` below.
1541  const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1542  if (!StartC)
1543  return false;
1544 
1545  APInt StartAI = StartC->getAPInt();
1546 
1547  for (unsigned Delta : {-2, -1, 1, 2}) {
1548  const SCEV *PreStart = getConstant(StartAI - Delta);
1549 
1552  ID.AddPointer(PreStart);
1553  ID.AddPointer(Step);
1554  ID.AddPointer(L);
1555  void *IP = nullptr;
1556  const auto *PreAR =
1557  static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1558 
1559  // Give up if we don't already have the add recurrence we need because
1560  // actually constructing an add recurrence is relatively expensive.
1561  if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1562  const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1564  const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1565  DeltaS, &Pred, this);
1566  if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1567  return true;
1568  }
1569  }
1570 
1571  return false;
1572 }
1573 
1574 const SCEV *
1576  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1577  "This is not an extending conversion!");
1578  assert(isSCEVable(Ty) &&
1579  "This is not a conversion to a SCEVable type!");
1580  Ty = getEffectiveSCEVType(Ty);
1581 
1582  // Fold if the operand is constant.
1583  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1584  return getConstant(
1585  cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1586 
1587  // zext(zext(x)) --> zext(x)
1588  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1589  return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1590 
1591  // Before doing any expensive analysis, check to see if we've already
1592  // computed a SCEV for this Op and Ty.
1595  ID.AddPointer(Op);
1596  ID.AddPointer(Ty);
1597  void *IP = nullptr;
1598  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1599  if (Depth > MaxExtDepth) {
1600  SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1601  Op, Ty);
1602  UniqueSCEVs.InsertNode(S, IP);
1603  addToLoopUseLists(S);
1604  return S;
1605  }
1606 
1607  // zext(trunc(x)) --> zext(x) or x or trunc(x)
1608  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1609  // It's possible the bits taken off by the truncate were all zero bits. If
1610  // so, we should be able to simplify this further.
1611  const SCEV *X = ST->getOperand();
1612  ConstantRange CR = getUnsignedRange(X);
1613  unsigned TruncBits = getTypeSizeInBits(ST->getType());
1614  unsigned NewBits = getTypeSizeInBits(Ty);
1615  if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1616  CR.zextOrTrunc(NewBits)))
1617  return getTruncateOrZeroExtend(X, Ty);
1618  }
1619 
1620  // If the input value is a chrec scev, and we can prove that the value
1621  // did not overflow the old, smaller, value, we can zero extend all of the
1622  // operands (often constants). This allows analysis of something like
1623  // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1624  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1625  if (AR->isAffine()) {
1626  const SCEV *Start = AR->getStart();
1627  const SCEV *Step = AR->getStepRecurrence(*this);
1628  unsigned BitWidth = getTypeSizeInBits(AR->getType());
1629  const Loop *L = AR->getLoop();
1630 
1631  if (!AR->hasNoUnsignedWrap()) {
1632  auto NewFlags = proveNoWrapViaConstantRanges(AR);
1633  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1634  }
1635 
1636  // If we have special knowledge that this addrec won't overflow,
1637  // we don't need to do any further analysis.
1638  if (AR->hasNoUnsignedWrap())
1639  return getAddRecExpr(
1640  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1641  getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1642 
1643  // Check whether the backedge-taken count is SCEVCouldNotCompute.
1644  // Note that this serves two purposes: It filters out loops that are
1645  // simply not analyzable, and it covers the case where this code is
1646  // being called from within backedge-taken count analysis, such that
1647  // attempting to ask for the backedge-taken count would likely result
1648  // in infinite recursion. In the later case, the analysis code will
1649  // cope with a conservative value, and it will take care to purge
1650  // that value once it has finished.
1651  const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1652  if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1653  // Manually compute the final value for AR, checking for
1654  // overflow.
1655 
1656  // Check whether the backedge-taken count can be losslessly casted to
1657  // the addrec's type. The count is always unsigned.
1658  const SCEV *CastedMaxBECount =
1659  getTruncateOrZeroExtend(MaxBECount, Start->getType());
1660  const SCEV *RecastedMaxBECount =
1661  getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1662  if (MaxBECount == RecastedMaxBECount) {
1663  Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1664  // Check whether Start+Step*MaxBECount has no unsigned overflow.
1665  const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1666  SCEV::FlagAnyWrap, Depth + 1);
1667  const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1669  Depth + 1),
1670  WideTy, Depth + 1);
1671  const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1672  const SCEV *WideMaxBECount =
1673  getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1674  const SCEV *OperandExtendedAdd =
1675  getAddExpr(WideStart,
1676  getMulExpr(WideMaxBECount,
1677  getZeroExtendExpr(Step, WideTy, Depth + 1),
1678  SCEV::FlagAnyWrap, Depth + 1),
1679  SCEV::FlagAnyWrap, Depth + 1);
1680  if (ZAdd == OperandExtendedAdd) {
1681  // Cache knowledge of AR NUW, which is propagated to this AddRec.
1682  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1683  // Return the expression with the addrec on the outside.
1684  return getAddRecExpr(
1685  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1686  Depth + 1),
1687  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1688  AR->getNoWrapFlags());
1689  }
1690  // Similar to above, only this time treat the step value as signed.
1691  // This covers loops that count down.
1692  OperandExtendedAdd =
1693  getAddExpr(WideStart,
1694  getMulExpr(WideMaxBECount,
1695  getSignExtendExpr(Step, WideTy, Depth + 1),
1696  SCEV::FlagAnyWrap, Depth + 1),
1697  SCEV::FlagAnyWrap, Depth + 1);
1698  if (ZAdd == OperandExtendedAdd) {
1699  // Cache knowledge of AR NW, which is propagated to this AddRec.
1700  // Negative step causes unsigned wrap, but it still can't self-wrap.
1701  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1702  // Return the expression with the addrec on the outside.
1703  return getAddRecExpr(
1704  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1705  Depth + 1),
1706  getSignExtendExpr(Step, Ty, Depth + 1), L,
1707  AR->getNoWrapFlags());
1708  }
1709  }
1710  }
1711 
1712  // Normally, in the cases we can prove no-overflow via a
1713  // backedge guarding condition, we can also compute a backedge
1714  // taken count for the loop. The exceptions are assumptions and
1715  // guards present in the loop -- SCEV is not great at exploiting
1716  // these to compute max backedge taken counts, but can still use
1717  // these to prove lack of overflow. Use this fact to avoid
1718  // doing extra work that may not pay off.
1719  if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1720  !AC.assumptions().empty()) {
1721  // If the backedge is guarded by a comparison with the pre-inc
1722  // value the addrec is safe. Also, if the entry is guarded by
1723  // a comparison with the start value and the backedge is
1724  // guarded by a comparison with the post-inc value, the addrec
1725  // is safe.
1726  if (isKnownPositive(Step)) {
1727  const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1728  getUnsignedRangeMax(Step));
1729  if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1730  (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1731  isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1732  AR->getPostIncExpr(*this), N))) {
1733  // Cache knowledge of AR NUW, which is propagated to this
1734  // AddRec.
1735  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1736  // Return the expression with the addrec on the outside.
1737  return getAddRecExpr(
1738  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1739  Depth + 1),
1740  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1741  AR->getNoWrapFlags());
1742  }
1743  } else if (isKnownNegative(Step)) {
1744  const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1745  getSignedRangeMin(Step));
1746  if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1747  (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1748  isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1749  AR->getPostIncExpr(*this), N))) {
1750  // Cache knowledge of AR NW, which is propagated to this
1751  // AddRec. Negative step causes unsigned wrap, but it
1752  // still can't self-wrap.
1753  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1754  // Return the expression with the addrec on the outside.
1755  return getAddRecExpr(
1756  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1757  Depth + 1),
1758  getSignExtendExpr(Step, Ty, Depth + 1), L,
1759  AR->getNoWrapFlags());
1760  }
1761  }
1762  }
1763 
1764  if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1765  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(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  if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1773  // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1774  if (SA->hasNoUnsignedWrap()) {
1775  // If the addition does not unsign overflow then we can, by definition,
1776  // commute the zero extension with the addition operation.
1778  for (const auto *Op : SA->operands())
1779  Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1780  return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1781  }
1782  }
1783 
1784  // The cast wasn't folded; create an explicit cast node.
1785  // Recompute the insert position, as it may have been invalidated.
1786  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1787  SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1788  Op, Ty);
1789  UniqueSCEVs.InsertNode(S, IP);
1790  addToLoopUseLists(S);
1791  return S;
1792 }
1793 
1794 const SCEV *
1796  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1797  "This is not an extending conversion!");
1798  assert(isSCEVable(Ty) &&
1799  "This is not a conversion to a SCEVable type!");
1800  Ty = getEffectiveSCEVType(Ty);
1801 
1802  // Fold if the operand is constant.
1803  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1804  return getConstant(
1805  cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1806 
1807  // sext(sext(x)) --> sext(x)
1808  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1809  return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1810 
1811  // sext(zext(x)) --> zext(x)
1812  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1813  return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1814 
1815  // Before doing any expensive analysis, check to see if we've already
1816  // computed a SCEV for this Op and Ty.
1819  ID.AddPointer(Op);
1820  ID.AddPointer(Ty);
1821  void *IP = nullptr;
1822  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1823  // Limit recursion depth.
1824  if (Depth > MaxExtDepth) {
1825  SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1826  Op, Ty);
1827  UniqueSCEVs.InsertNode(S, IP);
1828  addToLoopUseLists(S);
1829  return S;
1830  }
1831 
1832  // sext(trunc(x)) --> sext(x) or x or trunc(x)
1833  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1834  // It's possible the bits taken off by the truncate were all sign bits. If
1835  // so, we should be able to simplify this further.
1836  const SCEV *X = ST->getOperand();
1837  ConstantRange CR = getSignedRange(X);
1838  unsigned TruncBits = getTypeSizeInBits(ST->getType());
1839  unsigned NewBits = getTypeSizeInBits(Ty);
1840  if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1841  CR.sextOrTrunc(NewBits)))
1842  return getTruncateOrSignExtend(X, Ty);
1843  }
1844 
1845  // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1846  if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1847  if (SA->getNumOperands() == 2) {
1848  auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1849  auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1850  if (SMul && SC1) {
1851  if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1852  const APInt &C1 = SC1->getAPInt();
1853  const APInt &C2 = SC2->getAPInt();
1854  if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1855  C2.ugt(C1) && C2.isPowerOf2())
1856  return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1857  getSignExtendExpr(SMul, Ty, Depth + 1),
1858  SCEV::FlagAnyWrap, Depth + 1);
1859  }
1860  }
1861  }
1862 
1863  // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1864  if (SA->hasNoSignedWrap()) {
1865  // If the addition does not sign overflow then we can, by definition,
1866  // commute the sign extension with the addition operation.
1868  for (const auto *Op : SA->operands())
1869  Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1870  return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1871  }
1872  }
1873  // If the input value is a chrec scev, and we can prove that the value
1874  // did not overflow the old, smaller, value, we can sign extend all of the
1875  // operands (often constants). This allows analysis of something like
1876  // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1877  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1878  if (AR->isAffine()) {
1879  const SCEV *Start = AR->getStart();
1880  const SCEV *Step = AR->getStepRecurrence(*this);
1881  unsigned BitWidth = getTypeSizeInBits(AR->getType());
1882  const Loop *L = AR->getLoop();
1883 
1884  if (!AR->hasNoSignedWrap()) {
1885  auto NewFlags = proveNoWrapViaConstantRanges(AR);
1886  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1887  }
1888 
1889  // If we have special knowledge that this addrec won't overflow,
1890  // we don't need to do any further analysis.
1891  if (AR->hasNoSignedWrap())
1892  return getAddRecExpr(
1893  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1894  getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1895 
1896  // Check whether the backedge-taken count is SCEVCouldNotCompute.
1897  // Note that this serves two purposes: It filters out loops that are
1898  // simply not analyzable, and it covers the case where this code is
1899  // being called from within backedge-taken count analysis, such that
1900  // attempting to ask for the backedge-taken count would likely result
1901  // in infinite recursion. In the later case, the analysis code will
1902  // cope with a conservative value, and it will take care to purge
1903  // that value once it has finished.
1904  const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1905  if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1906  // Manually compute the final value for AR, checking for
1907  // overflow.
1908 
1909  // Check whether the backedge-taken count can be losslessly casted to
1910  // the addrec's type. The count is always unsigned.
1911  const SCEV *CastedMaxBECount =
1912  getTruncateOrZeroExtend(MaxBECount, Start->getType());
1913  const SCEV *RecastedMaxBECount =
1914  getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1915  if (MaxBECount == RecastedMaxBECount) {
1916  Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1917  // Check whether Start+Step*MaxBECount has no signed overflow.
1918  const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1919  SCEV::FlagAnyWrap, Depth + 1);
1920  const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1922  Depth + 1),
1923  WideTy, Depth + 1);
1924  const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1925  const SCEV *WideMaxBECount =
1926  getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1927  const SCEV *OperandExtendedAdd =
1928  getAddExpr(WideStart,
1929  getMulExpr(WideMaxBECount,
1930  getSignExtendExpr(Step, WideTy, Depth + 1),
1931  SCEV::FlagAnyWrap, Depth + 1),
1932  SCEV::FlagAnyWrap, Depth + 1);
1933  if (SAdd == OperandExtendedAdd) {
1934  // Cache knowledge of AR NSW, which is propagated to this AddRec.
1935  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1936  // Return the expression with the addrec on the outside.
1937  return getAddRecExpr(
1938  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1939  Depth + 1),
1940  getSignExtendExpr(Step, Ty, Depth + 1), L,
1941  AR->getNoWrapFlags());
1942  }
1943  // Similar to above, only this time treat the step value as unsigned.
1944  // This covers loops that count up with an unsigned step.
1945  OperandExtendedAdd =
1946  getAddExpr(WideStart,
1947  getMulExpr(WideMaxBECount,
1948  getZeroExtendExpr(Step, WideTy, Depth + 1),
1949  SCEV::FlagAnyWrap, Depth + 1),
1950  SCEV::FlagAnyWrap, Depth + 1);
1951  if (SAdd == OperandExtendedAdd) {
1952  // If AR wraps around then
1953  //
1954  // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1955  // => SAdd != OperandExtendedAdd
1956  //
1957  // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1958  // (SAdd == OperandExtendedAdd => AR is NW)
1959 
1960  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1961 
1962  // Return the expression with the addrec on the outside.
1963  return getAddRecExpr(
1964  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1965  Depth + 1),
1966  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1967  AR->getNoWrapFlags());
1968  }
1969  }
1970  }
1971 
1972  // Normally, in the cases we can prove no-overflow via a
1973  // backedge guarding condition, we can also compute a backedge
1974  // taken count for the loop. The exceptions are assumptions and
1975  // guards present in the loop -- SCEV is not great at exploiting
1976  // these to compute max backedge taken counts, but can still use
1977  // these to prove lack of overflow. Use this fact to avoid
1978  // doing extra work that may not pay off.
1979 
1980  if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1981  !AC.assumptions().empty()) {
1982  // If the backedge is guarded by a comparison with the pre-inc
1983  // value the addrec is safe. Also, if the entry is guarded by
1984  // a comparison with the start value and the backedge is
1985  // guarded by a comparison with the post-inc value, the addrec
1986  // is safe.
1987  ICmpInst::Predicate Pred;
1988  const SCEV *OverflowLimit =
1989  getSignedOverflowLimitForStep(Step, &Pred, this);
1990  if (OverflowLimit &&
1991  (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1992  (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1993  isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1994  OverflowLimit)))) {
1995  // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1996  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1997  return getAddRecExpr(
1998  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1999  getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2000  }
2001  }
2002 
2003  // If Start and Step are constants, check if we can apply this
2004  // transformation:
2005  // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2006  auto *SC1 = dyn_cast<SCEVConstant>(Start);
2007  auto *SC2 = dyn_cast<SCEVConstant>(Step);
2008  if (SC1 && SC2) {
2009  const APInt &C1 = SC1->getAPInt();
2010  const APInt &C2 = SC2->getAPInt();
2011  if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2012  C2.isPowerOf2()) {
2013  Start = getSignExtendExpr(Start, Ty, Depth + 1);
2014  const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2015  AR->getNoWrapFlags());
2016  return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2017  SCEV::FlagAnyWrap, Depth + 1);
2018  }
2019  }
2020 
2021  if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2022  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2023  return getAddRecExpr(
2024  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2025  getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2026  }
2027  }
2028 
2029  // If the input value is provably positive and we could not simplify
2030  // away the sext build a zext instead.
2031  if (isKnownNonNegative(Op))
2032  return getZeroExtendExpr(Op, Ty, Depth + 1);
2033 
2034  // The cast wasn't folded; create an explicit cast node.
2035  // Recompute the insert position, as it may have been invalidated.
2036  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2037  SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2038  Op, Ty);
2039  UniqueSCEVs.InsertNode(S, IP);
2040  addToLoopUseLists(S);
2041  return S;
2042 }
2043 
2044 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2045 /// unspecified bits out to the given type.
2047  Type *Ty) {
2048  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2049  "This is not an extending conversion!");
2050  assert(isSCEVable(Ty) &&
2051  "This is not a conversion to a SCEVable type!");
2052  Ty = getEffectiveSCEVType(Ty);
2053 
2054  // Sign-extend negative constants.
2055  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2056  if (SC->getAPInt().isNegative())
2057  return getSignExtendExpr(Op, Ty);
2058 
2059  // Peel off a truncate cast.
2060  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2061  const SCEV *NewOp = T->getOperand();
2062  if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2063  return getAnyExtendExpr(NewOp, Ty);
2064  return getTruncateOrNoop(NewOp, Ty);
2065  }
2066 
2067  // Next try a zext cast. If the cast is folded, use it.
2068  const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2069  if (!isa<SCEVZeroExtendExpr>(ZExt))
2070  return ZExt;
2071 
2072  // Next try a sext cast. If the cast is folded, use it.
2073  const SCEV *SExt = getSignExtendExpr(Op, Ty);
2074  if (!isa<SCEVSignExtendExpr>(SExt))
2075  return SExt;
2076 
2077  // Force the cast to be folded into the operands of an addrec.
2078  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2080  for (const SCEV *Op : AR->operands())
2081  Ops.push_back(getAnyExtendExpr(Op, Ty));
2082  return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2083  }
2084 
2085  // If the expression is obviously signed, use the sext cast value.
2086  if (isa<SCEVSMaxExpr>(Op))
2087  return SExt;
2088 
2089  // Absent any other information, use the zext cast value.
2090  return ZExt;
2091 }
2092 
2093 /// Process the given Ops list, which is a list of operands to be added under
2094 /// the given scale, update the given map. This is a helper function for
2095 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2096 /// that would form an add expression like this:
2097 ///
2098 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2099 ///
2100 /// where A and B are constants, update the map with these values:
2101 ///
2102 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2103 ///
2104 /// and add 13 + A*B*29 to AccumulatedConstant.
2105 /// This will allow getAddRecExpr to produce this:
2106 ///
2107 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2108 ///
2109 /// This form often exposes folding opportunities that are hidden in
2110 /// the original operand list.
2111 ///
2112 /// Return true iff it appears that any interesting folding opportunities
2113 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2114 /// the common case where no interesting opportunities are present, and
2115 /// is also used as a check to avoid infinite recursion.
2116 static bool
2119  APInt &AccumulatedConstant,
2120  const SCEV *const *Ops, size_t NumOperands,
2121  const APInt &Scale,
2122  ScalarEvolution &SE) {
2123  bool Interesting = false;
2124 
2125  // Iterate over the add operands. They are sorted, with constants first.
2126  unsigned i = 0;
2127  while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2128  ++i;
2129  // Pull a buried constant out to the outside.
2130  if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2131  Interesting = true;
2132  AccumulatedConstant += Scale * C->getAPInt();
2133  }
2134 
2135  // Next comes everything else. We're especially interested in multiplies
2136  // here, but they're in the middle, so just visit the rest with one loop.
2137  for (; i != NumOperands; ++i) {
2138  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2139  if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2140  APInt NewScale =
2141  Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2142  if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2143  // A multiplication of a constant with another add; recurse.
2144  const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2145  Interesting |=
2146  CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2147  Add->op_begin(), Add->getNumOperands(),
2148  NewScale, SE);
2149  } else {
2150  // A multiplication of a constant with some other value. Update
2151  // the map.
2152  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2153  const SCEV *Key = SE.getMulExpr(MulOps);
2154  auto Pair = M.insert({Key, NewScale});
2155  if (Pair.second) {
2156  NewOps.push_back(Pair.first->first);
2157  } else {
2158  Pair.first->second += NewScale;
2159  // The map already had an entry for this value, which may indicate
2160  // a folding opportunity.
2161  Interesting = true;
2162  }
2163  }
2164  } else {
2165  // An ordinary operand. Update the map.
2166  std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2167  M.insert({Ops[i], Scale});
2168  if (Pair.second) {
2169  NewOps.push_back(Pair.first->first);
2170  } else {
2171  Pair.first->second += Scale;
2172  // The map already had an entry for this value, which may indicate
2173  // a folding opportunity.
2174  Interesting = true;
2175  }
2176  }
2177  }
2178 
2179  return Interesting;
2180 }
2181 
2182 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2183 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2184 // can't-overflow flags for the operation if possible.
2185 static SCEV::NoWrapFlags
2187  const SmallVectorImpl<const SCEV *> &Ops,
2188  SCEV::NoWrapFlags Flags) {
2189  using namespace std::placeholders;
2190 
2191  using OBO = OverflowingBinaryOperator;
2192 
2193  bool CanAnalyze =
2194  Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2195  (void)CanAnalyze;
2196  assert(CanAnalyze && "don't call from other places!");
2197 
2198  int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2199  SCEV::NoWrapFlags SignOrUnsignWrap =
2200  ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2201 
2202  // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2203  auto IsKnownNonNegative = [&](const SCEV *S) {
2204  return SE->isKnownNonNegative(S);
2205  };
2206 
2207  if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2208  Flags =
2209  ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2210 
2211  SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2212 
2213  if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2214  Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2215 
2216  // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2217  // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2218 
2219  const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2220  if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2222  Instruction::Add, C, OBO::NoSignedWrap);
2223  if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2224  Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2225  }
2226  if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2228  Instruction::Add, C, OBO::NoUnsignedWrap);
2229  if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2230  Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2231  }
2232  }
2233 
2234  return Flags;
2235 }
2236 
2238  if (!isLoopInvariant(S, L))
2239  return false;
2240  // If a value depends on a SCEVUnknown which is defined after the loop, we
2241  // conservatively assume that we cannot calculate it at the loop's entry.
2242  struct FindDominatedSCEVUnknown {
2243  bool Found = false;
2244  const Loop *L;
2245  DominatorTree &DT;
2246  LoopInfo &LI;
2247 
2248  FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2249  : L(L), DT(DT), LI(LI) {}
2250 
2251  bool checkSCEVUnknown(const SCEVUnknown *SU) {
2252  if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2253  if (DT.dominates(L->getHeader(), I->getParent()))
2254  Found = true;
2255  else
2256  assert(DT.dominates(I->getParent(), L->getHeader()) &&
2257  "No dominance relationship between SCEV and loop?");
2258  }
2259  return false;
2260  }
2261 
2262  bool follow(const SCEV *S) {
2263  switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2264  case scConstant:
2265  return false;
2266  case scAddRecExpr:
2267  case scTruncate:
2268  case scZeroExtend:
2269  case scSignExtend:
2270  case scAddExpr:
2271  case scMulExpr:
2272  case scUMaxExpr:
2273  case scSMaxExpr:
2274  case scUDivExpr:
2275  return true;
2276  case scUnknown:
2277  return checkSCEVUnknown(cast<SCEVUnknown>(S));
2278  case scCouldNotCompute:
2279  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2280  }
2281  return false;
2282  }
2283 
2284  bool isDone() { return Found; }
2285  };
2286 
2287  FindDominatedSCEVUnknown FSU(L, DT, LI);
2289  ST.visitAll(S);
2290  return !FSU.Found;
2291 }
2292 
2293 /// Get a canonical add expression, or something simpler if possible.
2295  SCEV::NoWrapFlags Flags,
2296  unsigned Depth) {
2297  assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2298  "only nuw or nsw allowed");
2299  assert(!Ops.empty() && "Cannot get empty add!");
2300  if (Ops.size() == 1) return Ops[0];
2301 #ifndef NDEBUG
2302  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2303  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2304  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2305  "SCEVAddExpr operand types don't match!");
2306 #endif
2307 
2308  // Sort by complexity, this groups all similar expression types together.
2309  GroupByComplexity(Ops, &LI, DT);
2310 
2311  Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2312 
2313  // If there are any constants, fold them together.
2314  unsigned Idx = 0;
2315  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2316  ++Idx;
2317  assert(Idx < Ops.size());
2318  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2319  // We found two constants, fold them together!
2320  Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2321  if (Ops.size() == 2) return Ops[0];
2322  Ops.erase(Ops.begin()+1); // Erase the folded element
2323  LHSC = cast<SCEVConstant>(Ops[0]);
2324  }
2325 
2326  // If we are left with a constant zero being added, strip it off.
2327  if (LHSC->getValue()->isZero()) {
2328  Ops.erase(Ops.begin());
2329  --Idx;
2330  }
2331 
2332  if (Ops.size() == 1) return Ops[0];
2333  }
2334 
2335  // Limit recursion calls depth.
2336  if (Depth > MaxArithDepth)
2337  return getOrCreateAddExpr(Ops, Flags);
2338 
2339  // Okay, check to see if the same value occurs in the operand list more than
2340  // once. If so, merge them together into an multiply expression. Since we
2341  // sorted the list, these values are required to be adjacent.
2342  Type *Ty = Ops[0]->getType();
2343  bool FoundMatch = false;
2344  for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2345  if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2346  // Scan ahead to count how many equal operands there are.
2347  unsigned Count = 2;
2348  while (i+Count != e && Ops[i+Count] == Ops[i])
2349  ++Count;
2350  // Merge the values into a multiply.
2351  const SCEV *Scale = getConstant(Ty, Count);
2352  const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2353  if (Ops.size() == Count)
2354  return Mul;
2355  Ops[i] = Mul;
2356  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2357  --i; e -= Count - 1;
2358  FoundMatch = true;
2359  }
2360  if (FoundMatch)
2361  return getAddExpr(Ops, Flags, Depth + 1);
2362 
2363  // Check for truncates. If all the operands are truncated from the same
2364  // type, see if factoring out the truncate would permit the result to be
2365  // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2366  // if the contents of the resulting outer trunc fold to something simple.
2367  auto FindTruncSrcType = [&]() -> Type * {
2368  // We're ultimately looking to fold an addrec of truncs and muls of only
2369  // constants and truncs, so if we find any other types of SCEV
2370  // as operands of the addrec then we bail and return nullptr here.
2371  // Otherwise, we return the type of the operand of a trunc that we find.
2372  if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2373  return T->getOperand()->getType();
2374  if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2375  const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2376  if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2377  return T->getOperand()->getType();
2378  }
2379  return nullptr;
2380  };
2381  if (auto *SrcType = FindTruncSrcType()) {
2383  bool Ok = true;
2384  // Check all the operands to see if they can be represented in the
2385  // source type of the truncate.
2386  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2387  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2388  if (T->getOperand()->getType() != SrcType) {
2389  Ok = false;
2390  break;
2391  }
2392  LargeOps.push_back(T->getOperand());
2393  } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2394  LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2395  } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2396  SmallVector<const SCEV *, 8> LargeMulOps;
2397  for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2398  if (const SCEVTruncateExpr *T =
2399  dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2400  if (T->getOperand()->getType() != SrcType) {
2401  Ok = false;
2402  break;
2403  }
2404  LargeMulOps.push_back(T->getOperand());
2405  } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2406  LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2407  } else {
2408  Ok = false;
2409  break;
2410  }
2411  }
2412  if (Ok)
2413  LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2414  } else {
2415  Ok = false;
2416  break;
2417  }
2418  }
2419  if (Ok) {
2420  // Evaluate the expression in the larger type.
2421  const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2422  // If it folds to something simple, use it. Otherwise, don't.
2423  if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2424  return getTruncateExpr(Fold, Ty);
2425  }
2426  }
2427 
2428  // Skip past any other cast SCEVs.
2429  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2430  ++Idx;
2431 
2432  // If there are add operands they would be next.
2433  if (Idx < Ops.size()) {
2434  bool DeletedAdd = false;
2435  while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2436  if (Ops.size() > AddOpsInlineThreshold ||
2437  Add->getNumOperands() > AddOpsInlineThreshold)
2438  break;
2439  // If we have an add, expand the add operands onto the end of the operands
2440  // list.
2441  Ops.erase(Ops.begin()+Idx);
2442  Ops.append(Add->op_begin(), Add->op_end());
2443  DeletedAdd = true;
2444  }
2445 
2446  // If we deleted at least one add, we added operands to the end of the list,
2447  // and they are not necessarily sorted. Recurse to resort and resimplify
2448  // any operands we just acquired.
2449  if (DeletedAdd)
2450  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2451  }
2452 
2453  // Skip over the add expression until we get to a multiply.
2454  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2455  ++Idx;
2456 
2457  // Check to see if there are any folding opportunities present with
2458  // operands multiplied by constant values.
2459  if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2460  uint64_t BitWidth = getTypeSizeInBits(Ty);
2463  APInt AccumulatedConstant(BitWidth, 0);
2464  if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2465  Ops.data(), Ops.size(),
2466  APInt(BitWidth, 1), *this)) {
2467  struct APIntCompare {
2468  bool operator()(const APInt &LHS, const APInt &RHS) const {
2469  return LHS.ult(RHS);
2470  }
2471  };
2472 
2473  // Some interesting folding opportunity is present, so its worthwhile to
2474  // re-generate the operands list. Group the operands by constant scale,
2475  // to avoid multiplying by the same constant scale multiple times.
2476  std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2477  for (const SCEV *NewOp : NewOps)
2478  MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2479  // Re-generate the operands list.
2480  Ops.clear();
2481  if (AccumulatedConstant != 0)
2482  Ops.push_back(getConstant(AccumulatedConstant));
2483  for (auto &MulOp : MulOpLists)
2484  if (MulOp.first != 0)
2485  Ops.push_back(getMulExpr(
2486  getConstant(MulOp.first),
2487  getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2488  SCEV::FlagAnyWrap, Depth + 1));
2489  if (Ops.empty())
2490  return getZero(Ty);
2491  if (Ops.size() == 1)
2492  return Ops[0];
2493  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2494  }
2495  }
2496 
2497  // If we are adding something to a multiply expression, make sure the
2498  // something is not already an operand of the multiply. If so, merge it into
2499  // the multiply.
2500  for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2501  const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2502  for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2503  const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2504  if (isa<SCEVConstant>(MulOpSCEV))
2505  continue;
2506  for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2507  if (MulOpSCEV == Ops[AddOp]) {
2508  // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2509  const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2510  if (Mul->getNumOperands() != 2) {
2511  // If the multiply has more than two operands, we must get the
2512  // Y*Z term.
2513  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2514  Mul->op_begin()+MulOp);
2515  MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2516  InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2517  }
2518  SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2519  const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2520  const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2521  SCEV::FlagAnyWrap, Depth + 1);
2522  if (Ops.size() == 2) return OuterMul;
2523  if (AddOp < Idx) {
2524  Ops.erase(Ops.begin()+AddOp);
2525  Ops.erase(Ops.begin()+Idx-1);
2526  } else {
2527  Ops.erase(Ops.begin()+Idx);
2528  Ops.erase(Ops.begin()+AddOp-1);
2529  }
2530  Ops.push_back(OuterMul);
2531  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2532  }
2533 
2534  // Check this multiply against other multiplies being added together.
2535  for (unsigned OtherMulIdx = Idx+1;
2536  OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2537  ++OtherMulIdx) {
2538  const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2539  // If MulOp occurs in OtherMul, we can fold the two multiplies
2540  // together.
2541  for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2542  OMulOp != e; ++OMulOp)
2543  if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2544  // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2545  const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2546  if (Mul->getNumOperands() != 2) {
2547  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2548  Mul->op_begin()+MulOp);
2549  MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2550  InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2551  }
2552  const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2553  if (OtherMul->getNumOperands() != 2) {
2554  SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2555  OtherMul->op_begin()+OMulOp);
2556  MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2557  InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2558  }
2559  SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2560  const SCEV *InnerMulSum =
2561  getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2562  const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2563  SCEV::FlagAnyWrap, Depth + 1);
2564  if (Ops.size() == 2) return OuterMul;
2565  Ops.erase(Ops.begin()+Idx);
2566  Ops.erase(Ops.begin()+OtherMulIdx-1);
2567  Ops.push_back(OuterMul);
2568  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2569  }
2570  }
2571  }
2572  }
2573 
2574  // If there are any add recurrences in the operands list, see if any other
2575  // added values are loop invariant. If so, we can fold them into the
2576  // recurrence.
2577  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2578  ++Idx;
2579 
2580  // Scan over all recurrences, trying to fold loop invariants into them.
2581  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2582  // Scan all of the other operands to this add and add them to the vector if
2583  // they are loop invariant w.r.t. the recurrence.
2585  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2586  const Loop *AddRecLoop = AddRec->getLoop();
2587  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2588  if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2589  LIOps.push_back(Ops[i]);
2590  Ops.erase(Ops.begin()+i);
2591  --i; --e;
2592  }
2593 
2594  // If we found some loop invariants, fold them into the recurrence.
2595  if (!LIOps.empty()) {
2596  // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2597  LIOps.push_back(AddRec->getStart());
2598 
2599  SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2600  AddRec->op_end());
2601  // This follows from the fact that the no-wrap flags on the outer add
2602  // expression are applicable on the 0th iteration, when the add recurrence
2603  // will be equal to its start value.
2604  AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2605 
2606  // Build the new addrec. Propagate the NUW and NSW flags if both the
2607  // outer add and the inner addrec are guaranteed to have no overflow.
2608  // Always propagate NW.
2609  Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2610  const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2611 
2612  // If all of the other operands were loop invariant, we are done.
2613  if (Ops.size() == 1) return NewRec;
2614 
2615  // Otherwise, add the folded AddRec by the non-invariant parts.
2616  for (unsigned i = 0;; ++i)
2617  if (Ops[i] == AddRec) {
2618  Ops[i] = NewRec;
2619  break;
2620  }
2621  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2622  }
2623 
2624  // Okay, if there weren't any loop invariants to be folded, check to see if
2625  // there are multiple AddRec's with the same loop induction variable being
2626  // added together. If so, we can fold them.
2627  for (unsigned OtherIdx = Idx+1;
2628  OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2629  ++OtherIdx) {
2630  // We expect the AddRecExpr's to be sorted in reverse dominance order,
2631  // so that the 1st found AddRecExpr is dominated by all others.
2632  assert(DT.dominates(
2633  cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2634  AddRec->getLoop()->getHeader()) &&
2635  "AddRecExprs are not sorted in reverse dominance order?");
2636  if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2637  // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2638  SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2639  AddRec->op_end());
2640  for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2641  ++OtherIdx) {
2642  const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2643  if (OtherAddRec->getLoop() == AddRecLoop) {
2644  for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2645  i != e; ++i) {
2646  if (i >= AddRecOps.size()) {
2647  AddRecOps.append(OtherAddRec->op_begin()+i,
2648  OtherAddRec->op_end());
2649  break;
2650  }
2651  SmallVector<const SCEV *, 2> TwoOps = {
2652  AddRecOps[i], OtherAddRec->getOperand(i)};
2653  AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2654  }
2655  Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2656  }
2657  }
2658  // Step size has changed, so we cannot guarantee no self-wraparound.
2659  Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2660  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2661  }
2662  }
2663 
2664  // Otherwise couldn't fold anything into this recurrence. Move onto the
2665  // next one.
2666  }
2667 
2668  // Okay, it looks like we really DO need an add expr. Check to see if we
2669  // already have one, otherwise create a new one.
2670  return getOrCreateAddExpr(Ops, Flags);
2671 }
2672 
2673 const SCEV *
2674 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2675  SCEV::NoWrapFlags Flags) {
2677  ID.AddInteger(scAddExpr);
2678  for (const SCEV *Op : Ops)
2679  ID.AddPointer(Op);
2680  void *IP = nullptr;
2681  SCEVAddExpr *S =
2682  static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2683  if (!S) {
2684  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2685  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2686  S = new (SCEVAllocator)
2687  SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2688  UniqueSCEVs.InsertNode(S, IP);
2689  addToLoopUseLists(S);
2690  }
2691  S->setNoWrapFlags(Flags);
2692  return S;
2693 }
2694 
2695 const SCEV *
2696 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2697  SCEV::NoWrapFlags Flags) {
2699  ID.AddInteger(scMulExpr);
2700  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2701  ID.AddPointer(Ops[i]);
2702  void *IP = nullptr;
2703  SCEVMulExpr *S =
2704  static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2705  if (!S) {
2706  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2707  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2708  S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2709  O, Ops.size());
2710  UniqueSCEVs.InsertNode(S, IP);
2711  addToLoopUseLists(S);
2712  }
2713  S->setNoWrapFlags(Flags);
2714  return S;
2715 }
2716 
2717 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2718  uint64_t k = i*j;
2719  if (j > 1 && k / j != i) Overflow = true;
2720  return k;
2721 }
2722 
2723 /// Compute the result of "n choose k", the binomial coefficient. If an
2724 /// intermediate computation overflows, Overflow will be set and the return will
2725 /// be garbage. Overflow is not cleared on absence of overflow.
2726 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2727  // We use the multiplicative formula:
2728  // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2729  // At each iteration, we take the n-th term of the numeral and divide by the
2730  // (k-n)th term of the denominator. This division will always produce an
2731  // integral result, and helps reduce the chance of overflow in the
2732  // intermediate computations. However, we can still overflow even when the
2733  // final result would fit.
2734 
2735  if (n == 0 || n == k) return 1;
2736  if (k > n) return 0;
2737 
2738  if (k > n/2)
2739  k = n-k;
2740 
2741  uint64_t r = 1;
2742  for (uint64_t i = 1; i <= k; ++i) {
2743  r = umul_ov(r, n-(i-1), Overflow);
2744  r /= i;
2745  }
2746  return r;
2747 }
2748 
2749 /// Determine if any of the operands in this SCEV are a constant or if
2750 /// any of the add or multiply expressions in this SCEV contain a constant.
2751 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2752  struct FindConstantInAddMulChain {
2753  bool FoundConstant = false;
2754 
2755  bool follow(const SCEV *S) {
2756  FoundConstant |= isa<SCEVConstant>(S);
2757  return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2758  }
2759 
2760  bool isDone() const {
2761  return FoundConstant;
2762  }
2763  };
2764 
2765  FindConstantInAddMulChain F;
2767  ST.visitAll(StartExpr);
2768  return F.FoundConstant;
2769 }
2770 
2771 /// Get a canonical multiply expression, or something simpler if possible.
2773  SCEV::NoWrapFlags Flags,
2774  unsigned Depth) {
2775  assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2776  "only nuw or nsw allowed");
2777  assert(!Ops.empty() && "Cannot get empty mul!");
2778  if (Ops.size() == 1) return Ops[0];
2779 #ifndef NDEBUG
2780  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2781  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2782  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2783  "SCEVMulExpr operand types don't match!");
2784 #endif
2785 
2786  // Sort by complexity, this groups all similar expression types together.
2787  GroupByComplexity(Ops, &LI, DT);
2788 
2789  Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2790 
2791  // Limit recursion calls depth.
2792  if (Depth > MaxArithDepth)
2793  return getOrCreateMulExpr(Ops, Flags);
2794 
2795  // If there are any constants, fold them together.
2796  unsigned Idx = 0;
2797  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2798 
2799  // C1*(C2+V) -> C1*C2 + C1*V
2800  if (Ops.size() == 2)
2801  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2802  // If any of Add's ops are Adds or Muls with a constant,
2803  // apply this transformation as well.
2804  if (Add->getNumOperands() == 2)
2805  // TODO: There are some cases where this transformation is not
2806  // profitable, for example:
2807  // Add = (C0 + X) * Y + Z.
2808  // Maybe the scope of this transformation should be narrowed down.
2810  return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2811  SCEV::FlagAnyWrap, Depth + 1),
2812  getMulExpr(LHSC, Add->getOperand(1),
2813  SCEV::FlagAnyWrap, Depth + 1),
2814  SCEV::FlagAnyWrap, Depth + 1);
2815 
2816  ++Idx;
2817  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2818  // We found two constants, fold them together!
2819  ConstantInt *Fold =
2820  ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2821  Ops[0] = getConstant(Fold);
2822  Ops.erase(Ops.begin()+1); // Erase the folded element
2823  if (Ops.size() == 1) return Ops[0];
2824  LHSC = cast<SCEVConstant>(Ops[0]);
2825  }
2826 
2827  // If we are left with a constant one being multiplied, strip it off.
2828  if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2829  Ops.erase(Ops.begin());
2830  --Idx;
2831  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2832  // If we have a multiply of zero, it will always be zero.
2833  return Ops[0];
2834  } else if (Ops[0]->isAllOnesValue()) {
2835  // If we have a mul by -1 of an add, try distributing the -1 among the
2836  // add operands.
2837  if (Ops.size() == 2) {
2838  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2840  bool AnyFolded = false;
2841  for (const SCEV *AddOp : Add->operands()) {
2842  const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2843  Depth + 1);
2844  if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2845  NewOps.push_back(Mul);
2846  }
2847  if (AnyFolded)
2848  return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2849  } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2850  // Negation preserves a recurrence's no self-wrap property.
2852  for (const SCEV *AddRecOp : AddRec->operands())
2853  Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2854  Depth + 1));
2855 
2856  return getAddRecExpr(Operands, AddRec->getLoop(),
2857  AddRec->getNoWrapFlags(SCEV::FlagNW));
2858  }
2859  }
2860  }
2861 
2862  if (Ops.size() == 1)
2863  return Ops[0];
2864  }
2865 
2866  // Skip over the add expression until we get to a multiply.
2867  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2868  ++Idx;
2869 
2870  // If there are mul operands inline them all into this expression.
2871  if (Idx < Ops.size()) {
2872  bool DeletedMul = false;
2873  while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2874  if (Ops.size() > MulOpsInlineThreshold)
2875  break;
2876  // If we have an mul, expand the mul operands onto the end of the
2877  // operands list.
2878  Ops.erase(Ops.begin()+Idx);
2879  Ops.append(Mul->op_begin(), Mul->op_end());
2880  DeletedMul = true;
2881  }
2882 
2883  // If we deleted at least one mul, we added operands to the end of the
2884  // list, and they are not necessarily sorted. Recurse to resort and
2885  // resimplify any operands we just acquired.
2886  if (DeletedMul)
2887  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2888  }
2889 
2890  // If there are any add recurrences in the operands list, see if any other
2891  // added values are loop invariant. If so, we can fold them into the
2892  // recurrence.
2893  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2894  ++Idx;
2895 
2896  // Scan over all recurrences, trying to fold loop invariants into them.
2897  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2898  // Scan all of the other operands to this mul and add them to the vector
2899  // if they are loop invariant w.r.t. the recurrence.
2901  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2902  const Loop *AddRecLoop = AddRec->getLoop();
2903  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2904  if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2905  LIOps.push_back(Ops[i]);
2906  Ops.erase(Ops.begin()+i);
2907  --i; --e;
2908  }
2909 
2910  // If we found some loop invariants, fold them into the recurrence.
2911  if (!LIOps.empty()) {
2912  // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2914  NewOps.reserve(AddRec->getNumOperands());
2915  const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2916  for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2917  NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2918  SCEV::FlagAnyWrap, Depth + 1));
2919 
2920  // Build the new addrec. Propagate the NUW and NSW flags if both the
2921  // outer mul and the inner addrec are guaranteed to have no overflow.
2922  //
2923  // No self-wrap cannot be guaranteed after changing the step size, but
2924  // will be inferred if either NUW or NSW is true.
2925  Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2926  const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2927 
2928  // If all of the other operands were loop invariant, we are done.
2929  if (Ops.size() == 1) return NewRec;
2930 
2931  // Otherwise, multiply the folded AddRec by the non-invariant parts.
2932  for (unsigned i = 0;; ++i)
2933  if (Ops[i] == AddRec) {
2934  Ops[i] = NewRec;
2935  break;
2936  }
2937  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2938  }
2939 
2940  // Okay, if there weren't any loop invariants to be folded, check to see
2941  // if there are multiple AddRec's with the same loop induction variable
2942  // being multiplied together. If so, we can fold them.
2943 
2944  // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2945  // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2946  // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2947  // ]]],+,...up to x=2n}.
2948  // Note that the arguments to choose() are always integers with values
2949  // known at compile time, never SCEV objects.
2950  //
2951  // The implementation avoids pointless extra computations when the two
2952  // addrec's are of different length (mathematically, it's equivalent to
2953  // an infinite stream of zeros on the right).
2954  bool OpsModified = false;
2955  for (unsigned OtherIdx = Idx+1;
2956  OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2957  ++OtherIdx) {
2958  const SCEVAddRecExpr *OtherAddRec =
2959  dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2960  if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2961  continue;
2962 
2963  // Limit max number of arguments to avoid creation of unreasonably big
2964  // SCEVAddRecs with very complex operands.
2965  if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2966  MaxAddRecSize)
2967  continue;
2968 
2969  bool Overflow = false;
2970  Type *Ty = AddRec->getType();
2971  bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2972  SmallVector<const SCEV*, 7> AddRecOps;
2973  for (int x = 0, xe = AddRec->getNumOperands() +
2974  OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2975  const SCEV *Term = getZero(Ty);
2976  for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2977  uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2978  for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2979  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2980  z < ze && !Overflow; ++z) {
2981  uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2982  uint64_t Coeff;
2983  if (LargerThan64Bits)
2984  Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2985  else
2986  Coeff = Coeff1*Coeff2;
2987  const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2988  const SCEV *Term1 = AddRec->getOperand(y-z);
2989  const SCEV *Term2 = OtherAddRec->getOperand(z);
2990  Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2991  SCEV::FlagAnyWrap, Depth + 1),
2992  SCEV::FlagAnyWrap, Depth + 1);
2993  }
2994  }
2995  AddRecOps.push_back(Term);
2996  }
2997  if (!Overflow) {
2998  const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3000  if (Ops.size() == 2) return NewAddRec;
3001  Ops[Idx] = NewAddRec;
3002  Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3003  OpsModified = true;
3004  AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3005  if (!AddRec)
3006  break;
3007  }
3008  }
3009  if (OpsModified)
3010  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3011 
3012  // Otherwise couldn't fold anything into this recurrence. Move onto the
3013  // next one.
3014  }
3015 
3016  // Okay, it looks like we really DO need an mul expr. Check to see if we
3017  // already have one, otherwise create a new one.
3018  return getOrCreateMulExpr(Ops, Flags);
3019 }
3020 
3021 /// Represents an unsigned remainder expression based on unsigned division.
3023  const SCEV *RHS) {
3024  assert(getEffectiveSCEVType(LHS->getType()) ==
3025  getEffectiveSCEVType(RHS->getType()) &&
3026  "SCEVURemExpr operand types don't match!");
3027 
3028  // Short-circuit easy cases
3029  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3030  // If constant is one, the result is trivial
3031  if (RHSC->getValue()->isOne())
3032  return getZero(LHS->getType()); // X urem 1 --> 0
3033 
3034  // If constant is a power of two, fold into a zext(trunc(LHS)).
3035  if (RHSC->getAPInt().isPowerOf2()) {
3036  Type *FullTy = LHS->getType();
3037  Type *TruncTy =
3038  IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3039  return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3040  }
3041  }
3042 
3043  // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3044  const SCEV *UDiv = getUDivExpr(LHS, RHS);
3045  const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3046  return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3047 }
3048 
3049 /// Get a canonical unsigned division expression, or something simpler if
3050 /// possible.
3052  const SCEV *RHS) {
3053  assert(getEffectiveSCEVType(LHS->getType()) ==
3054  getEffectiveSCEVType(RHS->getType()) &&
3055  "SCEVUDivExpr operand types don't match!");
3056 
3057  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3058  if (RHSC->getValue()->isOne())
3059  return LHS; // X udiv 1 --> x
3060  // If the denominator is zero, the result of the udiv is undefined. Don't
3061  // try to analyze it, because the resolution chosen here may differ from
3062  // the resolution chosen in other parts of the compiler.
3063  if (!RHSC->getValue()->isZero()) {
3064  // Determine if the division can be folded into the operands of
3065  // its operands.
3066  // TODO: Generalize this to non-constants by using known-bits information.
3067  Type *Ty = LHS->getType();
3068  unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3069  unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3070  // For non-power-of-two values, effectively round the value up to the
3071  // nearest power of two.
3072  if (!RHSC->getAPInt().isPowerOf2())
3073  ++MaxShiftAmt;
3074  IntegerType *ExtTy =
3075  IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3076  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3077  if (const SCEVConstant *Step =
3078  dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3079  // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3080  const APInt &StepInt = Step->getAPInt();
3081  const APInt &DivInt = RHSC->getAPInt();
3082  if (!StepInt.urem(DivInt) &&
3083  getZeroExtendExpr(AR, ExtTy) ==
3084  getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3085  getZeroExtendExpr(Step, ExtTy),
3086  AR->getLoop(), SCEV::FlagAnyWrap)) {
3088  for (const SCEV *Op : AR->operands())
3089  Operands.push_back(getUDivExpr(Op, RHS));
3090  return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3091  }
3092  /// Get a canonical UDivExpr for a recurrence.
3093  /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3094  // We can currently only fold X%N if X is constant.
3095  const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3096  if (StartC && !DivInt.urem(StepInt) &&
3097  getZeroExtendExpr(AR, ExtTy) ==
3098  getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3099  getZeroExtendExpr(Step, ExtTy),
3100  AR->getLoop(), SCEV::FlagAnyWrap)) {
3101  const APInt &StartInt = StartC->getAPInt();
3102  const APInt &StartRem = StartInt.urem(StepInt);
3103  if (StartRem != 0)
3104  LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3105  AR->getLoop(), SCEV::FlagNW);
3106  }
3107  }
3108  // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3109  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3111  for (const SCEV *Op : M->operands())
3112  Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3113  if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3114  // Find an operand that's safely divisible.
3115  for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3116  const SCEV *Op = M->getOperand(i);
3117  const SCEV *Div = getUDivExpr(Op, RHSC);
3118  if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3119  Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3120  M->op_end());
3121  Operands[i] = Div;
3122  return getMulExpr(Operands);
3123  }
3124  }
3125  }
3126  // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3127  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3129  for (const SCEV *Op : A->operands())
3130  Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3131  if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3132  Operands.clear();
3133  for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3134  const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3135  if (isa<SCEVUDivExpr>(Op) ||
3136  getMulExpr(Op, RHS) != A->getOperand(i))
3137  break;
3138  Operands.push_back(Op);
3139  }
3140  if (Operands.size() == A->getNumOperands())
3141  return getAddExpr(Operands);
3142  }
3143  }
3144 
3145  // Fold if both operands are constant.
3146  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3147  Constant *LHSCV = LHSC->getValue();
3148  Constant *RHSCV = RHSC->getValue();
3149  return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3150  RHSCV)));
3151  }
3152  }
3153  }
3154 
3156  ID.AddInteger(scUDivExpr);
3157  ID.AddPointer(LHS);
3158  ID.AddPointer(RHS);
3159  void *IP = nullptr;
3160  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3161  SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3162  LHS, RHS);
3163  UniqueSCEVs.InsertNode(S, IP);
3164  addToLoopUseLists(S);
3165  return S;
3166 }
3167 
3168 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3169  APInt A = C1->getAPInt().abs();
3170  APInt B = C2->getAPInt().abs();
3171  uint32_t ABW = A.getBitWidth();
3172  uint32_t BBW = B.getBitWidth();
3173 
3174  if (ABW > BBW)
3175  B = B.zext(ABW);
3176  else if (ABW < BBW)
3177  A = A.zext(BBW);
3178 
3179  return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3180 }
3181 
3182 /// Get a canonical unsigned division expression, or something simpler if
3183 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3184 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3185 /// it's not exact because the udiv may be clearing bits.
3187  const SCEV *RHS) {
3188  // TODO: we could try to find factors in all sorts of things, but for now we
3189  // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3190  // end of this file for inspiration.
3191 
3192  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3193  if (!Mul || !Mul->hasNoUnsignedWrap())
3194  return getUDivExpr(LHS, RHS);
3195 
3196  if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3197  // If the mulexpr multiplies by a constant, then that constant must be the
3198  // first element of the mulexpr.
3199  if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3200  if (LHSCst == RHSCst) {
3202  Operands.append(Mul->op_begin() + 1, Mul->op_end());
3203  return getMulExpr(Operands);
3204  }
3205 
3206  // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3207  // that there's a factor provided by one of the other terms. We need to
3208  // check.
3209  APInt Factor = gcd(LHSCst, RHSCst);
3210  if (!Factor.isIntN(1)) {
3211  LHSCst =
3212  cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3213  RHSCst =
3214  cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3216  Operands.push_back(LHSCst);
3217  Operands.append(Mul->op_begin() + 1, Mul->op_end());
3218  LHS = getMulExpr(Operands);
3219  RHS = RHSCst;
3220  Mul = dyn_cast<SCEVMulExpr>(LHS);
3221  if (!Mul)
3222  return getUDivExactExpr(LHS, RHS);
3223  }
3224  }
3225  }
3226 
3227  for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3228  if (Mul->getOperand(i) == RHS) {
3230  Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3231  Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3232  return getMulExpr(Operands);
3233  }
3234  }
3235 
3236  return getUDivExpr(LHS, RHS);
3237 }
3238 
3239 /// Get an add recurrence expression for the specified loop. Simplify the
3240 /// expression as much as possible.
3241 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3242  const Loop *L,
3243  SCEV::NoWrapFlags Flags) {
3245  Operands.push_back(Start);
3246  if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3247  if (StepChrec->getLoop() == L) {
3248  Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3249  return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3250  }
3251 
3252  Operands.push_back(Step);
3253  return getAddRecExpr(Operands, L, Flags);
3254 }
3255 
3256 /// Get an add recurrence expression for the specified loop. Simplify the
3257 /// expression as much as possible.
3258 const SCEV *
3260  const Loop *L, SCEV::NoWrapFlags Flags) {
3261  if (Operands.size() == 1) return Operands[0];
3262 #ifndef NDEBUG
3263  Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3264  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3265  assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3266  "SCEVAddRecExpr operand types don't match!");
3267  for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3268  assert(isLoopInvariant(Operands[i], L) &&
3269  "SCEVAddRecExpr operand is not loop-invariant!");
3270 #endif
3271 
3272  if (Operands.back()->isZero()) {
3273  Operands.pop_back();
3274  return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3275  }
3276 
3277  // It's tempting to want to call getMaxBackedgeTakenCount count here and
3278  // use that information to infer NUW and NSW flags. However, computing a
3279  // BE count requires calling getAddRecExpr, so we may not yet have a
3280  // meaningful BE count at this point (and if we don't, we'd be stuck
3281  // with a SCEVCouldNotCompute as the cached BE count).
3282 
3283  Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3284 
3285  // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3286  if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3287  const Loop *NestedLoop = NestedAR->getLoop();
3288  if (L->contains(NestedLoop)
3289  ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3290  : (!NestedLoop->contains(L) &&
3291  DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3292  SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3293  NestedAR->op_end());
3294  Operands[0] = NestedAR->getStart();
3295  // AddRecs require their operands be loop-invariant with respect to their
3296  // loops. Don't perform this transformation if it would break this
3297  // requirement.
3298  bool AllInvariant = all_of(
3299  Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3300 
3301  if (AllInvariant) {
3302  // Create a recurrence for the outer loop with the same step size.
3303  //
3304  // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3305  // inner recurrence has the same property.
3306  SCEV::NoWrapFlags OuterFlags =
3307  maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3308 
3309  NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3310  AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3311  return isLoopInvariant(Op, NestedLoop);
3312  });
3313 
3314  if (AllInvariant) {
3315  // Ok, both add recurrences are valid after the transformation.
3316  //
3317  // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3318  // the outer recurrence has the same property.
3319  SCEV::NoWrapFlags InnerFlags =
3320  maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3321  return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3322  }
3323  }
3324  // Reset Operands to its original state.
3325  Operands[0] = NestedAR;
3326  }
3327  }
3328 
3329  // Okay, it looks like we really DO need an addrec expr. Check to see if we
3330  // already have one, otherwise create a new one.
3333  for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3334  ID.AddPointer(Operands[i]);
3335  ID.AddPointer(L);
3336  void *IP = nullptr;
3337  SCEVAddRecExpr *S =
3338  static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3339  if (!S) {
3340  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3341  std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3342  S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3343  O, Operands.size(), L);
3344  UniqueSCEVs.InsertNode(S, IP);
3345  addToLoopUseLists(S);
3346  }
3347  S->setNoWrapFlags(Flags);
3348  return S;
3349 }
3350 
3351 const SCEV *
3353  const SmallVectorImpl<const SCEV *> &IndexExprs) {
3354  const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3355  // getSCEV(Base)->getType() has the same address space as Base->getType()
3356  // because SCEV::getType() preserves the address space.
3357  Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3358  // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3359  // instruction to its SCEV, because the Instruction may be guarded by control
3360  // flow and the no-overflow bits may not be valid for the expression in any
3361  // context. This can be fixed similarly to how these flags are handled for
3362  // adds.
3365 
3366  const SCEV *TotalOffset = getZero(IntPtrTy);
3367  // The array size is unimportant. The first thing we do on CurTy is getting
3368  // its element type.
3369  Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3370  for (const SCEV *IndexExpr : IndexExprs) {
3371  // Compute the (potentially symbolic) offset in bytes for this index.
3372  if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3373  // For a struct, add the member offset.
3374  ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3375  unsigned FieldNo = Index->getZExtValue();
3376  const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3377 
3378  // Add the field offset to the running total offset.
3379  TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3380 
3381  // Update CurTy to the type of the field at Index.
3382  CurTy = STy->getTypeAtIndex(Index);
3383  } else {
3384  // Update CurTy to its element type.
3385  CurTy = cast<SequentialType>(CurTy)->getElementType();
3386  // For an array, add the element offset, explicitly scaled.
3387  const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3388  // Getelementptr indices are signed.
3389  IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3390 
3391  // Multiply the index by the element size to compute the element offset.
3392  const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3393 
3394  // Add the element offset to the running total offset.
3395  TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3396  }
3397  }
3398 
3399  // Add the total offset from all the GEP indices to the base.
3400  return getAddExpr(BaseExpr, TotalOffset, Wrap);
3401 }
3402 
3404  const SCEV *RHS) {
3405  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3406  return getSMaxExpr(Ops);
3407 }
3408 
3409 const SCEV *
3411  assert(!Ops.empty() && "Cannot get empty smax!");
3412  if (Ops.size() == 1) return Ops[0];
3413 #ifndef NDEBUG
3414  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3415  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3416  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3417  "SCEVSMaxExpr operand types don't match!");
3418 #endif
3419 
3420  // Sort by complexity, this groups all similar expression types together.
3421  GroupByComplexity(Ops, &LI, DT);
3422 
3423  // If there are any constants, fold them together.
3424  unsigned Idx = 0;
3425  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3426  ++Idx;
3427  assert(Idx < Ops.size());
3428  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3429  // We found two constants, fold them together!
3430  ConstantInt *Fold = ConstantInt::get(
3431  getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3432  Ops[0] = getConstant(Fold);
3433  Ops.erase(Ops.begin()+1); // Erase the folded element
3434  if (Ops.size() == 1) return Ops[0];
3435  LHSC = cast<SCEVConstant>(Ops[0]);
3436  }
3437 
3438  // If we are left with a constant minimum-int, strip it off.
3439  if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3440  Ops.erase(Ops.begin());
3441  --Idx;
3442  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3443  // If we have an smax with a constant maximum-int, it will always be
3444  // maximum-int.
3445  return Ops[0];
3446  }
3447 
3448  if (Ops.size() == 1) return Ops[0];
3449  }
3450 
3451  // Find the first SMax
3452  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3453  ++Idx;
3454 
3455  // Check to see if one of the operands is an SMax. If so, expand its operands
3456  // onto our operand list, and recurse to simplify.
3457  if (Idx < Ops.size()) {
3458  bool DeletedSMax = false;
3459  while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3460  Ops.erase(Ops.begin()+Idx);
3461  Ops.append(SMax->op_begin(), SMax->op_end());
3462  DeletedSMax = true;
3463  }
3464 
3465  if (DeletedSMax)
3466  return getSMaxExpr(Ops);
3467  }
3468 
3469  // Okay, check to see if the same value occurs in the operand list twice. If
3470  // so, delete one. Since we sorted the list, these values are required to
3471  // be adjacent.
3472  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3473  // X smax Y smax Y --> X smax Y
3474  // X smax Y --> X, if X is always greater than Y
3475  if (Ops[i] == Ops[i+1] ||
3476  isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3477  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3478  --i; --e;
3479  } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3480  Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3481  --i; --e;
3482  }
3483 
3484  if (Ops.size() == 1) return Ops[0];
3485 
3486  assert(!Ops.empty() && "Reduced smax down to nothing!");
3487 
3488  // Okay, it looks like we really DO need an smax expr. Check to see if we
3489  // already have one, otherwise create a new one.
3491  ID.AddInteger(scSMaxExpr);
3492  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3493  ID.AddPointer(Ops[i]);
3494  void *IP = nullptr;
3495  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3496  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3497  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3498  SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3499  O, Ops.size());
3500  UniqueSCEVs.InsertNode(S, IP);
3501  addToLoopUseLists(S);
3502  return S;
3503 }
3504 
3506  const SCEV *RHS) {
3507  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3508  return getUMaxExpr(Ops);
3509 }
3510 
3511 const SCEV *
3513  assert(!Ops.empty() && "Cannot get empty umax!");
3514  if (Ops.size() == 1) return Ops[0];
3515 #ifndef NDEBUG
3516  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3517  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3518  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3519  "SCEVUMaxExpr operand types don't match!");
3520 #endif
3521 
3522  // Sort by complexity, this groups all similar expression types together.
3523  GroupByComplexity(Ops, &LI, DT);
3524 
3525  // If there are any constants, fold them together.
3526  unsigned Idx = 0;
3527  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3528  ++Idx;
3529  assert(Idx < Ops.size());
3530  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3531  // We found two constants, fold them together!
3532  ConstantInt *Fold = ConstantInt::get(
3533  getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3534  Ops[0] = getConstant(Fold);
3535  Ops.erase(Ops.begin()+1); // Erase the folded element
3536  if (Ops.size() == 1) return Ops[0];
3537  LHSC = cast<SCEVConstant>(Ops[0]);
3538  }
3539 
3540  // If we are left with a constant minimum-int, strip it off.
3541  if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3542  Ops.erase(Ops.begin());
3543  --Idx;
3544  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3545  // If we have an umax with a constant maximum-int, it will always be
3546  // maximum-int.
3547  return Ops[0];
3548  }
3549 
3550  if (Ops.size() == 1) return Ops[0];
3551  }
3552 
3553  // Find the first UMax
3554  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3555  ++Idx;
3556 
3557  // Check to see if one of the operands is a UMax. If so, expand its operands
3558  // onto our operand list, and recurse to simplify.
3559  if (Idx < Ops.size()) {
3560  bool DeletedUMax = false;
3561  while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3562  Ops.erase(Ops.begin()+Idx);
3563  Ops.append(UMax->op_begin(), UMax->op_end());
3564  DeletedUMax = true;
3565  }
3566 
3567  if (DeletedUMax)
3568  return getUMaxExpr(Ops);
3569  }
3570 
3571  // Okay, check to see if the same value occurs in the operand list twice. If
3572  // so, delete one. Since we sorted the list, these values are required to
3573  // be adjacent.
3574  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3575  // X umax Y umax Y --> X umax Y
3576  // X umax Y --> X, if X is always greater than Y
3577  if (Ops[i] == Ops[i+1] ||
3578  isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3579  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3580  --i; --e;
3581  } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3582  Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3583  --i; --e;
3584  }
3585 
3586  if (Ops.size() == 1) return Ops[0];
3587 
3588  assert(!Ops.empty() && "Reduced umax down to nothing!");
3589 
3590  // Okay, it looks like we really DO need a umax expr. Check to see if we
3591  // already have one, otherwise create a new one.
3593  ID.AddInteger(scUMaxExpr);
3594  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3595  ID.AddPointer(Ops[i]);
3596  void *IP = nullptr;
3597  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3598  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3599  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3600  SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3601  O, Ops.size());
3602  UniqueSCEVs.InsertNode(S, IP);
3603  addToLoopUseLists(S);
3604  return S;
3605 }
3606 
3608  const SCEV *RHS) {
3609  // ~smax(~x, ~y) == smin(x, y).
3610  return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3611 }
3612 
3614  const SCEV *RHS) {
3615  // ~umax(~x, ~y) == umin(x, y)
3616  return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3617 }
3618 
3619 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3620  // We can bypass creating a target-independent
3621  // constant expression and then folding it back into a ConstantInt.
3622  // This is just a compile-time optimization.
3623  return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3624 }
3625 
3627  StructType *STy,
3628  unsigned FieldNo) {
3629  // We can bypass creating a target-independent
3630  // constant expression and then folding it back into a ConstantInt.
3631  // This is just a compile-time optimization.
3632  return getConstant(
3633  IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3634 }
3635 
3637  // Don't attempt to do anything other than create a SCEVUnknown object
3638  // here. createSCEV only calls getUnknown after checking for all other
3639  // interesting possibilities, and any other code that calls getUnknown
3640  // is doing so in order to hide a value from SCEV canonicalization.
3641 
3643  ID.AddInteger(scUnknown);
3644  ID.AddPointer(V);
3645  void *IP = nullptr;
3646  if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3647  assert(cast<SCEVUnknown>(S)->getValue() == V &&
3648  "Stale SCEVUnknown in uniquing map!");
3649  return S;
3650  }
3651  SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3652  FirstUnknown);
3653  FirstUnknown = cast<SCEVUnknown>(S);
3654  UniqueSCEVs.InsertNode(S, IP);
3655  return S;
3656 }
3657 
3658 //===----------------------------------------------------------------------===//
3659 // Basic SCEV Analysis and PHI Idiom Recognition Code
3660 //
3661 
3662 /// Test if values of the given type are analyzable within the SCEV
3663 /// framework. This primarily includes integer types, and it can optionally
3664 /// include pointer types if the ScalarEvolution class has access to
3665 /// target-specific information.
3667  // Integers and pointers are always SCEVable.
3668  return Ty->isIntegerTy() || Ty->isPointerTy();
3669 }
3670 
3671 /// Return the size in bits of the specified type, for which isSCEVable must
3672 /// return true.
3674  assert(isSCEVable(Ty) && "Type is not SCEVable!");
3675  return getDataLayout().getTypeSizeInBits(Ty);
3676 }
3677 
3678 /// Return a type with the same bitwidth as the given type and which represents
3679 /// how SCEV will treat the given type, for which isSCEVable must return
3680 /// true. For pointer types, this is the pointer-sized integer type.
3682  assert(isSCEVable(Ty) && "Type is not SCEVable!");
3683 
3684  if (Ty->isIntegerTy())
3685  return Ty;
3686 
3687  // The only other support type is pointer.
3688  assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3689  return getDataLayout().getIntPtrType(Ty);
3690 }
3691 
3693  return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3694 }
3695 
3697  return CouldNotCompute.get();
3698 }
3699 
3700 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3701  bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3702  auto *SU = dyn_cast<SCEVUnknown>(S);
3703  return SU && SU->getValue() == nullptr;
3704  });
3705 
3706  return !ContainsNulls;
3707 }
3708 
3710  HasRecMapType::iterator I = HasRecMap.find(S);
3711  if (I != HasRecMap.end())
3712  return I->second;
3713 
3714  bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3715  HasRecMap.insert({S, FoundAddRec});
3716  return FoundAddRec;
3717 }
3718 
3719 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3720 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3721 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3722 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3723  const auto *Add = dyn_cast<SCEVAddExpr>(S);
3724  if (!Add)
3725  return {S, nullptr};
3726 
3727  if (Add->getNumOperands() != 2)
3728  return {S, nullptr};
3729 
3730  auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3731  if (!ConstOp)
3732  return {S, nullptr};
3733 
3734  return {Add->getOperand(1), ConstOp->getValue()};
3735 }
3736 
3737 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3738 /// by the value and offset from any ValueOffsetPair in the set.
3740 ScalarEvolution::getSCEVValues(const SCEV *S) {
3741  ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3742  if (SI == ExprValueMap.end())
3743  return nullptr;
3744 #ifndef NDEBUG
3745  if (VerifySCEVMap) {
3746  // Check there is no dangling Value in the set returned.
3747  for (const auto &VE : SI->second)
3748  assert(ValueExprMap.count(VE.first));
3749  }
3750 #endif
3751  return &SI->second;
3752 }
3753 
3754 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3755 /// cannot be used separately. eraseValueFromMap should be used to remove
3756 /// V from ValueExprMap and ExprValueMap at the same time.
3758  ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3759  if (I != ValueExprMap.end()) {
3760  const SCEV *S = I->second;
3761  // Remove {V, 0} from the set of ExprValueMap[S]
3762  if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3763  SV->remove({V, nullptr});
3764 
3765  // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3766  const SCEV *Stripped;
3768  std::tie(Stripped, Offset) = splitAddExpr(S);
3769  if (Offset != nullptr) {
3770  if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3771  SV->remove({V, Offset});
3772  }
3773  ValueExprMap.erase(V);
3774  }
3775 }
3776 
3777 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3778 /// TODO: In reality it is better to check the poison recursevely
3779 /// but this is better than nothing.
3780 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3781  if (auto *I = dyn_cast<Instruction>(V)) {
3782  if (isa<OverflowingBinaryOperator>(I)) {
3783  if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3784  if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3785  return true;
3786  if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3787  return true;
3788  }
3789  } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3790  return true;
3791  }
3792  return false;
3793 }
3794 
3795 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3796 /// create a new one.
3798  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3799 
3800  const SCEV *S = getExistingSCEV(V);
3801  if (S == nullptr) {
3802  S = createSCEV(V);
3803  // During PHI resolution, it is possible to create two SCEVs for the same
3804  // V, so it is needed to double check whether V->S is inserted into
3805  // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3806  std::pair<ValueExprMapType::iterator, bool> Pair =
3807  ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3808  if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3809  ExprValueMap[S].insert({V, nullptr});
3810 
3811  // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3812  // ExprValueMap.
3813  const SCEV *Stripped = S;
3814  ConstantInt *Offset = nullptr;
3815  std::tie(Stripped, Offset) = splitAddExpr(S);
3816  // If stripped is SCEVUnknown, don't bother to save
3817  // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3818  // increase the complexity of the expansion code.
3819  // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3820  // because it may generate add/sub instead of GEP in SCEV expansion.
3821  if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3822  !isa<GetElementPtrInst>(V))
3823  ExprValueMap[Stripped].insert({V, Offset});
3824  }
3825  }
3826  return S;
3827 }
3828 
3829 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3830  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3831 
3832  ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3833  if (I != ValueExprMap.end()) {
3834  const SCEV *S = I->second;
3835  if (checkValidity(S))
3836  return S;
3837  eraseValueFromMap(V);
3838  forgetMemoizedResults(S);
3839  }
3840  return nullptr;
3841 }
3842 
3843 /// Return a SCEV corresponding to -V = -1*V
3845  SCEV::NoWrapFlags Flags) {
3846  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3847  return getConstant(
3848  cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3849 
3850  Type *Ty = V->getType();
3851  Ty = getEffectiveSCEVType(Ty);
3852  return getMulExpr(
3853  V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3854 }
3855 
3856 /// Return a SCEV corresponding to ~V = -1-V
3858  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3859  return getConstant(
3860  cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3861 
3862  Type *Ty = V->getType();
3863  Ty = getEffectiveSCEVType(Ty);
3864  const SCEV *AllOnes =
3865  getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3866  return getMinusSCEV(AllOnes, V);
3867 }
3868 
3869 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3870  SCEV::NoWrapFlags Flags,
3871  unsigned Depth) {
3872  // Fast path: X - X --> 0.
3873  if (LHS == RHS)
3874  return getZero(LHS->getType());
3875 
3876  // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3877  // makes it so that we cannot make much use of NUW.
3878  auto AddFlags = SCEV::FlagAnyWrap;
3879  const bool RHSIsNotMinSigned =
3880  !getSignedRangeMin(RHS).isMinSignedValue();
3881  if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3882  // Let M be the minimum representable signed value. Then (-1)*RHS
3883  // signed-wraps if and only if RHS is M. That can happen even for
3884  // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3885  // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3886  // (-1)*RHS, we need to prove that RHS != M.
3887  //
3888  // If LHS is non-negative and we know that LHS - RHS does not
3889  // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3890  // either by proving that RHS > M or that LHS >= 0.
3891  if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3892  AddFlags = SCEV::FlagNSW;
3893  }
3894  }
3895 
3896  // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3897  // RHS is NSW and LHS >= 0.
3898  //
3899  // The difficulty here is that the NSW flag may have been proven
3900  // relative to a loop that is to be found in a recurrence in LHS and
3901  // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3902  // larger scope than intended.
3903  auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3904 
3905  return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3906 }
3907 
3908 const SCEV *
3910  Type *SrcTy = V->getType();
3911  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3912  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3913  "Cannot truncate or zero extend with non-integer arguments!");
3914  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3915  return V; // No conversion
3916  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3917  return getTruncateExpr(V, Ty);
3918  return getZeroExtendExpr(V, Ty);
3919 }
3920 
3921 const SCEV *
3923  Type *Ty) {
3924  Type *SrcTy = V->getType();
3925  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3926  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3927  "Cannot truncate or zero extend with non-integer arguments!");
3928  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3929  return V; // No conversion
3930  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3931  return getTruncateExpr(V, Ty);
3932  return getSignExtendExpr(V, Ty);
3933 }
3934 
3935 const SCEV *
3937  Type *SrcTy = V->getType();
3938  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3939  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3940  "Cannot noop or zero extend with non-integer arguments!");
3941  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3942  "getNoopOrZeroExtend cannot truncate!");
3943  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3944  return V; // No conversion
3945  return getZeroExtendExpr(V, Ty);
3946 }
3947 
3948 const SCEV *
3950  Type *SrcTy = V->getType();
3951  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3952  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3953  "Cannot noop or sign extend with non-integer arguments!");
3954  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3955  "getNoopOrSignExtend cannot truncate!");
3956  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3957  return V; // No conversion
3958  return getSignExtendExpr(V, Ty);
3959 }
3960 
3961 const SCEV *
3963  Type *SrcTy = V->getType();
3964  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3965  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3966  "Cannot noop or any extend with non-integer arguments!");
3967  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3968  "getNoopOrAnyExtend cannot truncate!");
3969  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3970  return V; // No conversion
3971  return getAnyExtendExpr(V, Ty);
3972 }
3973 
3974 const SCEV *
3976  Type *SrcTy = V->getType();
3977  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3978  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3979  "Cannot truncate or noop with non-integer arguments!");
3980  assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3981  "getTruncateOrNoop cannot extend!");
3982  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3983  return V; // No conversion
3984  return getTruncateExpr(V, Ty);
3985 }
3986 
3988  const SCEV *RHS) {
3989  const SCEV *PromotedLHS = LHS;
3990  const SCEV *PromotedRHS = RHS;
3991 
3992  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3993  PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3994  else
3995  PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3996 
3997  return getUMaxExpr(PromotedLHS, PromotedRHS);
3998 }
3999 
4001  const SCEV *RHS) {
4002  const SCEV *PromotedLHS = LHS;
4003  const SCEV *PromotedRHS = RHS;
4004 
4005  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4006  PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4007  else
4008  PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4009 
4010  return getUMinExpr(PromotedLHS, PromotedRHS);
4011 }
4012 
4014  // A pointer operand may evaluate to a nonpointer expression, such as null.
4015  if (!V->getType()->isPointerTy())
4016  return V;
4017 
4018  if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4019  return getPointerBase(Cast->getOperand());
4020  } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4021  const SCEV *PtrOp = nullptr;
4022  for (const SCEV *NAryOp : NAry->operands()) {
4023  if (NAryOp->getType()->isPointerTy()) {
4024  // Cannot find the base of an expression with multiple pointer operands.
4025  if (PtrOp)
4026  return V;
4027  PtrOp = NAryOp;
4028  }
4029  }
4030  if (!PtrOp)
4031  return V;
4032  return getPointerBase(PtrOp);
4033  }
4034  return V;
4035 }
4036 
4037 /// Push users of the given Instruction onto the given Worklist.
4038 static void
4040  SmallVectorImpl<Instruction *> &Worklist) {
4041  // Push the def-use children onto the Worklist stack.
4042  for (User *U : I->users())
4043  Worklist.push_back(cast<Instruction>(U));
4044 }
4045 
4046 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4048  PushDefUseChildren(PN, Worklist);
4049 
4051  Visited.insert(PN);
4052  while (!Worklist.empty()) {
4053  Instruction *I = Worklist.pop_back_val();
4054  if (!Visited.insert(I).second)
4055  continue;
4056 
4057  auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4058  if (It != ValueExprMap.end()) {
4059  const SCEV *Old = It->second;
4060 
4061  // Short-circuit the def-use traversal if the symbolic name
4062  // ceases to appear in expressions.
4063  if (Old != SymName && !hasOperand(Old, SymName))
4064  continue;
4065 
4066  // SCEVUnknown for a PHI either means that it has an unrecognized
4067  // structure, it's a PHI that's in the progress of being computed
4068  // by createNodeForPHI, or it's a single-value PHI. In the first case,
4069  // additional loop trip count information isn't going to change anything.
4070  // In the second case, createNodeForPHI will perform the necessary
4071  // updates on its own when it gets to that point. In the third, we do
4072  // want to forget the SCEVUnknown.
4073  if (!isa<PHINode>(I) ||
4074  !isa<SCEVUnknown>(Old) ||
4075  (I != PN && Old == SymName)) {
4076  eraseValueFromMap(It->first);
4077  forgetMemoizedResults(Old);
4078  }
4079  }
4080 
4081  PushDefUseChildren(I, Worklist);
4082  }
4083 }
4084 
4085 namespace {
4086 
4087 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4088 public:
4089  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4090  ScalarEvolution &SE) {
4091  SCEVInitRewriter Rewriter(L, SE);
4092  const SCEV *Result = Rewriter.visit(S);
4093  return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4094  }
4095 
4096  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4097  if (!SE.isLoopInvariant(Expr, L))
4098  Valid = false;
4099  return Expr;
4100  }
4101 
4102  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4103  // Only allow AddRecExprs for this loop.
4104  if (Expr->getLoop() == L)
4105  return Expr->getStart();
4106  Valid = false;
4107  return Expr;
4108  }
4109 
4110  bool isValid() { return Valid; }
4111 
4112 private:
4113  explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4114  : SCEVRewriteVisitor(SE), L(L) {}
4115 
4116  const Loop *L;
4117  bool Valid = true;
4118 };
4119 
4120 /// This class evaluates the compare condition by matching it against the
4121 /// condition of loop latch. If there is a match we assume a true value
4122 /// for the condition while building SCEV nodes.
4123 class SCEVBackedgeConditionFolder
4124  : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4125 public:
4126  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4127  ScalarEvolution &SE) {
4128  bool IsPosBECond = false;
4129  Value *BECond = nullptr;
4130  if (BasicBlock *Latch = L->getLoopLatch()) {
4131  BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4132  if (BI && BI->isConditional()) {
4133  assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4134  "Both outgoing branches should not target same header!");
4135  BECond = BI->getCondition();
4136  IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4137  } else {
4138  return S;
4139  }
4140  }
4141  SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4142  return Rewriter.visit(S);
4143  }
4144 
4145  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4146  const SCEV *Result = Expr;
4147  bool InvariantF = SE.isLoopInvariant(Expr, L);
4148 
4149  if (!InvariantF) {
4150  Instruction *I = cast<Instruction>(Expr->getValue());
4151  switch (I->getOpcode()) {
4152  case Instruction::Select: {
4153  SelectInst *SI = cast<SelectInst>(I);
4155  compareWithBackedgeCondition(SI->getCondition());
4156  if (Res.hasValue()) {
4157  bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4158  Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4159  }
4160  break;
4161  }
4162  default: {
4163  Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4164  if (Res.hasValue())
4165  Result = Res.getValue();
4166  break;
4167  }
4168  }
4169  }
4170  return Result;
4171  }
4172 
4173 private:
4174  explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4175  bool IsPosBECond, ScalarEvolution &SE)
4176  : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4177  IsPositiveBECond(IsPosBECond) {}
4178 
4179  Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4180 
4181  const Loop *L;
4182  /// Loop back condition.
4183  Value *BackedgeCond = nullptr;
4184  /// Set to true if loop back is on positive branch condition.
4185  bool IsPositiveBECond;
4186 };
4187 
4189 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4190 
4191  // If value matches the backedge condition for loop latch,
4192  // then return a constant evolution node based on loopback
4193  // branch taken.
4194  if (BackedgeCond == IC)
4195  return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4196  : SE.getZero(Type::getInt1Ty(SE.getContext()));
4197  return None;
4198 }
4199 
4200 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4201 public:
4202  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4203  ScalarEvolution &SE) {
4204  SCEVShiftRewriter Rewriter(L, SE);
4205  const SCEV *Result = Rewriter.visit(S);
4206  return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4207  }
4208 
4209  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4210  // Only allow AddRecExprs for this loop.
4211  if (!SE.isLoopInvariant(Expr, L))
4212  Valid = false;
4213  return Expr;
4214  }
4215 
4216  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4217  if (Expr->getLoop() == L && Expr->isAffine())
4218  return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4219  Valid = false;
4220  return Expr;
4221  }
4222 
4223  bool isValid() { return Valid; }
4224 
4225 private:
4226  explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4227  : SCEVRewriteVisitor(SE), L(L) {}
4228 
4229  const Loop *L;
4230  bool Valid = true;
4231 };
4232 
4233 } // end anonymous namespace
4234 
4236 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4237  if (!AR->isAffine())
4238  return SCEV::FlagAnyWrap;
4239 
4240  using OBO = OverflowingBinaryOperator;
4241 
4243 
4244  if (!AR->hasNoSignedWrap()) {
4245  ConstantRange AddRecRange = getSignedRange(AR);
4246  ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4247 
4249  Instruction::Add, IncRange, OBO::NoSignedWrap);
4250  if (NSWRegion.contains(AddRecRange))
4251  Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4252  }
4253 
4254  if (!AR->hasNoUnsignedWrap()) {
4255  ConstantRange AddRecRange = getUnsignedRange(AR);
4256  ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4257 
4259  Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4260  if (NUWRegion.contains(AddRecRange))
4261  Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4262  }
4263 
4264  return Result;
4265 }
4266 
4267 namespace {
4268 
4269 /// Represents an abstract binary operation. This may exist as a
4270 /// normal instruction or constant expression, or may have been
4271 /// derived from an expression tree.
4272 struct BinaryOp {
4273  unsigned Opcode;
4274  Value *LHS;
4275  Value *RHS;
4276  bool IsNSW = false;
4277  bool IsNUW = false;
4278 
4279  /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4280  /// constant expression.
4281  Operator *Op = nullptr;
4282 
4283  explicit BinaryOp(Operator *Op)
4284  : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4285  Op(Op) {
4286  if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4287  IsNSW = OBO->hasNoSignedWrap();
4288  IsNUW = OBO->hasNoUnsignedWrap();
4289  }
4290  }
4291 
4292  explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4293  bool IsNUW = false)
4294  : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4295 };
4296 
4297 } // end anonymous namespace
4298 
4299 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4301  auto *Op = dyn_cast<Operator>(V);
4302  if (!Op)
4303  return None;
4304 
4305  // Implementation detail: all the cleverness here should happen without
4306  // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4307  // SCEV expressions when possible, and we should not break that.
4308 
4309  switch (Op->getOpcode()) {
4310  case Instruction::Add:
4311  case Instruction::Sub:
4312  case Instruction::Mul:
4313  case Instruction::UDiv:
4314  case Instruction::URem:
4315  case Instruction::And:
4316  case Instruction::Or:
4317  case Instruction::AShr:
4318  case Instruction::Shl:
4319  return BinaryOp(Op);
4320 
4321  case Instruction::Xor:
4322  if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4323  // If the RHS of the xor is a signmask, then this is just an add.
4324  // Instcombine turns add of signmask into xor as a strength reduction step.
4325  if (RHSC->getValue().isSignMask())
4326  return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4327  return BinaryOp(Op);
4328 
4329  case Instruction::LShr:
4330  // Turn logical shift right of a constant into a unsigned divide.
4331  if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4332  uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4333 
4334  // If the shift count is not less than the bitwidth, the result of
4335  // the shift is undefined. Don't try to analyze it, because the
4336  // resolution chosen here may differ from the resolution chosen in
4337  // other parts of the compiler.
4338  if (SA->getValue().ult(BitWidth)) {
4339  Constant *X =
4340  ConstantInt::get(SA->getContext(),
4341  APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4342  return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4343  }
4344  }
4345  return BinaryOp(Op);
4346 
4347  case Instruction::ExtractValue: {
4348  auto *EVI = cast<ExtractValueInst>(Op);
4349  if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4350  break;
4351 
4352  auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4353  if (!CI)
4354  break;
4355 
4356  if (auto *F = CI->getCalledFunction())
4357  switch (F->getIntrinsicID()) {
4358  case Intrinsic::sadd_with_overflow:
4359  case Intrinsic::uadd_with_overflow:
4360  if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4361  return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4362  CI->getArgOperand(1));
4363 
4364  // Now that we know that all uses of the arithmetic-result component of
4365  // CI are guarded by the overflow check, we can go ahead and pretend
4366  // that the arithmetic is non-overflowing.
4367  if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4368  return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4369  CI->getArgOperand(1), /* IsNSW = */ true,
4370  /* IsNUW = */ false);
4371  else
4372  return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4373  CI->getArgOperand(1), /* IsNSW = */ false,
4374  /* IsNUW*/ true);
4375  case Intrinsic::ssub_with_overflow:
4376  case Intrinsic::usub_with_overflow:
4377  if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4378  return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4379  CI->getArgOperand(1));
4380 
4381  // The same reasoning as sadd/uadd above.
4382  if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4383  return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4384  CI->getArgOperand(1), /* IsNSW = */ true,
4385  /* IsNUW = */ false);
4386  else
4387  return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4388  CI->getArgOperand(1), /* IsNSW = */ false,
4389  /* IsNUW = */ true);
4390  case Intrinsic::smul_with_overflow:
4391  case Intrinsic::umul_with_overflow:
4392  return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4393  CI->getArgOperand(1));
4394  default:
4395  break;
4396  }
4397  break;
4398  }
4399 
4400  default:
4401  break;
4402  }
4403 
4404  return None;
4405 }
4406 
4407 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4408 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4409 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4410 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4411 /// follows one of the following patterns:
4412 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4413 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4414 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4415 /// we return the type of the truncation operation, and indicate whether the
4416 /// truncated type should be treated as signed/unsigned by setting
4417 /// \p Signed to true/false, respectively.
4418 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4419  bool &Signed, ScalarEvolution &SE) {
4420  // The case where Op == SymbolicPHI (that is, with no type conversions on
4421  // the way) is handled by the regular add recurrence creating logic and
4422  // would have already been triggered in createAddRecForPHI. Reaching it here
4423  // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4424  // because one of the other operands of the SCEVAddExpr updating this PHI is
4425  // not invariant).
4426  //
4427  // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4428  // this case predicates that allow us to prove that Op == SymbolicPHI will
4429  // be added.
4430  if (Op == SymbolicPHI)
4431  return nullptr;
4432 
4433  unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4434  unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4435  if (SourceBits != NewBits)
4436  return nullptr;
4437 
4440  if (!SExt && !ZExt)
4441  return nullptr;
4442  const SCEVTruncateExpr *Trunc =
4443  SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4444  : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4445  if (!Trunc)
4446  return nullptr;
4447  const SCEV *X = Trunc->getOperand();
4448  if (X != SymbolicPHI)
4449  return nullptr;
4450  Signed = SExt != nullptr;
4451  return Trunc->getType();
4452 }
4453 
4454 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4455  if (!PN->getType()->isIntegerTy())
4456  return nullptr;
4457  const Loop *L = LI.getLoopFor(PN->getParent());
4458  if (!L || L->getHeader() != PN->getParent())
4459  return nullptr;
4460  return L;
4461 }
4462 
4463 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4464 // computation that updates the phi follows the following pattern:
4465 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4466 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4467 // If so, try to see if it can be rewritten as an AddRecExpr under some
4468 // Predicates. If successful, return them as a pair. Also cache the results
4469 // of the analysis.
4470 //
4471 // Example usage scenario:
4472 // Say the Rewriter is called for the following SCEV:
4473 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4474 // where:
4475 // %X = phi i64 (%Start, %BEValue)
4476 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4477 // and call this function with %SymbolicPHI = %X.
4478 //
4479 // The analysis will find that the value coming around the backedge has
4480 // the following SCEV:
4481 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4482 // Upon concluding that this matches the desired pattern, the function
4483 // will return the pair {NewAddRec, SmallPredsVec} where:
4484 // NewAddRec = {%Start,+,%Step}
4485 // SmallPredsVec = {P1, P2, P3} as follows:
4486 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4487 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4488 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4489 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4490 // under the predicates {P1,P2,P3}.
4491 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4492 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4493 //
4494 // TODO's:
4495 //
4496 // 1) Extend the Induction descriptor to also support inductions that involve
4497 // casts: When needed (namely, when we are called in the context of the
4498 // vectorizer induction analysis), a Set of cast instructions will be
4499 // populated by this method, and provided back to isInductionPHI. This is
4500 // needed to allow the vectorizer to properly record them to be ignored by
4501 // the cost model and to avoid vectorizing them (otherwise these casts,
4502 // which are redundant under the runtime overflow checks, will be
4503 // vectorized, which can be costly).
4504 //
4505 // 2) Support additional induction/PHISCEV patterns: We also want to support
4506 // inductions where the sext-trunc / zext-trunc operations (partly) occur
4507 // after the induction update operation (the induction increment):
4508 //
4509 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4510 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4511 //
4512 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4513 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4514 //
4515 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4517 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4519 
4520  // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4521  // return an AddRec expression under some predicate.
4522 
4523  auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4524  const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4525  assert(L && "Expecting an integer loop header phi");
4526 
4527  // The loop may have multiple entrances or multiple exits; we can analyze
4528  // this phi as an addrec if it has a unique entry value and a unique
4529  // backedge value.
4530  Value *BEValueV = nullptr, *StartValueV = nullptr;
4531  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4532  Value *V = PN->getIncomingValue(i);
4533  if (L->contains(PN->getIncomingBlock(i))) {
4534  if (!BEValueV) {
4535  BEValueV = V;
4536  } else if (BEValueV != V) {
4537  BEValueV = nullptr;
4538  break;
4539  }
4540  } else if (!StartValueV) {
4541  StartValueV = V;
4542  } else if (StartValueV != V) {
4543  StartValueV = nullptr;
4544  break;
4545  }
4546  }
4547  if (!BEValueV || !StartValueV)
4548  return None;
4549 
4550  const SCEV *BEValue = getSCEV(BEValueV);
4551 
4552  // If the value coming around the backedge is an add with the symbolic
4553  // value we just inserted, possibly with casts that we can ignore under
4554  // an appropriate runtime guard, then we found a simple induction variable!
4555  const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4556  if (!Add)
4557  return None;
4558 
4559  // If there is a single occurrence of the symbolic value, possibly
4560  // casted, replace it with a recurrence.
4561  unsigned FoundIndex = Add->getNumOperands();
4562  Type *TruncTy = nullptr;
4563  bool Signed;
4564  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4565  if ((TruncTy =
4566  isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4567  if (FoundIndex == e) {
4568  FoundIndex = i;
4569  break;
4570  }
4571 
4572  if (FoundIndex == Add->getNumOperands())
4573  return None;
4574 
4575  // Create an add with everything but the specified operand.
4577  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4578  if (i != FoundIndex)
4579  Ops.push_back(Add->getOperand(i));
4580  const SCEV *Accum = getAddExpr(Ops);
4581 
4582  // The runtime checks will not be valid if the step amount is
4583  // varying inside the loop.
4584  if (!isLoopInvariant(Accum, L))
4585  return None;
4586 
4587  // *** Part2: Create the predicates
4588 
4589  // Analysis was successful: we have a phi-with-cast pattern for which we
4590  // can return an AddRec expression under the following predicates:
4591  //
4592  // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4593  // fits within the truncated type (does not overflow) for i = 0 to n-1.
4594  // P2: An Equal predicate that guarantees that
4595  // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4596  // P3: An Equal predicate that guarantees that
4597  // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4598  //
4599  // As we next prove, the above predicates guarantee that:
4600  // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4601  //
4602  //
4603  // More formally, we want to prove that:
4604  // Expr(i+1) = Start + (i+1) * Accum
4605  // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4606  //
4607  // Given that:
4608  // 1) Expr(0) = Start
4609  // 2) Expr(1) = Start + Accum
4610  // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4611  // 3) Induction hypothesis (step i):
4612  // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4613  //
4614  // Proof:
4615  // Expr(i+1) =
4616  // = Start + (i+1)*Accum
4617  // = (Start + i*Accum) + Accum
4618  // = Expr(i) + Accum
4619  // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4620  // :: from step i
4621  //
4622  // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4623  //
4624  // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4625  // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4626  // + Accum :: from P3
4627  //
4628  // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4629  // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4630  //
4631  // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4632  // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4633  //
4634  // By induction, the same applies to all iterations 1<=i<n:
4635  //
4636 
4637  // Create a truncated addrec for which we will add a no overflow check (P1).
4638  const SCEV *StartVal = getSCEV(StartValueV);
4639  const SCEV *PHISCEV =
4640  getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4641  getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4642 
4643  // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4644  // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4645  // will be constant.
4646  //
4647  // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4648  // add P1.
4649  if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4653  const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4654  Predicates.push_back(AddRecPred);
4655  }
4656 
4657  // Create the Equal Predicates P2,P3:
4658 
4659  // It is possible that the predicates P2 and/or P3 are computable at
4660  // compile time due to StartVal and/or Accum being constants.
4661  // If either one is, then we can check that now and escape if either P2
4662  // or P3 is false.
4663 
4664  // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4665  // for each of StartVal and Accum
4666  auto getExtendedExpr = [&](const SCEV *Expr,
4667  bool CreateSignExtend) -> const SCEV * {
4668  assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4669  const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4670  const SCEV *ExtendedExpr =
4671  CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4672  : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4673  return ExtendedExpr;
4674  };
4675 
4676  // Given:
4677  // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4678  // = getExtendedExpr(Expr)
4679  // Determine whether the predicate P: Expr == ExtendedExpr
4680  // is known to be false at compile time
4681  auto PredIsKnownFalse = [&](const SCEV *Expr,
4682  const SCEV *ExtendedExpr) -> bool {
4683  return Expr != ExtendedExpr &&
4684  isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4685  };
4686 
4687  const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4688  if (PredIsKnownFalse(StartVal, StartExtended)) {
4689  DEBUG(dbgs() << "P2 is compile-time false\n";);
4690  return None;
4691  }
4692 
4693  // The Step is always Signed (because the overflow checks are either
4694  // NSSW or NUSW)
4695  const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4696  if (PredIsKnownFalse(Accum, AccumExtended)) {
4697  DEBUG(dbgs() << "P3 is compile-time false\n";);
4698  return None;
4699  }
4700 
4701  auto AppendPredicate = [&](const SCEV *Expr,
4702  const SCEV *ExtendedExpr) -> void {
4703  if (Expr != ExtendedExpr &&
4704  !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4705  const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4706  DEBUG (dbgs() << "Added Predicate: " << *Pred);
4707  Predicates.push_back(Pred);
4708  }
4709  };
4710 
4711  AppendPredicate(StartVal, StartExtended);
4712  AppendPredicate(Accum, AccumExtended);
4713 
4714  // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4715  // which the casts had been folded away. The caller can rewrite SymbolicPHI
4716  // into NewAR if it will also add the runtime overflow checks specified in
4717  // Predicates.
4718  auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4719 
4720  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4721  std::make_pair(NewAR, Predicates);
4722  // Remember the result of the analysis for this SCEV at this locayyytion.
4723  PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4724  return PredRewrite;
4725 }
4726 
4729  auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4730  const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4731  if (!L)
4732  return None;
4733 
4734  // Check to see if we already analyzed this PHI.
4735  auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4736  if (I != PredicatedSCEVRewrites.end()) {
4737  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4738  I->second;
4739  // Analysis was done before and failed to create an AddRec:
4740  if (Rewrite.first == SymbolicPHI)
4741  return None;
4742  // Analysis was done before and succeeded to create an AddRec under
4743  // a predicate:
4744  assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4745  assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4746  return Rewrite;
4747  }
4748 
4750  Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4751 
4752  // Record in the cache that the analysis failed
4753  if (!Rewrite) {
4755  PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4756  return None;
4757  }
4758 
4759  return Rewrite;
4760 }
4761 
4762 // FIXME: This utility is currently required because the Rewriter currently
4763 // does not rewrite this expression:
4764 // {0, +, (sext ix (trunc iy to ix) to iy)}
4765 // into {0, +, %step},
4766 // even when the following Equal predicate exists:
4767 // "%step == (sext ix (trunc iy to ix) to iy)".
4769  const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4770  if (AR1 == AR2)
4771  return true;
4772 
4773  auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4774  if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4775  !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4776  return false;
4777  return true;
4778  };
4779 
4780  if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4781  !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4782  return false;
4783  return true;
4784 }
4785 
4786 /// A helper function for createAddRecFromPHI to handle simple cases.
4787 ///
4788 /// This function tries to find an AddRec expression for the simplest (yet most
4789 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4790 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4791 /// technique for finding the AddRec expression.
4792 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4793  Value *BEValueV,
4794  Value *StartValueV) {
4795  const Loop *L = LI.getLoopFor(PN->getParent());
4796  assert(L && L->getHeader() == PN->getParent());
4797  assert(BEValueV && StartValueV);
4798 
4799  auto BO = MatchBinaryOp(BEValueV, DT);
4800  if (!BO)
4801  return nullptr;
4802 
4803  if (BO->Opcode != Instruction::Add)
4804  return nullptr;
4805 
4806  const SCEV *Accum = nullptr;
4807  if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4808  Accum = getSCEV(BO->RHS);
4809  else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4810  Accum = getSCEV(BO->LHS);
4811 
4812  if (!Accum)
4813  return nullptr;
4814 
4816  if (BO->IsNUW)
4817  Flags = setFlags(Flags, SCEV::FlagNUW);
4818  if (BO->IsNSW)
4819  Flags = setFlags(Flags, SCEV::FlagNSW);
4820 
4821  const SCEV *StartVal = getSCEV(StartValueV);
4822  const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4823 
4824  ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4825 
4826  // We can add Flags to the post-inc expression only if we
4827  // know that it is *undefined behavior* for BEValueV to
4828  // overflow.
4829  if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4830  if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4831  (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4832 
4833  return PHISCEV;
4834 }
4835 
4836 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4837  const Loop *L = LI.getLoopFor(PN->getParent());
4838  if (!L || L->getHeader() != PN->getParent())
4839  return nullptr;
4840 
4841  // The loop may have multiple entrances or multiple exits; we can analyze
4842  // this phi as an addrec if it has a unique entry value and a unique
4843  // backedge value.
4844  Value *BEValueV = nullptr, *StartValueV = nullptr;
4845  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4846  Value *V = PN->getIncomingValue(i);
4847  if (L->contains(PN->getIncomingBlock(i))) {
4848  if (!BEValueV) {
4849  BEValueV = V;
4850  } else if (BEValueV != V) {
4851  BEValueV = nullptr;
4852  break;
4853  }
4854  } else if (!StartValueV) {
4855  StartValueV = V;
4856  } else if (StartValueV != V) {
4857  StartValueV = nullptr;
4858  break;
4859  }
4860  }
4861  if (!BEValueV || !StartValueV)
4862  return nullptr;
4863 
4864  assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4865  "PHI node already processed?");
4866 
4867  // First, try to find AddRec expression without creating a fictituos symbolic
4868  // value for PN.
4869  if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4870  return S;
4871 
4872  // Handle PHI node value symbolically.
4873  const SCEV *SymbolicName = getUnknown(PN);
4874  ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4875 
4876  // Using this symbolic name for the PHI, analyze the value coming around
4877  // the back-edge.
4878  const SCEV *BEValue = getSCEV(BEValueV);
4879 
4880  // NOTE: If BEValue is loop invariant, we know that the PHI node just
4881  // has a special value for the first iteration of the loop.
4882 
4883  // If the value coming around the backedge is an add with the symbolic
4884  // value we just inserted, then we found a simple induction variable!
4885  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4886  // If there is a single occurrence of the symbolic value, replace it
4887  // with a recurrence.
4888  unsigned FoundIndex = Add->getNumOperands();
4889  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4890  if (Add->getOperand(i) == SymbolicName)
4891  if (FoundIndex == e) {
4892  FoundIndex = i;
4893  break;
4894  }
4895 
4896  if (FoundIndex != Add->getNumOperands()) {
4897  // Create an add with everything but the specified operand.
4899  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4900  if (i != FoundIndex)
4901  Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4902  L, *this));
4903  const SCEV *Accum = getAddExpr(Ops);
4904 
4905  // This is not a valid addrec if the step amount is varying each
4906  // loop iteration, but is not itself an addrec in this loop.
4907  if (isLoopInvariant(Accum, L) ||
4908  (isa<SCEVAddRecExpr>(Accum) &&
4909  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4911 
4912  if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4913  if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4914  if (BO->IsNUW)
4915  Flags = setFlags(Flags, SCEV::FlagNUW);
4916  if (BO->IsNSW)
4917  Flags = setFlags(Flags, SCEV::FlagNSW);
4918  }
4919  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4920  // If the increment is an inbounds GEP, then we know the address
4921  // space cannot be wrapped around. We cannot make any guarantee
4922  // about signed or unsigned overflow because pointers are
4923  // unsigned but we may have a negative index from the base
4924  // pointer. We can guarantee that no unsigned wrap occurs if the
4925  // indices form a positive value.
4926  if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4927  Flags = setFlags(Flags, SCEV::FlagNW);
4928 
4929  const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4930  if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4931  Flags = setFlags(Flags, SCEV::FlagNUW);
4932  }
4933 
4934  // We cannot transfer nuw and nsw flags from subtraction
4935  // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4936  // for instance.
4937  }
4938 
4939  const SCEV *StartVal = getSCEV(StartValueV);
4940  const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4941 
4942  // Okay, for the entire analysis of this edge we assumed the PHI
4943  // to be symbolic. We now need to go back and purge all of the
4944  // entries for the scalars that use the symbolic expression.
4945  forgetSymbolicName(PN, SymbolicName);
4946  ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4947 
4948  // We can add Flags to the post-inc expression only if we
4949  // know that it is *undefined behavior* for BEValueV to
4950  // overflow.
4951  if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4952  if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4953  (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4954 
4955  return PHISCEV;
4956  }
4957  }
4958  } else {
4959  // Otherwise, this could be a loop like this:
4960  // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4961  // In this case, j = {1,+,1} and BEValue is j.
4962  // Because the other in-value of i (0) fits the evolution of BEValue
4963  // i really is an addrec evolution.
4964  //
4965  // We can generalize this saying that i is the shifted value of BEValue
4966  // by one iteration:
4967  // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4968  const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4969  const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4970  if (Shifted != getCouldNotCompute() &&
4971  Start != getCouldNotCompute()) {
4972  const SCEV *StartVal = getSCEV(StartValueV);
4973  if (Start == StartVal) {
4974  // Okay, for the entire analysis of this edge we assumed the PHI
4975  // to be symbolic. We now need to go back and purge all of the
4976  // entries for the scalars that use the symbolic expression.
4977  forgetSymbolicName(PN, SymbolicName);
4978  ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4979  return Shifted;
4980  }
4981  }
4982  }
4983 
4984  // Remove the temporary PHI node SCEV that has been inserted while intending
4985  // to create an AddRecExpr for this PHI node. We can not keep this temporary
4986  // as it will prevent later (possibly simpler) SCEV expressions to be added
4987  // to the ValueExprMap.
4988  eraseValueFromMap(PN);
4989 
4990  return nullptr;
4991 }
4992 
4993 // Checks if the SCEV S is available at BB. S is considered available at BB
4994 // if S can be materialized at BB without introducing a fault.
4995 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4996  BasicBlock *BB) {
4997  struct CheckAvailable {
4998  bool TraversalDone = false;
4999  bool Available = true;
5000 
5001  const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5002  BasicBlock *BB = nullptr;
5003  DominatorTree &DT;
5004 
5005  CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5006  : L(L), BB(BB), DT(DT) {}
5007 
5008  bool setUnavailable() {
5009  TraversalDone = true;
5010  Available = false;
5011  return false;
5012  }
5013 
5014  bool follow(const SCEV *S) {
5015  switch (S->getSCEVType()) {
5016  case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5017  case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5018  // These expressions are available if their operand(s) is/are.
5019  return true;
5020 
5021  case scAddRecExpr: {
5022  // We allow add recurrences that are on the loop BB is in, or some
5023  // outer loop. This guarantees availability because the value of the
5024  // add recurrence at BB is simply the "current" value of the induction
5025  // variable. We can relax this in the future; for instance an add
5026  // recurrence on a sibling dominating loop is also available at BB.
5027  const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5028  if (L && (ARLoop == L || ARLoop->contains(L)))
5029  return true;
5030 
5031  return setUnavailable();
5032  }
5033 
5034  case scUnknown: {
5035  // For SCEVUnknown, we check for simple dominance.
5036  const auto *SU = cast<SCEVUnknown>(S);
5037  Value *V = SU->getValue();
5038 
5039  if (isa<Argument>(V))
5040  return false;
5041 
5042  if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5043  return false;
5044 
5045  return setUnavailable();
5046  }
5047 
5048  case scUDivExpr:
5049  case scCouldNotCompute:
5050  // We do not try to smart about these at all.
5051  return setUnavailable();
5052  }
5053  llvm_unreachable("switch should be fully covered!");
5054  }
5055 
5056  bool isDone() { return TraversalDone; }
5057  };
5058 
5059  CheckAvailable CA(L, BB, DT);
5061 
5062  ST.visitAll(S);
5063  return CA.Available;
5064 }
5065 
5066 // Try to match a control flow sequence that branches out at BI and merges back
5067 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5068 // match.
5070  Value *&C, Value *&LHS, Value *&RHS) {
5071  C = BI->getCondition();
5072 
5073  BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5074  BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5075 
5076  if (!LeftEdge.isSingleEdge())
5077  return false;
5078 
5079  assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5080 
5081  Use &LeftUse = Merge->getOperandUse(0);
5082  Use &RightUse = Merge->getOperandUse(1);
5083 
5084  if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5085  LHS = LeftUse;
5086  RHS = RightUse;
5087  return true;
5088  }
5089 
5090  if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5091  LHS = RightUse;
5092  RHS = LeftUse;
5093  return true;
5094  }
5095 
5096  return false;
5097 }
5098 
5099 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5100  auto IsReachable =
5101  [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5102  if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5103  const Loop *L = LI.getLoopFor(PN->getParent());
5104 
5105  // We don't want to break LCSSA, even in a SCEV expression tree.
5106  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5107  if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5108  return nullptr;
5109 
5110  // Try to match
5111  //
5112  // br %cond, label %left, label %right
5113  // left:
5114  // br label %merge
5115  // right:
5116  // br label %merge
5117  // merge:
5118  // V = phi [ %x, %left ], [ %y, %right ]
5119  //
5120  // as "select %cond, %x, %y"
5121 
5122  BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5123  assert(IDom && "At least the entry block should dominate PN");
5124 
5125  auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5126  Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5127 
5128  if (BI && BI->isConditional() &&
5129  BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5130  IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5131  IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5132  return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5133  }
5134 
5135  return nullptr;
5136 }
5137 
5138 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5139  if (const SCEV *S = createAddRecFromPHI(PN))
5140  return S;
5141 
5142  if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5143  return S;
5144 
5145  // If the PHI has a single incoming value, follow that value, unless the
5146  // PHI's incoming blocks are in a different loop, in which case doing so
5147  // risks breaking LCSSA form. Instcombine would normally zap these, but
5148  // it doesn't have DominatorTree information, so it may miss cases.
5149  if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5150  if (LI.replacementPreservesLCSSAForm(PN, V))
5151  return getSCEV(V);
5152 
5153  // If it's not a loop phi, we can't handle it yet.
5154  return getUnknown(PN);
5155 }
5156 
5157 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5158  Value *Cond,
5159  Value *TrueVal,
5160  Value *FalseVal) {
5161  // Handle "constant" branch or select. This can occur for instance when a
5162  // loop pass transforms an inner loop and moves on to process the outer loop.
5163  if (auto *CI = dyn_cast<ConstantInt>(Cond))
5164  return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5165 
5166  // Try to match some simple smax or umax patterns.
5167  auto *ICI = dyn_cast<ICmpInst>(Cond);
5168  if (!ICI)
5169  return getUnknown(I);
5170 
5171  Value *LHS = ICI->getOperand(0);
5172  Value *RHS = ICI->getOperand(1);
5173 
5174  switch (ICI->getPredicate()) {
5175  case ICmpInst::ICMP_SLT:
5176  case ICmpInst::ICMP_SLE:
5177  std::swap(LHS, RHS);
5179  case ICmpInst::ICMP_SGT:
5180  case ICmpInst::ICMP_SGE:
5181  // a >s b ? a+x : b+x -> smax(a, b)+x
5182  // a >s b ? b+x : a+x -> smin(a, b)+x
5183  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5184  const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5185  const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5186  const SCEV *LA = getSCEV(TrueVal);
5187  const SCEV *RA = getSCEV(FalseVal);
5188  const SCEV *LDiff = getMinusSCEV(LA, LS);
5189  const SCEV *RDiff = getMinusSCEV(RA, RS);
5190  if (LDiff == RDiff)
5191  return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5192  LDiff = getMinusSCEV(LA, RS);
5193  RDiff = getMinusSCEV(RA, LS);
5194  if (LDiff == RDiff)
5195  return getAddExpr(getSMinExpr(LS, RS), LDiff);
5196  }
5197  break;
5198  case ICmpInst::ICMP_ULT:
5199  case ICmpInst::ICMP_ULE:
5200  std::swap(LHS, RHS);
5202  case ICmpInst::ICMP_UGT:
5203  case ICmpInst::ICMP_UGE:
5204  // a >u b ? a+x : b+x -> umax(a, b)+x
5205  // a >u b ? b+x : a+x -> umin(a, b)+x
5206  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5207  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5208  const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5209  const SCEV *LA = getSCEV(TrueVal);
5210  const SCEV *RA = getSCEV(FalseVal);
5211  const SCEV *LDiff = getMinusSCEV(LA, LS);
5212  const SCEV *RDiff = getMinusSCEV(RA, RS);
5213  if (LDiff == RDiff)
5214  return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5215  LDiff = getMinusSCEV(LA, RS);
5216  RDiff = getMinusSCEV(RA, LS);
5217  if (LDiff == RDiff)
5218  return getAddExpr(getUMinExpr(LS, RS), LDiff);
5219  }
5220  break;
5221  case ICmpInst::ICMP_NE:
5222  // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5223  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5224  isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5225  const SCEV *One = getOne(I->getType());
5226  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5227  const SCEV *LA = getSCEV(TrueVal);
5228  const SCEV *RA = getSCEV(FalseVal);
5229  const SCEV *LDiff = getMinusSCEV(LA, LS);
5230  const SCEV *RDiff = getMinusSCEV(RA, One);
5231  if (LDiff == RDiff)
5232  return getAddExpr(getUMaxExpr(One, LS), LDiff);
5233  }
5234  break;
5235  case ICmpInst::ICMP_EQ:
5236  // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5237  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5238  isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5239  const SCEV *One = getOne(I->getType());
5240  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5241  const SCEV *LA = getSCEV(TrueVal);
5242  const SCEV *RA = getSCEV(FalseVal);
5243  const SCEV *LDiff = getMinusSCEV(LA, One);
5244  const SCEV *RDiff = getMinusSCEV(RA, LS);
5245  if (LDiff == RDiff)
5246  return getAddExpr(getUMaxExpr(One, LS), LDiff);
5247  }
5248  break;
5249  default:
5250  break;
5251  }
5252 
5253  return getUnknown(I);
5254 }
5255 
5256 /// Expand GEP instructions into add and multiply operations. This allows them
5257 /// to be analyzed by regular SCEV code.
5258 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5259  // Don't attempt to analyze GEPs over unsized objects.
5260  if (!GEP->getSourceElementType()->isSized())
5261  return getUnknown(GEP);
5262 
5263  SmallVector<const SCEV *, 4> IndexExprs;
5264  for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5265  IndexExprs.push_back(getSCEV(*Index));
5266  return getGEPExpr(GEP, IndexExprs);
5267 }
5268 
5269 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5270  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5271  return C->getAPInt().countTrailingZeros();
5272 
5273  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5274  return std::min(GetMinTrailingZeros(T->getOperand()),
5275  (uint32_t)getTypeSizeInBits(T->getType()));
5276 
5277  if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5278  uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5279  return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5280  ? getTypeSizeInBits(E->getType())
5281  : OpRes;
5282  }
5283 
5284  if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5285  uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5286  return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5287  ? getTypeSizeInBits(E->getType())
5288  : OpRes;
5289  }
5290 
5291  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5292  // The result is the min of all operands results.
5293  uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5294  for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5295  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5296  return MinOpRes;
5297  }
5298 
5299  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5300  // The result is the sum of all operands results.
5301  uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5302  uint32_t BitWidth = getTypeSizeInBits(M->getType());
5303  for (unsigned i = 1, e = M->getNumOperands();
5304  SumOpRes != BitWidth && i != e; ++i)
5305  SumOpRes =
5306  std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5307  return SumOpRes;
5308  }
5309 
5310  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5311  // The result is the min of all operands results.
5312  uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5313  for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5314  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5315  return MinOpRes;
5316  }
5317 
5318  if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5319  // The result is the min of all operands results.
5320  uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5321  for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5322  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5323  return MinOpRes;
5324  }
5325 
5326  if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5327  // The result is the min of all operands results.
5328  uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5329  for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5330  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5331  return MinOpRes;
5332  }
5333 
5334  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5335  // For a SCEVUnknown, ask ValueTracking.
5336  KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5337  return Known.countMinTrailingZeros();
5338  }
5339 
5340  // SCEVUDivExpr
5341  return 0;
5342 }
5343 
5345  auto I = MinTrailingZerosCache.find(S);
5346  if (I != MinTrailingZerosCache.end())
5347  return I->second;
5348 
5349  uint32_t Result = GetMinTrailingZerosImpl(S);
5350  auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5351  assert(InsertPair.second && "Should insert a new key");
5352  return InsertPair.first->second;
5353 }
5354 
5355 /// Helper method to assign a range to V from metadata present in the IR.
5357  if (Instruction *I = dyn_cast<Instruction>(V))
5359  return getConstantRangeFromMetadata(*MD);
5360 
5361  return None;
5362 }
5363 
5364 /// Determine the range for a particular SCEV. If SignHint is
5365 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5366 /// with a "cleaner" unsigned (resp. signed) representation.
5367 const ConstantRange &
5368 ScalarEvolution::getRangeRef(const SCEV *S,
5369  ScalarEvolution::RangeSignHint SignHint) {
5371  SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5372  : SignedRanges;
5373 
5374  // See if we've computed this range already.
5376  if (I != Cache.end())
5377  return I->second;
5378 
5379  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5380  return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5381 
5382  unsigned BitWidth = getTypeSizeInBits(S->getType());
5383  ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5384 
5385  // If the value has known zeros, the maximum value will have those known zeros
5386  // as well.
5387  uint32_t TZ = GetMinTrailingZeros(S);
5388  if (TZ != 0) {
5389  if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5390  ConservativeResult =
5392  APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5393  else
5394  ConservativeResult = ConstantRange(
5395  APInt::getSignedMinValue(BitWidth),
5396  APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5397  }
5398 
5399  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5400  ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5401  for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5402  X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5403  return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5404  }
5405 
5406  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5407  ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5408  for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5409  X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5410  return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5411  }
5412 
5413  if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5414  ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5415  for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5416  X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5417  return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5418  }
5419 
5420  if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5421  ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5422  for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5423  X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5424  return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5425  }
5426 
5427  if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5428  ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5429  ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5430  return setRange(UDiv, SignHint,
5431  ConservativeResult.intersectWith(X.udiv(Y)));
5432  }
5433 
5434  if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5435  ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5436  return setRange(ZExt, SignHint,
5437  ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5438  }
5439 
5440  if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5441  ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5442  return setRange(SExt, SignHint,
5443  ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5444  }
5445 
5446  if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5447  ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5448  return setRange(Trunc, SignHint,
5449