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  isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1731  // Cache knowledge of AR NUW, which is propagated to this
1732  // AddRec.
1733  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1734  // Return the expression with the addrec on the outside.
1735  return getAddRecExpr(
1736  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1737  Depth + 1),
1738  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1739  AR->getNoWrapFlags());
1740  }
1741  } else if (isKnownNegative(Step)) {
1742  const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1743  getSignedRangeMin(Step));
1744  if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1745  isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1746  // Cache knowledge of AR NW, which is propagated to this
1747  // AddRec. Negative step causes unsigned wrap, but it
1748  // still can't self-wrap.
1749  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1750  // Return the expression with the addrec on the outside.
1751  return getAddRecExpr(
1752  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1753  Depth + 1),
1754  getSignExtendExpr(Step, Ty, Depth + 1), L,
1755  AR->getNoWrapFlags());
1756  }
1757  }
1758  }
1759 
1760  if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1761  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1762  return getAddRecExpr(
1763  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1764  getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1765  }
1766  }
1767 
1768  if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1769  // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1770  if (SA->hasNoUnsignedWrap()) {
1771  // If the addition does not unsign overflow then we can, by definition,
1772  // commute the zero extension with the addition operation.
1774  for (const auto *Op : SA->operands())
1775  Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1776  return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1777  }
1778  }
1779 
1780  // The cast wasn't folded; create an explicit cast node.
1781  // Recompute the insert position, as it may have been invalidated.
1782  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1783  SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1784  Op, Ty);
1785  UniqueSCEVs.InsertNode(S, IP);
1786  addToLoopUseLists(S);
1787  return S;
1788 }
1789 
1790 const SCEV *
1792  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1793  "This is not an extending conversion!");
1794  assert(isSCEVable(Ty) &&
1795  "This is not a conversion to a SCEVable type!");
1796  Ty = getEffectiveSCEVType(Ty);
1797 
1798  // Fold if the operand is constant.
1799  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1800  return getConstant(
1801  cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1802 
1803  // sext(sext(x)) --> sext(x)
1804  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1805  return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1806 
1807  // sext(zext(x)) --> zext(x)
1808  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1809  return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1810 
1811  // Before doing any expensive analysis, check to see if we've already
1812  // computed a SCEV for this Op and Ty.
1815  ID.AddPointer(Op);
1816  ID.AddPointer(Ty);
1817  void *IP = nullptr;
1818  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1819  // Limit recursion depth.
1820  if (Depth > MaxExtDepth) {
1821  SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1822  Op, Ty);
1823  UniqueSCEVs.InsertNode(S, IP);
1824  addToLoopUseLists(S);
1825  return S;
1826  }
1827 
1828  // sext(trunc(x)) --> sext(x) or x or trunc(x)
1829  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1830  // It's possible the bits taken off by the truncate were all sign bits. If
1831  // so, we should be able to simplify this further.
1832  const SCEV *X = ST->getOperand();
1833  ConstantRange CR = getSignedRange(X);
1834  unsigned TruncBits = getTypeSizeInBits(ST->getType());
1835  unsigned NewBits = getTypeSizeInBits(Ty);
1836  if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1837  CR.sextOrTrunc(NewBits)))
1838  return getTruncateOrSignExtend(X, Ty);
1839  }
1840 
1841  // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1842  if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1843  if (SA->getNumOperands() == 2) {
1844  auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1845  auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1846  if (SMul && SC1) {
1847  if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1848  const APInt &C1 = SC1->getAPInt();
1849  const APInt &C2 = SC2->getAPInt();
1850  if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1851  C2.ugt(C1) && C2.isPowerOf2())
1852  return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1853  getSignExtendExpr(SMul, Ty, Depth + 1),
1854  SCEV::FlagAnyWrap, Depth + 1);
1855  }
1856  }
1857  }
1858 
1859  // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1860  if (SA->hasNoSignedWrap()) {
1861  // If the addition does not sign overflow then we can, by definition,
1862  // commute the sign extension with the addition operation.
1864  for (const auto *Op : SA->operands())
1865  Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1866  return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1867  }
1868  }
1869  // If the input value is a chrec scev, and we can prove that the value
1870  // did not overflow the old, smaller, value, we can sign extend all of the
1871  // operands (often constants). This allows analysis of something like
1872  // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1873  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1874  if (AR->isAffine()) {
1875  const SCEV *Start = AR->getStart();
1876  const SCEV *Step = AR->getStepRecurrence(*this);
1877  unsigned BitWidth = getTypeSizeInBits(AR->getType());
1878  const Loop *L = AR->getLoop();
1879 
1880  if (!AR->hasNoSignedWrap()) {
1881  auto NewFlags = proveNoWrapViaConstantRanges(AR);
1882  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1883  }
1884 
1885  // If we have special knowledge that this addrec won't overflow,
1886  // we don't need to do any further analysis.
1887  if (AR->hasNoSignedWrap())
1888  return getAddRecExpr(
1889  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1890  getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1891 
1892  // Check whether the backedge-taken count is SCEVCouldNotCompute.
1893  // Note that this serves two purposes: It filters out loops that are
1894  // simply not analyzable, and it covers the case where this code is
1895  // being called from within backedge-taken count analysis, such that
1896  // attempting to ask for the backedge-taken count would likely result
1897  // in infinite recursion. In the later case, the analysis code will
1898  // cope with a conservative value, and it will take care to purge
1899  // that value once it has finished.
1900  const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1901  if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1902  // Manually compute the final value for AR, checking for
1903  // overflow.
1904 
1905  // Check whether the backedge-taken count can be losslessly casted to
1906  // the addrec's type. The count is always unsigned.
1907  const SCEV *CastedMaxBECount =
1908  getTruncateOrZeroExtend(MaxBECount, Start->getType());
1909  const SCEV *RecastedMaxBECount =
1910  getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1911  if (MaxBECount == RecastedMaxBECount) {
1912  Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1913  // Check whether Start+Step*MaxBECount has no signed overflow.
1914  const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1915  SCEV::FlagAnyWrap, Depth + 1);
1916  const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1918  Depth + 1),
1919  WideTy, Depth + 1);
1920  const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1921  const SCEV *WideMaxBECount =
1922  getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1923  const SCEV *OperandExtendedAdd =
1924  getAddExpr(WideStart,
1925  getMulExpr(WideMaxBECount,
1926  getSignExtendExpr(Step, WideTy, Depth + 1),
1927  SCEV::FlagAnyWrap, Depth + 1),
1928  SCEV::FlagAnyWrap, Depth + 1);
1929  if (SAdd == OperandExtendedAdd) {
1930  // Cache knowledge of AR NSW, which is propagated to this AddRec.
1931  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1932  // Return the expression with the addrec on the outside.
1933  return getAddRecExpr(
1934  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1935  Depth + 1),
1936  getSignExtendExpr(Step, Ty, Depth + 1), L,
1937  AR->getNoWrapFlags());
1938  }
1939  // Similar to above, only this time treat the step value as unsigned.
1940  // This covers loops that count up with an unsigned step.
1941  OperandExtendedAdd =
1942  getAddExpr(WideStart,
1943  getMulExpr(WideMaxBECount,
1944  getZeroExtendExpr(Step, WideTy, Depth + 1),
1945  SCEV::FlagAnyWrap, Depth + 1),
1946  SCEV::FlagAnyWrap, Depth + 1);
1947  if (SAdd == OperandExtendedAdd) {
1948  // If AR wraps around then
1949  //
1950  // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1951  // => SAdd != OperandExtendedAdd
1952  //
1953  // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1954  // (SAdd == OperandExtendedAdd => AR is NW)
1955 
1956  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1957 
1958  // Return the expression with the addrec on the outside.
1959  return getAddRecExpr(
1960  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1961  Depth + 1),
1962  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1963  AR->getNoWrapFlags());
1964  }
1965  }
1966  }
1967 
1968  // Normally, in the cases we can prove no-overflow via a
1969  // backedge guarding condition, we can also compute a backedge
1970  // taken count for the loop. The exceptions are assumptions and
1971  // guards present in the loop -- SCEV is not great at exploiting
1972  // these to compute max backedge taken counts, but can still use
1973  // these to prove lack of overflow. Use this fact to avoid
1974  // doing extra work that may not pay off.
1975 
1976  if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1977  !AC.assumptions().empty()) {
1978  // If the backedge is guarded by a comparison with the pre-inc
1979  // value the addrec is safe. Also, if the entry is guarded by
1980  // a comparison with the start value and the backedge is
1981  // guarded by a comparison with the post-inc value, the addrec
1982  // is safe.
1983  ICmpInst::Predicate Pred;
1984  const SCEV *OverflowLimit =
1985  getSignedOverflowLimitForStep(Step, &Pred, this);
1986  if (OverflowLimit &&
1987  (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1988  isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
1989  // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1990  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1991  return getAddRecExpr(
1992  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1993  getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1994  }
1995  }
1996 
1997  // If Start and Step are constants, check if we can apply this
1998  // transformation:
1999  // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2000  auto *SC1 = dyn_cast<SCEVConstant>(Start);
2001  auto *SC2 = dyn_cast<SCEVConstant>(Step);
2002  if (SC1 && SC2) {
2003  const APInt &C1 = SC1->getAPInt();
2004  const APInt &C2 = SC2->getAPInt();
2005  if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2006  C2.isPowerOf2()) {
2007  Start = getSignExtendExpr(Start, Ty, Depth + 1);
2008  const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2009  AR->getNoWrapFlags());
2010  return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2011  SCEV::FlagAnyWrap, Depth + 1);
2012  }
2013  }
2014 
2015  if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2016  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2017  return getAddRecExpr(
2018  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2019  getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2020  }
2021  }
2022 
2023  // If the input value is provably positive and we could not simplify
2024  // away the sext build a zext instead.
2025  if (isKnownNonNegative(Op))
2026  return getZeroExtendExpr(Op, Ty, Depth + 1);
2027 
2028  // The cast wasn't folded; create an explicit cast node.
2029  // Recompute the insert position, as it may have been invalidated.
2030  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2031  SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2032  Op, Ty);
2033  UniqueSCEVs.InsertNode(S, IP);
2034  addToLoopUseLists(S);
2035  return S;
2036 }
2037 
2038 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2039 /// unspecified bits out to the given type.
2041  Type *Ty) {
2042  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2043  "This is not an extending conversion!");
2044  assert(isSCEVable(Ty) &&
2045  "This is not a conversion to a SCEVable type!");
2046  Ty = getEffectiveSCEVType(Ty);
2047 
2048  // Sign-extend negative constants.
2049  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2050  if (SC->getAPInt().isNegative())
2051  return getSignExtendExpr(Op, Ty);
2052 
2053  // Peel off a truncate cast.
2054  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2055  const SCEV *NewOp = T->getOperand();
2056  if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2057  return getAnyExtendExpr(NewOp, Ty);
2058  return getTruncateOrNoop(NewOp, Ty);
2059  }
2060 
2061  // Next try a zext cast. If the cast is folded, use it.
2062  const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2063  if (!isa<SCEVZeroExtendExpr>(ZExt))
2064  return ZExt;
2065 
2066  // Next try a sext cast. If the cast is folded, use it.
2067  const SCEV *SExt = getSignExtendExpr(Op, Ty);
2068  if (!isa<SCEVSignExtendExpr>(SExt))
2069  return SExt;
2070 
2071  // Force the cast to be folded into the operands of an addrec.
2072  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2074  for (const SCEV *Op : AR->operands())
2075  Ops.push_back(getAnyExtendExpr(Op, Ty));
2076  return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2077  }
2078 
2079  // If the expression is obviously signed, use the sext cast value.
2080  if (isa<SCEVSMaxExpr>(Op))
2081  return SExt;
2082 
2083  // Absent any other information, use the zext cast value.
2084  return ZExt;
2085 }
2086 
2087 /// Process the given Ops list, which is a list of operands to be added under
2088 /// the given scale, update the given map. This is a helper function for
2089 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2090 /// that would form an add expression like this:
2091 ///
2092 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2093 ///
2094 /// where A and B are constants, update the map with these values:
2095 ///
2096 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2097 ///
2098 /// and add 13 + A*B*29 to AccumulatedConstant.
2099 /// This will allow getAddRecExpr to produce this:
2100 ///
2101 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2102 ///
2103 /// This form often exposes folding opportunities that are hidden in
2104 /// the original operand list.
2105 ///
2106 /// Return true iff it appears that any interesting folding opportunities
2107 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2108 /// the common case where no interesting opportunities are present, and
2109 /// is also used as a check to avoid infinite recursion.
2110 static bool
2113  APInt &AccumulatedConstant,
2114  const SCEV *const *Ops, size_t NumOperands,
2115  const APInt &Scale,
2116  ScalarEvolution &SE) {
2117  bool Interesting = false;
2118 
2119  // Iterate over the add operands. They are sorted, with constants first.
2120  unsigned i = 0;
2121  while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2122  ++i;
2123  // Pull a buried constant out to the outside.
2124  if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2125  Interesting = true;
2126  AccumulatedConstant += Scale * C->getAPInt();
2127  }
2128 
2129  // Next comes everything else. We're especially interested in multiplies
2130  // here, but they're in the middle, so just visit the rest with one loop.
2131  for (; i != NumOperands; ++i) {
2132  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2133  if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2134  APInt NewScale =
2135  Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2136  if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2137  // A multiplication of a constant with another add; recurse.
2138  const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2139  Interesting |=
2140  CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2141  Add->op_begin(), Add->getNumOperands(),
2142  NewScale, SE);
2143  } else {
2144  // A multiplication of a constant with some other value. Update
2145  // the map.
2146  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2147  const SCEV *Key = SE.getMulExpr(MulOps);
2148  auto Pair = M.insert({Key, NewScale});
2149  if (Pair.second) {
2150  NewOps.push_back(Pair.first->first);
2151  } else {
2152  Pair.first->second += NewScale;
2153  // The map already had an entry for this value, which may indicate
2154  // a folding opportunity.
2155  Interesting = true;
2156  }
2157  }
2158  } else {
2159  // An ordinary operand. Update the map.
2160  std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2161  M.insert({Ops[i], Scale});
2162  if (Pair.second) {
2163  NewOps.push_back(Pair.first->first);
2164  } else {
2165  Pair.first->second += Scale;
2166  // The map already had an entry for this value, which may indicate
2167  // a folding opportunity.
2168  Interesting = true;
2169  }
2170  }
2171  }
2172 
2173  return Interesting;
2174 }
2175 
2176 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2177 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2178 // can't-overflow flags for the operation if possible.
2179 static SCEV::NoWrapFlags
2181  const SmallVectorImpl<const SCEV *> &Ops,
2182  SCEV::NoWrapFlags Flags) {
2183  using namespace std::placeholders;
2184 
2185  using OBO = OverflowingBinaryOperator;
2186 
2187  bool CanAnalyze =
2188  Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2189  (void)CanAnalyze;
2190  assert(CanAnalyze && "don't call from other places!");
2191 
2192  int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2193  SCEV::NoWrapFlags SignOrUnsignWrap =
2194  ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2195 
2196  // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2197  auto IsKnownNonNegative = [&](const SCEV *S) {
2198  return SE->isKnownNonNegative(S);
2199  };
2200 
2201  if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2202  Flags =
2203  ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2204 
2205  SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2206 
2207  if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2208  Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2209 
2210  // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2211  // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2212 
2213  const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2214  if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2216  Instruction::Add, C, OBO::NoSignedWrap);
2217  if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2218  Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2219  }
2220  if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2222  Instruction::Add, C, OBO::NoUnsignedWrap);
2223  if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2224  Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2225  }
2226  }
2227 
2228  return Flags;
2229 }
2230 
2232  return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2233 }
2234 
2235 /// Get a canonical add expression, or something simpler if possible.
2237  SCEV::NoWrapFlags Flags,
2238  unsigned Depth) {
2239  assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2240  "only nuw or nsw allowed");
2241  assert(!Ops.empty() && "Cannot get empty add!");
2242  if (Ops.size() == 1) return Ops[0];
2243 #ifndef NDEBUG
2244  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2245  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2246  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2247  "SCEVAddExpr operand types don't match!");
2248 #endif
2249 
2250  // Sort by complexity, this groups all similar expression types together.
2251  GroupByComplexity(Ops, &LI, DT);
2252 
2253  Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2254 
2255  // If there are any constants, fold them together.
2256  unsigned Idx = 0;
2257  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2258  ++Idx;
2259  assert(Idx < Ops.size());
2260  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2261  // We found two constants, fold them together!
2262  Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2263  if (Ops.size() == 2) return Ops[0];
2264  Ops.erase(Ops.begin()+1); // Erase the folded element
2265  LHSC = cast<SCEVConstant>(Ops[0]);
2266  }
2267 
2268  // If we are left with a constant zero being added, strip it off.
2269  if (LHSC->getValue()->isZero()) {
2270  Ops.erase(Ops.begin());
2271  --Idx;
2272  }
2273 
2274  if (Ops.size() == 1) return Ops[0];
2275  }
2276 
2277  // Limit recursion calls depth.
2278  if (Depth > MaxArithDepth)
2279  return getOrCreateAddExpr(Ops, Flags);
2280 
2281  // Okay, check to see if the same value occurs in the operand list more than
2282  // once. If so, merge them together into an multiply expression. Since we
2283  // sorted the list, these values are required to be adjacent.
2284  Type *Ty = Ops[0]->getType();
2285  bool FoundMatch = false;
2286  for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2287  if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2288  // Scan ahead to count how many equal operands there are.
2289  unsigned Count = 2;
2290  while (i+Count != e && Ops[i+Count] == Ops[i])
2291  ++Count;
2292  // Merge the values into a multiply.
2293  const SCEV *Scale = getConstant(Ty, Count);
2294  const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2295  if (Ops.size() == Count)
2296  return Mul;
2297  Ops[i] = Mul;
2298  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2299  --i; e -= Count - 1;
2300  FoundMatch = true;
2301  }
2302  if (FoundMatch)
2303  return getAddExpr(Ops, Flags, Depth + 1);
2304 
2305  // Check for truncates. If all the operands are truncated from the same
2306  // type, see if factoring out the truncate would permit the result to be
2307  // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2308  // if the contents of the resulting outer trunc fold to something simple.
2309  auto FindTruncSrcType = [&]() -> Type * {
2310  // We're ultimately looking to fold an addrec of truncs and muls of only
2311  // constants and truncs, so if we find any other types of SCEV
2312  // as operands of the addrec then we bail and return nullptr here.
2313  // Otherwise, we return the type of the operand of a trunc that we find.
2314  if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2315  return T->getOperand()->getType();
2316  if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2317  const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2318  if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2319  return T->getOperand()->getType();
2320  }
2321  return nullptr;
2322  };
2323  if (auto *SrcType = FindTruncSrcType()) {
2325  bool Ok = true;
2326  // Check all the operands to see if they can be represented in the
2327  // source type of the truncate.
2328  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2329  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2330  if (T->getOperand()->getType() != SrcType) {
2331  Ok = false;
2332  break;
2333  }
2334  LargeOps.push_back(T->getOperand());
2335  } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2336  LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2337  } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2338  SmallVector<const SCEV *, 8> LargeMulOps;
2339  for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2340  if (const SCEVTruncateExpr *T =
2341  dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2342  if (T->getOperand()->getType() != SrcType) {
2343  Ok = false;
2344  break;
2345  }
2346  LargeMulOps.push_back(T->getOperand());
2347  } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2348  LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2349  } else {
2350  Ok = false;
2351  break;
2352  }
2353  }
2354  if (Ok)
2355  LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2356  } else {
2357  Ok = false;
2358  break;
2359  }
2360  }
2361  if (Ok) {
2362  // Evaluate the expression in the larger type.
2363  const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2364  // If it folds to something simple, use it. Otherwise, don't.
2365  if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2366  return getTruncateExpr(Fold, Ty);
2367  }
2368  }
2369 
2370  // Skip past any other cast SCEVs.
2371  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2372  ++Idx;
2373 
2374  // If there are add operands they would be next.
2375  if (Idx < Ops.size()) {
2376  bool DeletedAdd = false;
2377  while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2378  if (Ops.size() > AddOpsInlineThreshold ||
2379  Add->getNumOperands() > AddOpsInlineThreshold)
2380  break;
2381  // If we have an add, expand the add operands onto the end of the operands
2382  // list.
2383  Ops.erase(Ops.begin()+Idx);
2384  Ops.append(Add->op_begin(), Add->op_end());
2385  DeletedAdd = true;
2386  }
2387 
2388  // If we deleted at least one add, we added operands to the end of the list,
2389  // and they are not necessarily sorted. Recurse to resort and resimplify
2390  // any operands we just acquired.
2391  if (DeletedAdd)
2392  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2393  }
2394 
2395  // Skip over the add expression until we get to a multiply.
2396  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2397  ++Idx;
2398 
2399  // Check to see if there are any folding opportunities present with
2400  // operands multiplied by constant values.
2401  if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2402  uint64_t BitWidth = getTypeSizeInBits(Ty);
2405  APInt AccumulatedConstant(BitWidth, 0);
2406  if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2407  Ops.data(), Ops.size(),
2408  APInt(BitWidth, 1), *this)) {
2409  struct APIntCompare {
2410  bool operator()(const APInt &LHS, const APInt &RHS) const {
2411  return LHS.ult(RHS);
2412  }
2413  };
2414 
2415  // Some interesting folding opportunity is present, so its worthwhile to
2416  // re-generate the operands list. Group the operands by constant scale,
2417  // to avoid multiplying by the same constant scale multiple times.
2418  std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2419  for (const SCEV *NewOp : NewOps)
2420  MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2421  // Re-generate the operands list.
2422  Ops.clear();
2423  if (AccumulatedConstant != 0)
2424  Ops.push_back(getConstant(AccumulatedConstant));
2425  for (auto &MulOp : MulOpLists)
2426  if (MulOp.first != 0)
2427  Ops.push_back(getMulExpr(
2428  getConstant(MulOp.first),
2429  getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2430  SCEV::FlagAnyWrap, Depth + 1));
2431  if (Ops.empty())
2432  return getZero(Ty);
2433  if (Ops.size() == 1)
2434  return Ops[0];
2435  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2436  }
2437  }
2438 
2439  // If we are adding something to a multiply expression, make sure the
2440  // something is not already an operand of the multiply. If so, merge it into
2441  // the multiply.
2442  for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2443  const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2444  for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2445  const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2446  if (isa<SCEVConstant>(MulOpSCEV))
2447  continue;
2448  for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2449  if (MulOpSCEV == Ops[AddOp]) {
2450  // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2451  const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2452  if (Mul->getNumOperands() != 2) {
2453  // If the multiply has more than two operands, we must get the
2454  // Y*Z term.
2455  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2456  Mul->op_begin()+MulOp);
2457  MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2458  InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2459  }
2460  SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2461  const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2462  const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2463  SCEV::FlagAnyWrap, Depth + 1);
2464  if (Ops.size() == 2) return OuterMul;
2465  if (AddOp < Idx) {
2466  Ops.erase(Ops.begin()+AddOp);
2467  Ops.erase(Ops.begin()+Idx-1);
2468  } else {
2469  Ops.erase(Ops.begin()+Idx);
2470  Ops.erase(Ops.begin()+AddOp-1);
2471  }
2472  Ops.push_back(OuterMul);
2473  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2474  }
2475 
2476  // Check this multiply against other multiplies being added together.
2477  for (unsigned OtherMulIdx = Idx+1;
2478  OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2479  ++OtherMulIdx) {
2480  const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2481  // If MulOp occurs in OtherMul, we can fold the two multiplies
2482  // together.
2483  for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2484  OMulOp != e; ++OMulOp)
2485  if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2486  // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2487  const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2488  if (Mul->getNumOperands() != 2) {
2489  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2490  Mul->op_begin()+MulOp);
2491  MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2492  InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2493  }
2494  const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2495  if (OtherMul->getNumOperands() != 2) {
2496  SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2497  OtherMul->op_begin()+OMulOp);
2498  MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2499  InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2500  }
2501  SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2502  const SCEV *InnerMulSum =
2503  getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2504  const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2505  SCEV::FlagAnyWrap, Depth + 1);
2506  if (Ops.size() == 2) return OuterMul;
2507  Ops.erase(Ops.begin()+Idx);
2508  Ops.erase(Ops.begin()+OtherMulIdx-1);
2509  Ops.push_back(OuterMul);
2510  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2511  }
2512  }
2513  }
2514  }
2515 
2516  // If there are any add recurrences in the operands list, see if any other
2517  // added values are loop invariant. If so, we can fold them into the
2518  // recurrence.
2519  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2520  ++Idx;
2521 
2522  // Scan over all recurrences, trying to fold loop invariants into them.
2523  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2524  // Scan all of the other operands to this add and add them to the vector if
2525  // they are loop invariant w.r.t. the recurrence.
2527  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2528  const Loop *AddRecLoop = AddRec->getLoop();
2529  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2530  if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2531  LIOps.push_back(Ops[i]);
2532  Ops.erase(Ops.begin()+i);
2533  --i; --e;
2534  }
2535 
2536  // If we found some loop invariants, fold them into the recurrence.
2537  if (!LIOps.empty()) {
2538  // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2539  LIOps.push_back(AddRec->getStart());
2540 
2541  SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2542  AddRec->op_end());
2543  // This follows from the fact that the no-wrap flags on the outer add
2544  // expression are applicable on the 0th iteration, when the add recurrence
2545  // will be equal to its start value.
2546  AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2547 
2548  // Build the new addrec. Propagate the NUW and NSW flags if both the
2549  // outer add and the inner addrec are guaranteed to have no overflow.
2550  // Always propagate NW.
2551  Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2552  const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2553 
2554  // If all of the other operands were loop invariant, we are done.
2555  if (Ops.size() == 1) return NewRec;
2556 
2557  // Otherwise, add the folded AddRec by the non-invariant parts.
2558  for (unsigned i = 0;; ++i)
2559  if (Ops[i] == AddRec) {
2560  Ops[i] = NewRec;
2561  break;
2562  }
2563  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2564  }
2565 
2566  // Okay, if there weren't any loop invariants to be folded, check to see if
2567  // there are multiple AddRec's with the same loop induction variable being
2568  // added together. If so, we can fold them.
2569  for (unsigned OtherIdx = Idx+1;
2570  OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2571  ++OtherIdx) {
2572  // We expect the AddRecExpr's to be sorted in reverse dominance order,
2573  // so that the 1st found AddRecExpr is dominated by all others.
2574  assert(DT.dominates(
2575  cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2576  AddRec->getLoop()->getHeader()) &&
2577  "AddRecExprs are not sorted in reverse dominance order?");
2578  if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2579  // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2580  SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2581  AddRec->op_end());
2582  for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2583  ++OtherIdx) {
2584  const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2585  if (OtherAddRec->getLoop() == AddRecLoop) {
2586  for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2587  i != e; ++i) {
2588  if (i >= AddRecOps.size()) {
2589  AddRecOps.append(OtherAddRec->op_begin()+i,
2590  OtherAddRec->op_end());
2591  break;
2592  }
2593  SmallVector<const SCEV *, 2> TwoOps = {
2594  AddRecOps[i], OtherAddRec->getOperand(i)};
2595  AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2596  }
2597  Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2598  }
2599  }
2600  // Step size has changed, so we cannot guarantee no self-wraparound.
2601  Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2602  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2603  }
2604  }
2605 
2606  // Otherwise couldn't fold anything into this recurrence. Move onto the
2607  // next one.
2608  }
2609 
2610  // Okay, it looks like we really DO need an add expr. Check to see if we
2611  // already have one, otherwise create a new one.
2612  return getOrCreateAddExpr(Ops, Flags);
2613 }
2614 
2615 const SCEV *
2616 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2617  SCEV::NoWrapFlags Flags) {
2619  ID.AddInteger(scAddExpr);
2620  for (const SCEV *Op : Ops)
2621  ID.AddPointer(Op);
2622  void *IP = nullptr;
2623  SCEVAddExpr *S =
2624  static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2625  if (!S) {
2626  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2627  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2628  S = new (SCEVAllocator)
2629  SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2630  UniqueSCEVs.InsertNode(S, IP);
2631  addToLoopUseLists(S);
2632  }
2633  S->setNoWrapFlags(Flags);
2634  return S;
2635 }
2636 
2637 const SCEV *
2638 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2639  SCEV::NoWrapFlags Flags) {
2641  ID.AddInteger(scMulExpr);
2642  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2643  ID.AddPointer(Ops[i]);
2644  void *IP = nullptr;
2645  SCEVMulExpr *S =
2646  static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2647  if (!S) {
2648  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2649  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2650  S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2651  O, Ops.size());
2652  UniqueSCEVs.InsertNode(S, IP);
2653  addToLoopUseLists(S);
2654  }
2655  S->setNoWrapFlags(Flags);
2656  return S;
2657 }
2658 
2659 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2660  uint64_t k = i*j;
2661  if (j > 1 && k / j != i) Overflow = true;
2662  return k;
2663 }
2664 
2665 /// Compute the result of "n choose k", the binomial coefficient. If an
2666 /// intermediate computation overflows, Overflow will be set and the return will
2667 /// be garbage. Overflow is not cleared on absence of overflow.
2668 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2669  // We use the multiplicative formula:
2670  // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2671  // At each iteration, we take the n-th term of the numeral and divide by the
2672  // (k-n)th term of the denominator. This division will always produce an
2673  // integral result, and helps reduce the chance of overflow in the
2674  // intermediate computations. However, we can still overflow even when the
2675  // final result would fit.
2676 
2677  if (n == 0 || n == k) return 1;
2678  if (k > n) return 0;
2679 
2680  if (k > n/2)
2681  k = n-k;
2682 
2683  uint64_t r = 1;
2684  for (uint64_t i = 1; i <= k; ++i) {
2685  r = umul_ov(r, n-(i-1), Overflow);
2686  r /= i;
2687  }
2688  return r;
2689 }
2690 
2691 /// Determine if any of the operands in this SCEV are a constant or if
2692 /// any of the add or multiply expressions in this SCEV contain a constant.
2693 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2694  struct FindConstantInAddMulChain {
2695  bool FoundConstant = false;
2696 
2697  bool follow(const SCEV *S) {
2698  FoundConstant |= isa<SCEVConstant>(S);
2699  return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2700  }
2701 
2702  bool isDone() const {
2703  return FoundConstant;
2704  }
2705  };
2706 
2707  FindConstantInAddMulChain F;
2709  ST.visitAll(StartExpr);
2710  return F.FoundConstant;
2711 }
2712 
2713 /// Get a canonical multiply expression, or something simpler if possible.
2715  SCEV::NoWrapFlags Flags,
2716  unsigned Depth) {
2717  assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2718  "only nuw or nsw allowed");
2719  assert(!Ops.empty() && "Cannot get empty mul!");
2720  if (Ops.size() == 1) return Ops[0];
2721 #ifndef NDEBUG
2722  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2723  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2724  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2725  "SCEVMulExpr operand types don't match!");
2726 #endif
2727 
2728  // Sort by complexity, this groups all similar expression types together.
2729  GroupByComplexity(Ops, &LI, DT);
2730 
2731  Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2732 
2733  // Limit recursion calls depth.
2734  if (Depth > MaxArithDepth)
2735  return getOrCreateMulExpr(Ops, Flags);
2736 
2737  // If there are any constants, fold them together.
2738  unsigned Idx = 0;
2739  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2740 
2741  // C1*(C2+V) -> C1*C2 + C1*V
2742  if (Ops.size() == 2)
2743  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2744  // If any of Add's ops are Adds or Muls with a constant,
2745  // apply this transformation as well.
2746  if (Add->getNumOperands() == 2)
2747  // TODO: There are some cases where this transformation is not
2748  // profitable, for example:
2749  // Add = (C0 + X) * Y + Z.
2750  // Maybe the scope of this transformation should be narrowed down.
2752  return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2753  SCEV::FlagAnyWrap, Depth + 1),
2754  getMulExpr(LHSC, Add->getOperand(1),
2755  SCEV::FlagAnyWrap, Depth + 1),
2756  SCEV::FlagAnyWrap, Depth + 1);
2757 
2758  ++Idx;
2759  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2760  // We found two constants, fold them together!
2761  ConstantInt *Fold =
2762  ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2763  Ops[0] = getConstant(Fold);
2764  Ops.erase(Ops.begin()+1); // Erase the folded element
2765  if (Ops.size() == 1) return Ops[0];
2766  LHSC = cast<SCEVConstant>(Ops[0]);
2767  }
2768 
2769  // If we are left with a constant one being multiplied, strip it off.
2770  if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2771  Ops.erase(Ops.begin());
2772  --Idx;
2773  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2774  // If we have a multiply of zero, it will always be zero.
2775  return Ops[0];
2776  } else if (Ops[0]->isAllOnesValue()) {
2777  // If we have a mul by -1 of an add, try distributing the -1 among the
2778  // add operands.
2779  if (Ops.size() == 2) {
2780  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2782  bool AnyFolded = false;
2783  for (const SCEV *AddOp : Add->operands()) {
2784  const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2785  Depth + 1);
2786  if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2787  NewOps.push_back(Mul);
2788  }
2789  if (AnyFolded)
2790  return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2791  } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2792  // Negation preserves a recurrence's no self-wrap property.
2794  for (const SCEV *AddRecOp : AddRec->operands())
2795  Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2796  Depth + 1));
2797 
2798  return getAddRecExpr(Operands, AddRec->getLoop(),
2799  AddRec->getNoWrapFlags(SCEV::FlagNW));
2800  }
2801  }
2802  }
2803 
2804  if (Ops.size() == 1)
2805  return Ops[0];
2806  }
2807 
2808  // Skip over the add expression until we get to a multiply.
2809  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2810  ++Idx;
2811 
2812  // If there are mul operands inline them all into this expression.
2813  if (Idx < Ops.size()) {
2814  bool DeletedMul = false;
2815  while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2816  if (Ops.size() > MulOpsInlineThreshold)
2817  break;
2818  // If we have an mul, expand the mul operands onto the end of the
2819  // operands list.
2820  Ops.erase(Ops.begin()+Idx);
2821  Ops.append(Mul->op_begin(), Mul->op_end());
2822  DeletedMul = true;
2823  }
2824 
2825  // If we deleted at least one mul, we added operands to the end of the
2826  // list, and they are not necessarily sorted. Recurse to resort and
2827  // resimplify any operands we just acquired.
2828  if (DeletedMul)
2829  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2830  }
2831 
2832  // If there are any add recurrences in the operands list, see if any other
2833  // added values are loop invariant. If so, we can fold them into the
2834  // recurrence.
2835  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2836  ++Idx;
2837 
2838  // Scan over all recurrences, trying to fold loop invariants into them.
2839  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2840  // Scan all of the other operands to this mul and add them to the vector
2841  // if they are loop invariant w.r.t. the recurrence.
2843  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2844  const Loop *AddRecLoop = AddRec->getLoop();
2845  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2846  if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2847  LIOps.push_back(Ops[i]);
2848  Ops.erase(Ops.begin()+i);
2849  --i; --e;
2850  }
2851 
2852  // If we found some loop invariants, fold them into the recurrence.
2853  if (!LIOps.empty()) {
2854  // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2856  NewOps.reserve(AddRec->getNumOperands());
2857  const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2858  for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2859  NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2860  SCEV::FlagAnyWrap, Depth + 1));
2861 
2862  // Build the new addrec. Propagate the NUW and NSW flags if both the
2863  // outer mul and the inner addrec are guaranteed to have no overflow.
2864  //
2865  // No self-wrap cannot be guaranteed after changing the step size, but
2866  // will be inferred if either NUW or NSW is true.
2867  Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2868  const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2869 
2870  // If all of the other operands were loop invariant, we are done.
2871  if (Ops.size() == 1) return NewRec;
2872 
2873  // Otherwise, multiply the folded AddRec by the non-invariant parts.
2874  for (unsigned i = 0;; ++i)
2875  if (Ops[i] == AddRec) {
2876  Ops[i] = NewRec;
2877  break;
2878  }
2879  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2880  }
2881 
2882  // Okay, if there weren't any loop invariants to be folded, check to see
2883  // if there are multiple AddRec's with the same loop induction variable
2884  // being multiplied together. If so, we can fold them.
2885 
2886  // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2887  // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2888  // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2889  // ]]],+,...up to x=2n}.
2890  // Note that the arguments to choose() are always integers with values
2891  // known at compile time, never SCEV objects.
2892  //
2893  // The implementation avoids pointless extra computations when the two
2894  // addrec's are of different length (mathematically, it's equivalent to
2895  // an infinite stream of zeros on the right).
2896  bool OpsModified = false;
2897  for (unsigned OtherIdx = Idx+1;
2898  OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2899  ++OtherIdx) {
2900  const SCEVAddRecExpr *OtherAddRec =
2901  dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2902  if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2903  continue;
2904 
2905  // Limit max number of arguments to avoid creation of unreasonably big
2906  // SCEVAddRecs with very complex operands.
2907  if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2908  MaxAddRecSize)
2909  continue;
2910 
2911  bool Overflow = false;
2912  Type *Ty = AddRec->getType();
2913  bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2914  SmallVector<const SCEV*, 7> AddRecOps;
2915  for (int x = 0, xe = AddRec->getNumOperands() +
2916  OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2917  const SCEV *Term = getZero(Ty);
2918  for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2919  uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2920  for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2921  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2922  z < ze && !Overflow; ++z) {
2923  uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2924  uint64_t Coeff;
2925  if (LargerThan64Bits)
2926  Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2927  else
2928  Coeff = Coeff1*Coeff2;
2929  const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2930  const SCEV *Term1 = AddRec->getOperand(y-z);
2931  const SCEV *Term2 = OtherAddRec->getOperand(z);
2932  Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2933  SCEV::FlagAnyWrap, Depth + 1),
2934  SCEV::FlagAnyWrap, Depth + 1);
2935  }
2936  }
2937  AddRecOps.push_back(Term);
2938  }
2939  if (!Overflow) {
2940  const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2942  if (Ops.size() == 2) return NewAddRec;
2943  Ops[Idx] = NewAddRec;
2944  Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2945  OpsModified = true;
2946  AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2947  if (!AddRec)
2948  break;
2949  }
2950  }
2951  if (OpsModified)
2952  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2953 
2954  // Otherwise couldn't fold anything into this recurrence. Move onto the
2955  // next one.
2956  }
2957 
2958  // Okay, it looks like we really DO need an mul expr. Check to see if we
2959  // already have one, otherwise create a new one.
2960  return getOrCreateMulExpr(Ops, Flags);
2961 }
2962 
2963 /// Represents an unsigned remainder expression based on unsigned division.
2965  const SCEV *RHS) {
2966  assert(getEffectiveSCEVType(LHS->getType()) ==
2967  getEffectiveSCEVType(RHS->getType()) &&
2968  "SCEVURemExpr operand types don't match!");
2969 
2970  // Short-circuit easy cases
2971  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2972  // If constant is one, the result is trivial
2973  if (RHSC->getValue()->isOne())
2974  return getZero(LHS->getType()); // X urem 1 --> 0
2975 
2976  // If constant is a power of two, fold into a zext(trunc(LHS)).
2977  if (RHSC->getAPInt().isPowerOf2()) {
2978  Type *FullTy = LHS->getType();
2979  Type *TruncTy =
2980  IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
2981  return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
2982  }
2983  }
2984 
2985  // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
2986  const SCEV *UDiv = getUDivExpr(LHS, RHS);
2987  const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
2988  return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
2989 }
2990 
2991 /// Get a canonical unsigned division expression, or something simpler if
2992 /// possible.
2994  const SCEV *RHS) {
2995  assert(getEffectiveSCEVType(LHS->getType()) ==
2996  getEffectiveSCEVType(RHS->getType()) &&
2997  "SCEVUDivExpr operand types don't match!");
2998 
2999  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3000  if (RHSC->getValue()->isOne())
3001  return LHS; // X udiv 1 --> x
3002  // If the denominator is zero, the result of the udiv is undefined. Don't
3003  // try to analyze it, because the resolution chosen here may differ from
3004  // the resolution chosen in other parts of the compiler.
3005  if (!RHSC->getValue()->isZero()) {
3006  // Determine if the division can be folded into the operands of
3007  // its operands.
3008  // TODO: Generalize this to non-constants by using known-bits information.
3009  Type *Ty = LHS->getType();
3010  unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3011  unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3012  // For non-power-of-two values, effectively round the value up to the
3013  // nearest power of two.
3014  if (!RHSC->getAPInt().isPowerOf2())
3015  ++MaxShiftAmt;
3016  IntegerType *ExtTy =
3017  IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3018  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3019  if (const SCEVConstant *Step =
3020  dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3021  // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3022  const APInt &StepInt = Step->getAPInt();
3023  const APInt &DivInt = RHSC->getAPInt();
3024  if (!StepInt.urem(DivInt) &&
3025  getZeroExtendExpr(AR, ExtTy) ==
3026  getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3027  getZeroExtendExpr(Step, ExtTy),
3028  AR->getLoop(), SCEV::FlagAnyWrap)) {
3030  for (const SCEV *Op : AR->operands())
3031  Operands.push_back(getUDivExpr(Op, RHS));
3032  return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3033  }
3034  /// Get a canonical UDivExpr for a recurrence.
3035  /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3036  // We can currently only fold X%N if X is constant.
3037  const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3038  if (StartC && !DivInt.urem(StepInt) &&
3039  getZeroExtendExpr(AR, ExtTy) ==
3040  getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3041  getZeroExtendExpr(Step, ExtTy),
3042  AR->getLoop(), SCEV::FlagAnyWrap)) {
3043  const APInt &StartInt = StartC->getAPInt();
3044  const APInt &StartRem = StartInt.urem(StepInt);
3045  if (StartRem != 0)
3046  LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3047  AR->getLoop(), SCEV::FlagNW);
3048  }
3049  }
3050  // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3051  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3053  for (const SCEV *Op : M->operands())
3054  Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3055  if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3056  // Find an operand that's safely divisible.
3057  for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3058  const SCEV *Op = M->getOperand(i);
3059  const SCEV *Div = getUDivExpr(Op, RHSC);
3060  if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3061  Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3062  M->op_end());
3063  Operands[i] = Div;
3064  return getMulExpr(Operands);
3065  }
3066  }
3067  }
3068  // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3069  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3071  for (const SCEV *Op : A->operands())
3072  Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3073  if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3074  Operands.clear();
3075  for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3076  const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3077  if (isa<SCEVUDivExpr>(Op) ||
3078  getMulExpr(Op, RHS) != A->getOperand(i))
3079  break;
3080  Operands.push_back(Op);
3081  }
3082  if (Operands.size() == A->getNumOperands())
3083  return getAddExpr(Operands);
3084  }
3085  }
3086 
3087  // Fold if both operands are constant.
3088  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3089  Constant *LHSCV = LHSC->getValue();
3090  Constant *RHSCV = RHSC->getValue();
3091  return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3092  RHSCV)));
3093  }
3094  }
3095  }
3096 
3098  ID.AddInteger(scUDivExpr);
3099  ID.AddPointer(LHS);
3100  ID.AddPointer(RHS);
3101  void *IP = nullptr;
3102  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3103  SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3104  LHS, RHS);
3105  UniqueSCEVs.InsertNode(S, IP);
3106  addToLoopUseLists(S);
3107  return S;
3108 }
3109 
3110 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3111  APInt A = C1->getAPInt().abs();
3112  APInt B = C2->getAPInt().abs();
3113  uint32_t ABW = A.getBitWidth();
3114  uint32_t BBW = B.getBitWidth();
3115 
3116  if (ABW > BBW)
3117  B = B.zext(ABW);
3118  else if (ABW < BBW)
3119  A = A.zext(BBW);
3120 
3121  return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3122 }
3123 
3124 /// Get a canonical unsigned division expression, or something simpler if
3125 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3126 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3127 /// it's not exact because the udiv may be clearing bits.
3129  const SCEV *RHS) {
3130  // TODO: we could try to find factors in all sorts of things, but for now we
3131  // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3132  // end of this file for inspiration.
3133 
3134  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3135  if (!Mul || !Mul->hasNoUnsignedWrap())
3136  return getUDivExpr(LHS, RHS);
3137 
3138  if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3139  // If the mulexpr multiplies by a constant, then that constant must be the
3140  // first element of the mulexpr.
3141  if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3142  if (LHSCst == RHSCst) {
3144  Operands.append(Mul->op_begin() + 1, Mul->op_end());
3145  return getMulExpr(Operands);
3146  }
3147 
3148  // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3149  // that there's a factor provided by one of the other terms. We need to
3150  // check.
3151  APInt Factor = gcd(LHSCst, RHSCst);
3152  if (!Factor.isIntN(1)) {
3153  LHSCst =
3154  cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3155  RHSCst =
3156  cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3158  Operands.push_back(LHSCst);
3159  Operands.append(Mul->op_begin() + 1, Mul->op_end());
3160  LHS = getMulExpr(Operands);
3161  RHS = RHSCst;
3162  Mul = dyn_cast<SCEVMulExpr>(LHS);
3163  if (!Mul)
3164  return getUDivExactExpr(LHS, RHS);
3165  }
3166  }
3167  }
3168 
3169  for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3170  if (Mul->getOperand(i) == RHS) {
3172  Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3173  Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3174  return getMulExpr(Operands);
3175  }
3176  }
3177 
3178  return getUDivExpr(LHS, RHS);
3179 }
3180 
3181 /// Get an add recurrence expression for the specified loop. Simplify the
3182 /// expression as much as possible.
3183 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3184  const Loop *L,
3185  SCEV::NoWrapFlags Flags) {
3187  Operands.push_back(Start);
3188  if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3189  if (StepChrec->getLoop() == L) {
3190  Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3191  return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3192  }
3193 
3194  Operands.push_back(Step);
3195  return getAddRecExpr(Operands, L, Flags);
3196 }
3197 
3198 /// Get an add recurrence expression for the specified loop. Simplify the
3199 /// expression as much as possible.
3200 const SCEV *
3202  const Loop *L, SCEV::NoWrapFlags Flags) {
3203  if (Operands.size() == 1) return Operands[0];
3204 #ifndef NDEBUG
3205  Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3206  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3207  assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3208  "SCEVAddRecExpr operand types don't match!");
3209  for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3210  assert(isLoopInvariant(Operands[i], L) &&
3211  "SCEVAddRecExpr operand is not loop-invariant!");
3212 #endif
3213 
3214  if (Operands.back()->isZero()) {
3215  Operands.pop_back();
3216  return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3217  }
3218 
3219  // It's tempting to want to call getMaxBackedgeTakenCount count here and
3220  // use that information to infer NUW and NSW flags. However, computing a
3221  // BE count requires calling getAddRecExpr, so we may not yet have a
3222  // meaningful BE count at this point (and if we don't, we'd be stuck
3223  // with a SCEVCouldNotCompute as the cached BE count).
3224 
3225  Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3226 
3227  // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3228  if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3229  const Loop *NestedLoop = NestedAR->getLoop();
3230  if (L->contains(NestedLoop)
3231  ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3232  : (!NestedLoop->contains(L) &&
3233  DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3234  SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3235  NestedAR->op_end());
3236  Operands[0] = NestedAR->getStart();
3237  // AddRecs require their operands be loop-invariant with respect to their
3238  // loops. Don't perform this transformation if it would break this
3239  // requirement.
3240  bool AllInvariant = all_of(
3241  Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3242 
3243  if (AllInvariant) {
3244  // Create a recurrence for the outer loop with the same step size.
3245  //
3246  // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3247  // inner recurrence has the same property.
3248  SCEV::NoWrapFlags OuterFlags =
3249  maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3250 
3251  NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3252  AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3253  return isLoopInvariant(Op, NestedLoop);
3254  });
3255 
3256  if (AllInvariant) {
3257  // Ok, both add recurrences are valid after the transformation.
3258  //
3259  // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3260  // the outer recurrence has the same property.
3261  SCEV::NoWrapFlags InnerFlags =
3262  maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3263  return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3264  }
3265  }
3266  // Reset Operands to its original state.
3267  Operands[0] = NestedAR;
3268  }
3269  }
3270 
3271  // Okay, it looks like we really DO need an addrec expr. Check to see if we
3272  // already have one, otherwise create a new one.
3275  for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3276  ID.AddPointer(Operands[i]);
3277  ID.AddPointer(L);
3278  void *IP = nullptr;
3279  SCEVAddRecExpr *S =
3280  static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3281  if (!S) {
3282  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3283  std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3284  S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3285  O, Operands.size(), L);
3286  UniqueSCEVs.InsertNode(S, IP);
3287  addToLoopUseLists(S);
3288  }
3289  S->setNoWrapFlags(Flags);
3290  return S;
3291 }
3292 
3293 const SCEV *
3295  const SmallVectorImpl<const SCEV *> &IndexExprs) {
3296  const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3297  // getSCEV(Base)->getType() has the same address space as Base->getType()
3298  // because SCEV::getType() preserves the address space.
3299  Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3300  // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3301  // instruction to its SCEV, because the Instruction may be guarded by control
3302  // flow and the no-overflow bits may not be valid for the expression in any
3303  // context. This can be fixed similarly to how these flags are handled for
3304  // adds.
3307 
3308  const SCEV *TotalOffset = getZero(IntPtrTy);
3309  // The array size is unimportant. The first thing we do on CurTy is getting
3310  // its element type.
3311  Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3312  for (const SCEV *IndexExpr : IndexExprs) {
3313  // Compute the (potentially symbolic) offset in bytes for this index.
3314  if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3315  // For a struct, add the member offset.
3316  ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3317  unsigned FieldNo = Index->getZExtValue();
3318  const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3319 
3320  // Add the field offset to the running total offset.
3321  TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3322 
3323  // Update CurTy to the type of the field at Index.
3324  CurTy = STy->getTypeAtIndex(Index);
3325  } else {
3326  // Update CurTy to its element type.
3327  CurTy = cast<SequentialType>(CurTy)->getElementType();
3328  // For an array, add the element offset, explicitly scaled.
3329  const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3330  // Getelementptr indices are signed.
3331  IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3332 
3333  // Multiply the index by the element size to compute the element offset.
3334  const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3335 
3336  // Add the element offset to the running total offset.
3337  TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3338  }
3339  }
3340 
3341  // Add the total offset from all the GEP indices to the base.
3342  return getAddExpr(BaseExpr, TotalOffset, Wrap);
3343 }
3344 
3346  const SCEV *RHS) {
3347  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3348  return getSMaxExpr(Ops);
3349 }
3350 
3351 const SCEV *
3353  assert(!Ops.empty() && "Cannot get empty smax!");
3354  if (Ops.size() == 1) return Ops[0];
3355 #ifndef NDEBUG
3356  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3357  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3358  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3359  "SCEVSMaxExpr operand types don't match!");
3360 #endif
3361 
3362  // Sort by complexity, this groups all similar expression types together.
3363  GroupByComplexity(Ops, &LI, DT);
3364 
3365  // If there are any constants, fold them together.
3366  unsigned Idx = 0;
3367  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3368  ++Idx;
3369  assert(Idx < Ops.size());
3370  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3371  // We found two constants, fold them together!
3372  ConstantInt *Fold = ConstantInt::get(
3373  getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3374  Ops[0] = getConstant(Fold);
3375  Ops.erase(Ops.begin()+1); // Erase the folded element
3376  if (Ops.size() == 1) return Ops[0];
3377  LHSC = cast<SCEVConstant>(Ops[0]);
3378  }
3379 
3380  // If we are left with a constant minimum-int, strip it off.
3381  if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3382  Ops.erase(Ops.begin());
3383  --Idx;
3384  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3385  // If we have an smax with a constant maximum-int, it will always be
3386  // maximum-int.
3387  return Ops[0];
3388  }
3389 
3390  if (Ops.size() == 1) return Ops[0];
3391  }
3392 
3393  // Find the first SMax
3394  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3395  ++Idx;
3396 
3397  // Check to see if one of the operands is an SMax. If so, expand its operands
3398  // onto our operand list, and recurse to simplify.
3399  if (Idx < Ops.size()) {
3400  bool DeletedSMax = false;
3401  while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3402  Ops.erase(Ops.begin()+Idx);
3403  Ops.append(SMax->op_begin(), SMax->op_end());
3404  DeletedSMax = true;
3405  }
3406 
3407  if (DeletedSMax)
3408  return getSMaxExpr(Ops);
3409  }
3410 
3411  // Okay, check to see if the same value occurs in the operand list twice. If
3412  // so, delete one. Since we sorted the list, these values are required to
3413  // be adjacent.
3414  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3415  // X smax Y smax Y --> X smax Y
3416  // X smax Y --> X, if X is always greater than Y
3417  if (Ops[i] == Ops[i+1] ||
3418  isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3419  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3420  --i; --e;
3421  } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3422  Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3423  --i; --e;
3424  }
3425 
3426  if (Ops.size() == 1) return Ops[0];
3427 
3428  assert(!Ops.empty() && "Reduced smax down to nothing!");
3429 
3430  // Okay, it looks like we really DO need an smax expr. Check to see if we
3431  // already have one, otherwise create a new one.
3433  ID.AddInteger(scSMaxExpr);
3434  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3435  ID.AddPointer(Ops[i]);
3436  void *IP = nullptr;
3437  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3438  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3439  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3440  SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3441  O, Ops.size());
3442  UniqueSCEVs.InsertNode(S, IP);
3443  addToLoopUseLists(S);
3444  return S;
3445 }
3446 
3448  const SCEV *RHS) {
3449  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3450  return getUMaxExpr(Ops);
3451 }
3452 
3453 const SCEV *
3455  assert(!Ops.empty() && "Cannot get empty umax!");
3456  if (Ops.size() == 1) return Ops[0];
3457 #ifndef NDEBUG
3458  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3459  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3460  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3461  "SCEVUMaxExpr operand types don't match!");
3462 #endif
3463 
3464  // Sort by complexity, this groups all similar expression types together.
3465  GroupByComplexity(Ops, &LI, DT);
3466 
3467  // If there are any constants, fold them together.
3468  unsigned Idx = 0;
3469  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3470  ++Idx;
3471  assert(Idx < Ops.size());
3472  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3473  // We found two constants, fold them together!
3474  ConstantInt *Fold = ConstantInt::get(
3475  getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3476  Ops[0] = getConstant(Fold);
3477  Ops.erase(Ops.begin()+1); // Erase the folded element
3478  if (Ops.size() == 1) return Ops[0];
3479  LHSC = cast<SCEVConstant>(Ops[0]);
3480  }
3481 
3482  // If we are left with a constant minimum-int, strip it off.
3483  if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3484  Ops.erase(Ops.begin());
3485  --Idx;
3486  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3487  // If we have an umax with a constant maximum-int, it will always be
3488  // maximum-int.
3489  return Ops[0];
3490  }
3491 
3492  if (Ops.size() == 1) return Ops[0];
3493  }
3494 
3495  // Find the first UMax
3496  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3497  ++Idx;
3498 
3499  // Check to see if one of the operands is a UMax. If so, expand its operands
3500  // onto our operand list, and recurse to simplify.
3501  if (Idx < Ops.size()) {
3502  bool DeletedUMax = false;
3503  while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3504  Ops.erase(Ops.begin()+Idx);
3505  Ops.append(UMax->op_begin(), UMax->op_end());
3506  DeletedUMax = true;
3507  }
3508 
3509  if (DeletedUMax)
3510  return getUMaxExpr(Ops);
3511  }
3512 
3513  // Okay, check to see if the same value occurs in the operand list twice. If
3514  // so, delete one. Since we sorted the list, these values are required to
3515  // be adjacent.
3516  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3517  // X umax Y umax Y --> X umax Y
3518  // X umax Y --> X, if X is always greater than Y
3519  if (Ops[i] == Ops[i+1] ||
3520  isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3521  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3522  --i; --e;
3523  } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3524  Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3525  --i; --e;
3526  }
3527 
3528  if (Ops.size() == 1) return Ops[0];
3529 
3530  assert(!Ops.empty() && "Reduced umax down to nothing!");
3531 
3532  // Okay, it looks like we really DO need a umax expr. Check to see if we
3533  // already have one, otherwise create a new one.
3535  ID.AddInteger(scUMaxExpr);
3536  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3537  ID.AddPointer(Ops[i]);
3538  void *IP = nullptr;
3539  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3540  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3541  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3542  SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3543  O, Ops.size());
3544  UniqueSCEVs.InsertNode(S, IP);
3545  addToLoopUseLists(S);
3546  return S;
3547 }
3548 
3550  const SCEV *RHS) {
3551  // ~smax(~x, ~y) == smin(x, y).
3552  return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3553 }
3554 
3556  const SCEV *RHS) {
3557  // ~umax(~x, ~y) == umin(x, y)
3558  return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3559 }
3560 
3561 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3562  // We can bypass creating a target-independent
3563  // constant expression and then folding it back into a ConstantInt.
3564  // This is just a compile-time optimization.
3565  return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3566 }
3567 
3569  StructType *STy,
3570  unsigned FieldNo) {
3571  // We can bypass creating a target-independent
3572  // constant expression and then folding it back into a ConstantInt.
3573  // This is just a compile-time optimization.
3574  return getConstant(
3575  IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3576 }
3577 
3579  // Don't attempt to do anything other than create a SCEVUnknown object
3580  // here. createSCEV only calls getUnknown after checking for all other
3581  // interesting possibilities, and any other code that calls getUnknown
3582  // is doing so in order to hide a value from SCEV canonicalization.
3583 
3585  ID.AddInteger(scUnknown);
3586  ID.AddPointer(V);
3587  void *IP = nullptr;
3588  if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3589  assert(cast<SCEVUnknown>(S)->getValue() == V &&
3590  "Stale SCEVUnknown in uniquing map!");
3591  return S;
3592  }
3593  SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3594  FirstUnknown);
3595  FirstUnknown = cast<SCEVUnknown>(S);
3596  UniqueSCEVs.InsertNode(S, IP);
3597  return S;
3598 }
3599 
3600 //===----------------------------------------------------------------------===//
3601 // Basic SCEV Analysis and PHI Idiom Recognition Code
3602 //
3603 
3604 /// Test if values of the given type are analyzable within the SCEV
3605 /// framework. This primarily includes integer types, and it can optionally
3606 /// include pointer types if the ScalarEvolution class has access to
3607 /// target-specific information.
3609  // Integers and pointers are always SCEVable.
3610  return Ty->isIntegerTy() || Ty->isPointerTy();
3611 }
3612 
3613 /// Return the size in bits of the specified type, for which isSCEVable must
3614 /// return true.
3616  assert(isSCEVable(Ty) && "Type is not SCEVable!");
3617  if (Ty->isPointerTy())
3618  return getDataLayout().getIndexTypeSizeInBits(Ty);
3619  return getDataLayout().getTypeSizeInBits(Ty);
3620 }
3621 
3622 /// Return a type with the same bitwidth as the given type and which represents
3623 /// how SCEV will treat the given type, for which isSCEVable must return
3624 /// true. For pointer types, this is the pointer-sized integer type.
3626  assert(isSCEVable(Ty) && "Type is not SCEVable!");
3627 
3628  if (Ty->isIntegerTy())
3629  return Ty;
3630 
3631  // The only other support type is pointer.
3632  assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3633  return getDataLayout().getIntPtrType(Ty);
3634 }
3635 
3637  return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3638 }
3639 
3641  return CouldNotCompute.get();
3642 }
3643 
3644 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3645  bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3646  auto *SU = dyn_cast<SCEVUnknown>(S);
3647  return SU && SU->getValue() == nullptr;
3648  });
3649 
3650  return !ContainsNulls;
3651 }
3652 
3654  HasRecMapType::iterator I = HasRecMap.find(S);
3655  if (I != HasRecMap.end())
3656  return I->second;
3657 
3658  bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3659  HasRecMap.insert({S, FoundAddRec});
3660  return FoundAddRec;
3661 }
3662 
3663 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3664 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3665 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3666 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3667  const auto *Add = dyn_cast<SCEVAddExpr>(S);
3668  if (!Add)
3669  return {S, nullptr};
3670 
3671  if (Add->getNumOperands() != 2)
3672  return {S, nullptr};
3673 
3674  auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3675  if (!ConstOp)
3676  return {S, nullptr};
3677 
3678  return {Add->getOperand(1), ConstOp->getValue()};
3679 }
3680 
3681 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3682 /// by the value and offset from any ValueOffsetPair in the set.
3684 ScalarEvolution::getSCEVValues(const SCEV *S) {
3685  ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3686  if (SI == ExprValueMap.end())
3687  return nullptr;
3688 #ifndef NDEBUG
3689  if (VerifySCEVMap) {
3690  // Check there is no dangling Value in the set returned.
3691  for (const auto &VE : SI->second)
3692  assert(ValueExprMap.count(VE.first));
3693  }
3694 #endif
3695  return &SI->second;
3696 }
3697 
3698 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3699 /// cannot be used separately. eraseValueFromMap should be used to remove
3700 /// V from ValueExprMap and ExprValueMap at the same time.
3702  ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3703  if (I != ValueExprMap.end()) {
3704  const SCEV *S = I->second;
3705  // Remove {V, 0} from the set of ExprValueMap[S]
3706  if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3707  SV->remove({V, nullptr});
3708 
3709  // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3710  const SCEV *Stripped;
3712  std::tie(Stripped, Offset) = splitAddExpr(S);
3713  if (Offset != nullptr) {
3714  if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3715  SV->remove({V, Offset});
3716  }
3717  ValueExprMap.erase(V);
3718  }
3719 }
3720 
3721 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3722 /// TODO: In reality it is better to check the poison recursevely
3723 /// but this is better than nothing.
3724 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3725  if (auto *I = dyn_cast<Instruction>(V)) {
3726  if (isa<OverflowingBinaryOperator>(I)) {
3727  if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3728  if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3729  return true;
3730  if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3731  return true;
3732  }
3733  } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3734  return true;
3735  }
3736  return false;
3737 }
3738 
3739 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3740 /// create a new one.
3742  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3743 
3744  const SCEV *S = getExistingSCEV(V);
3745  if (S == nullptr) {
3746  S = createSCEV(V);
3747  // During PHI resolution, it is possible to create two SCEVs for the same
3748  // V, so it is needed to double check whether V->S is inserted into
3749  // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3750  std::pair<ValueExprMapType::iterator, bool> Pair =
3751  ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3752  if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3753  ExprValueMap[S].insert({V, nullptr});
3754 
3755  // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3756  // ExprValueMap.
3757  const SCEV *Stripped = S;
3758  ConstantInt *Offset = nullptr;
3759  std::tie(Stripped, Offset) = splitAddExpr(S);
3760  // If stripped is SCEVUnknown, don't bother to save
3761  // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3762  // increase the complexity of the expansion code.
3763  // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3764  // because it may generate add/sub instead of GEP in SCEV expansion.
3765  if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3766  !isa<GetElementPtrInst>(V))
3767  ExprValueMap[Stripped].insert({V, Offset});
3768  }
3769  }
3770  return S;
3771 }
3772 
3773 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3774  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3775 
3776  ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3777  if (I != ValueExprMap.end()) {
3778  const SCEV *S = I->second;
3779  if (checkValidity(S))
3780  return S;
3781  eraseValueFromMap(V);
3782  forgetMemoizedResults(S);
3783  }
3784  return nullptr;
3785 }
3786 
3787 /// Return a SCEV corresponding to -V = -1*V
3789  SCEV::NoWrapFlags Flags) {
3790  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3791  return getConstant(
3792  cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3793 
3794  Type *Ty = V->getType();
3795  Ty = getEffectiveSCEVType(Ty);
3796  return getMulExpr(
3797  V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3798 }
3799 
3800 /// Return a SCEV corresponding to ~V = -1-V
3802  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3803  return getConstant(
3804  cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3805 
3806  Type *Ty = V->getType();
3807  Ty = getEffectiveSCEVType(Ty);
3808  const SCEV *AllOnes =
3809  getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3810  return getMinusSCEV(AllOnes, V);
3811 }
3812 
3813 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3814  SCEV::NoWrapFlags Flags,
3815  unsigned Depth) {
3816  // Fast path: X - X --> 0.
3817  if (LHS == RHS)
3818  return getZero(LHS->getType());
3819 
3820  // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3821  // makes it so that we cannot make much use of NUW.
3822  auto AddFlags = SCEV::FlagAnyWrap;
3823  const bool RHSIsNotMinSigned =
3824  !getSignedRangeMin(RHS).isMinSignedValue();
3825  if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3826  // Let M be the minimum representable signed value. Then (-1)*RHS
3827  // signed-wraps if and only if RHS is M. That can happen even for
3828  // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3829  // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3830  // (-1)*RHS, we need to prove that RHS != M.
3831  //
3832  // If LHS is non-negative and we know that LHS - RHS does not
3833  // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3834  // either by proving that RHS > M or that LHS >= 0.
3835  if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3836  AddFlags = SCEV::FlagNSW;
3837  }
3838  }
3839 
3840  // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3841  // RHS is NSW and LHS >= 0.
3842  //
3843  // The difficulty here is that the NSW flag may have been proven
3844  // relative to a loop that is to be found in a recurrence in LHS and
3845  // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3846  // larger scope than intended.
3847  auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3848 
3849  return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3850 }
3851 
3852 const SCEV *
3854  Type *SrcTy = V->getType();
3855  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3856  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3857  "Cannot truncate or zero extend with non-integer arguments!");
3858  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3859  return V; // No conversion
3860  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3861  return getTruncateExpr(V, Ty);
3862  return getZeroExtendExpr(V, Ty);
3863 }
3864 
3865 const SCEV *
3867  Type *Ty) {
3868  Type *SrcTy = V->getType();
3869  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3870  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3871  "Cannot truncate or zero extend with non-integer arguments!");
3872  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3873  return V; // No conversion
3874  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3875  return getTruncateExpr(V, Ty);
3876  return getSignExtendExpr(V, Ty);
3877 }
3878 
3879 const SCEV *
3881  Type *SrcTy = V->getType();
3882  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3883  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3884  "Cannot noop or zero extend with non-integer arguments!");
3885  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3886  "getNoopOrZeroExtend cannot truncate!");
3887  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3888  return V; // No conversion
3889  return getZeroExtendExpr(V, Ty);
3890 }
3891 
3892 const SCEV *
3894  Type *SrcTy = V->getType();
3895  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3896  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3897  "Cannot noop or sign extend with non-integer arguments!");
3898  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3899  "getNoopOrSignExtend cannot truncate!");
3900  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3901  return V; // No conversion
3902  return getSignExtendExpr(V, Ty);
3903 }
3904 
3905 const SCEV *
3907  Type *SrcTy = V->getType();
3908  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3909  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3910  "Cannot noop or any extend with non-integer arguments!");
3911  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3912  "getNoopOrAnyExtend cannot truncate!");
3913  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3914  return V; // No conversion
3915  return getAnyExtendExpr(V, Ty);
3916 }
3917 
3918 const SCEV *
3920  Type *SrcTy = V->getType();
3921  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3922  (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3923  "Cannot truncate or noop with non-integer arguments!");
3924  assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3925  "getTruncateOrNoop cannot extend!");
3926  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3927  return V; // No conversion
3928  return getTruncateExpr(V, Ty);
3929 }
3930 
3932  const SCEV *RHS) {
3933  const SCEV *PromotedLHS = LHS;
3934  const SCEV *PromotedRHS = RHS;
3935 
3936  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3937  PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3938  else
3939  PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3940 
3941  return getUMaxExpr(PromotedLHS, PromotedRHS);
3942 }
3943 
3945  const SCEV *RHS) {
3946  const SCEV *PromotedLHS = LHS;
3947  const SCEV *PromotedRHS = RHS;
3948 
3949  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3950  PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3951  else
3952  PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3953 
3954  return getUMinExpr(PromotedLHS, PromotedRHS);
3955 }
3956 
3958  // A pointer operand may evaluate to a nonpointer expression, such as null.
3959  if (!V->getType()->isPointerTy())
3960  return V;
3961 
3962  if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3963  return getPointerBase(Cast->getOperand());
3964  } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3965  const SCEV *PtrOp = nullptr;
3966  for (const SCEV *NAryOp : NAry->operands()) {
3967  if (NAryOp->getType()->isPointerTy()) {
3968  // Cannot find the base of an expression with multiple pointer operands.
3969  if (PtrOp)
3970  return V;
3971  PtrOp = NAryOp;
3972  }
3973  }
3974  if (!PtrOp)
3975  return V;
3976  return getPointerBase(PtrOp);
3977  }
3978  return V;
3979 }
3980 
3981 /// Push users of the given Instruction onto the given Worklist.
3982 static void
3984  SmallVectorImpl<Instruction *> &Worklist) {
3985  // Push the def-use children onto the Worklist stack.
3986  for (User *U : I->users())
3987  Worklist.push_back(cast<Instruction>(U));
3988 }
3989 
3990 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3992  PushDefUseChildren(PN, Worklist);
3993 
3995  Visited.insert(PN);
3996  while (!Worklist.empty()) {
3997  Instruction *I = Worklist.pop_back_val();
3998  if (!Visited.insert(I).second)
3999  continue;
4000 
4001  auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4002  if (It != ValueExprMap.end()) {
4003  const SCEV *Old = It->second;
4004 
4005  // Short-circuit the def-use traversal if the symbolic name
4006  // ceases to appear in expressions.
4007  if (Old != SymName && !hasOperand(Old, SymName))
4008  continue;
4009 
4010  // SCEVUnknown for a PHI either means that it has an unrecognized
4011  // structure, it's a PHI that's in the progress of being computed
4012  // by createNodeForPHI, or it's a single-value PHI. In the first case,
4013  // additional loop trip count information isn't going to change anything.
4014  // In the second case, createNodeForPHI will perform the necessary
4015  // updates on its own when it gets to that point. In the third, we do
4016  // want to forget the SCEVUnknown.
4017  if (!isa<PHINode>(I) ||
4018  !isa<SCEVUnknown>(Old) ||
4019  (I != PN && Old == SymName)) {
4020  eraseValueFromMap(It->first);
4021  forgetMemoizedResults(Old);
4022  }
4023  }
4024 
4025  PushDefUseChildren(I, Worklist);
4026  }
4027 }
4028 
4029 namespace {
4030 
4031 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4032 /// expression in case its Loop is L. If it is not L then
4033 /// if IgnoreOtherLoops is true then use AddRec itself
4034 /// otherwise rewrite cannot be done.
4035 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4036 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4037 public:
4038  static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4039  bool IgnoreOtherLoops = true) {
4040  SCEVInitRewriter Rewriter(L, SE);
4041  const SCEV *Result = Rewriter.visit(S);
4042  if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4043  return SE.getCouldNotCompute();
4044  return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4045  ? SE.getCouldNotCompute()
4046  : Result;
4047  }
4048 
4049  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4050  if (!SE.isLoopInvariant(Expr, L))
4051  SeenLoopVariantSCEVUnknown = true;
4052  return Expr;
4053  }
4054 
4055  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4056  // Only re-write AddRecExprs for this loop.
4057  if (Expr->getLoop() == L)
4058  return Expr->getStart();
4059  SeenOtherLoops = true;
4060  return Expr;
4061  }
4062 
4063  bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4064 
4065  bool hasSeenOtherLoops() { return SeenOtherLoops; }
4066 
4067 private:
4068  explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4069  : SCEVRewriteVisitor(SE), L(L) {}
4070 
4071  const Loop *L;
4072  bool SeenLoopVariantSCEVUnknown = false;
4073  bool SeenOtherLoops = false;
4074 };
4075 
4076 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4077 /// increment expression in case its Loop is L. If it is not L then
4078 /// use AddRec itself.
4079 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4080 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4081 public:
4082  static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4083  SCEVPostIncRewriter Rewriter(L, SE);
4084  const SCEV *Result = Rewriter.visit(S);
4085  return Rewriter.hasSeenLoopVariantSCEVUnknown()
4086  ? SE.getCouldNotCompute()
4087  : Result;
4088  }
4089 
4090  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4091  if (!SE.isLoopInvariant(Expr, L))
4092  SeenLoopVariantSCEVUnknown = true;
4093  return Expr;
4094  }
4095 
4096  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4097  // Only re-write AddRecExprs for this loop.
4098  if (Expr->getLoop() == L)
4099  return Expr->getPostIncExpr(SE);
4100  SeenOtherLoops = true;
4101  return Expr;
4102  }
4103 
4104  bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4105 
4106  bool hasSeenOtherLoops() { return SeenOtherLoops; }
4107 
4108 private:
4109  explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4110  : SCEVRewriteVisitor(SE), L(L) {}
4111 
4112  const Loop *L;
4113  bool SeenLoopVariantSCEVUnknown = false;
4114  bool SeenOtherLoops = false;
4115 };
4116 
4117 /// This class evaluates the compare condition by matching it against the
4118 /// condition of loop latch. If there is a match we assume a true value
4119 /// for the condition while building SCEV nodes.
4120 class SCEVBackedgeConditionFolder
4121  : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4122 public:
4123  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4124  ScalarEvolution &SE) {
4125  bool IsPosBECond = false;
4126  Value *BECond = nullptr;
4127  if (BasicBlock *Latch = L->getLoopLatch()) {
4128  BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4129  if (BI && BI->isConditional()) {
4130  assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4131  "Both outgoing branches should not target same header!");
4132  BECond = BI->getCondition();
4133  IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4134  } else {
4135  return S;
4136  }
4137  }
4138  SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4139  return Rewriter.visit(S);
4140  }
4141 
4142  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4143  const SCEV *Result = Expr;
4144  bool InvariantF = SE.isLoopInvariant(Expr, L);
4145 
4146  if (!InvariantF) {
4147  Instruction *I = cast<Instruction>(Expr->getValue());
4148  switch (I->getOpcode()) {
4149  case Instruction::Select: {
4150  SelectInst *SI = cast<SelectInst>(I);
4152  compareWithBackedgeCondition(SI->getCondition());
4153  if (Res.hasValue()) {
4154  bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4155  Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4156  }
4157  break;
4158  }
4159  default: {
4160  Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4161  if (Res.hasValue())
4162  Result = Res.getValue();
4163  break;
4164  }
4165  }
4166  }
4167  return Result;
4168  }
4169 
4170 private:
4171  explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4172  bool IsPosBECond, ScalarEvolution &SE)
4173  : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4174  IsPositiveBECond(IsPosBECond) {}
4175 
4176  Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4177 
4178  const Loop *L;
4179  /// Loop back condition.
4180  Value *BackedgeCond = nullptr;
4181  /// Set to true if loop back is on positive branch condition.
4182  bool IsPositiveBECond;
4183 };
4184 
4186 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4187 
4188  // If value matches the backedge condition for loop latch,
4189  // then return a constant evolution node based on loopback
4190  // branch taken.
4191  if (BackedgeCond == IC)
4192  return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4193  : SE.getZero(Type::getInt1Ty(SE.getContext()));
4194  return None;
4195 }
4196 
4197 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4198 public:
4199  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4200  ScalarEvolution &SE) {
4201  SCEVShiftRewriter Rewriter(L, SE);
4202  const SCEV *Result = Rewriter.visit(S);
4203  return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4204  }
4205 
4206  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4207  // Only allow AddRecExprs for this loop.
4208  if (!SE.isLoopInvariant(Expr, L))
4209  Valid = false;
4210  return Expr;
4211  }
4212 
4213  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4214  if (Expr->getLoop() == L && Expr->isAffine())
4215  return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4216  Valid = false;
4217  return Expr;
4218  }
4219 
4220  bool isValid() { return Valid; }
4221 
4222 private:
4223  explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4224  : SCEVRewriteVisitor(SE), L(L) {}
4225 
4226  const Loop *L;
4227  bool Valid = true;
4228 };
4229 
4230 } // end anonymous namespace
4231 
4233 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4234  if (!AR->isAffine())
4235  return SCEV::FlagAnyWrap;
4236 
4237  using OBO = OverflowingBinaryOperator;
4238 
4240 
4241  if (!AR->hasNoSignedWrap()) {
4242  ConstantRange AddRecRange = getSignedRange(AR);
4243  ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4244 
4246  Instruction::Add, IncRange, OBO::NoSignedWrap);
4247  if (NSWRegion.contains(AddRecRange))
4248  Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4249  }
4250 
4251  if (!AR->hasNoUnsignedWrap()) {
4252  ConstantRange AddRecRange = getUnsignedRange(AR);
4253  ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4254 
4256  Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4257  if (NUWRegion.contains(AddRecRange))
4258  Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4259  }
4260 
4261  return Result;
4262 }
4263 
4264 namespace {
4265 
4266 /// Represents an abstract binary operation. This may exist as a
4267 /// normal instruction or constant expression, or may have been
4268 /// derived from an expression tree.
4269 struct BinaryOp {
4270  unsigned Opcode;
4271  Value *LHS;
4272  Value *RHS;
4273  bool IsNSW = false;
4274  bool IsNUW = false;
4275 
4276  /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4277  /// constant expression.
4278  Operator *Op = nullptr;
4279 
4280  explicit BinaryOp(Operator *Op)
4281  : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4282  Op(Op) {
4283  if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4284  IsNSW = OBO->hasNoSignedWrap();
4285  IsNUW = OBO->hasNoUnsignedWrap();
4286  }
4287  }
4288 
4289  explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4290  bool IsNUW = false)
4291  : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4292 };
4293 
4294 } // end anonymous namespace
4295 
4296 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4298  auto *Op = dyn_cast<Operator>(V);
4299  if (!Op)
4300  return None;
4301 
4302  // Implementation detail: all the cleverness here should happen without
4303  // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4304  // SCEV expressions when possible, and we should not break that.
4305 
4306  switch (Op->getOpcode()) {
4307  case Instruction::Add:
4308  case Instruction::Sub:
4309  case Instruction::Mul:
4310  case Instruction::UDiv:
4311  case Instruction::URem:
4312  case Instruction::And:
4313  case Instruction::Or:
4314  case Instruction::AShr:
4315  case Instruction::Shl:
4316  return BinaryOp(Op);
4317 
4318  case Instruction::Xor:
4319  if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4320  // If the RHS of the xor is a signmask, then this is just an add.
4321  // Instcombine turns add of signmask into xor as a strength reduction step.
4322  if (RHSC->getValue().isSignMask())
4323  return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4324  return BinaryOp(Op);
4325 
4326  case Instruction::LShr:
4327  // Turn logical shift right of a constant into a unsigned divide.
4328  if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4329  uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4330 
4331  // If the shift count is not less than the bitwidth, the result of
4332  // the shift is undefined. Don't try to analyze it, because the
4333  // resolution chosen here may differ from the resolution chosen in
4334  // other parts of the compiler.
4335  if (SA->getValue().ult(BitWidth)) {
4336  Constant *X =
4337  ConstantInt::get(SA->getContext(),
4338  APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4339  return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4340  }
4341  }
4342  return BinaryOp(Op);
4343 
4344  case Instruction::ExtractValue: {
4345  auto *EVI = cast<ExtractValueInst>(Op);
4346  if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4347  break;
4348 
4349  auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4350  if (!CI)
4351  break;
4352 
4353  if (auto *F = CI->getCalledFunction())
4354  switch (F->getIntrinsicID()) {
4355  case Intrinsic::sadd_with_overflow:
4356  case Intrinsic::uadd_with_overflow:
4357  if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4358  return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4359  CI->getArgOperand(1));
4360 
4361  // Now that we know that all uses of the arithmetic-result component of
4362  // CI are guarded by the overflow check, we can go ahead and pretend
4363  // that the arithmetic is non-overflowing.
4364  if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4365  return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4366  CI->getArgOperand(1), /* IsNSW = */ true,
4367  /* IsNUW = */ false);
4368  else
4369  return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4370  CI->getArgOperand(1), /* IsNSW = */ false,
4371  /* IsNUW*/ true);
4372  case Intrinsic::ssub_with_overflow:
4373  case Intrinsic::usub_with_overflow:
4374  if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4375  return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4376  CI->getArgOperand(1));
4377 
4378  // The same reasoning as sadd/uadd above.
4379  if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4380  return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4381  CI->getArgOperand(1), /* IsNSW = */ true,
4382  /* IsNUW = */ false);
4383  else
4384  return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4385  CI->getArgOperand(1), /* IsNSW = */ false,
4386  /* IsNUW = */ true);
4387  case Intrinsic::smul_with_overflow:
4388  case Intrinsic::umul_with_overflow:
4389  return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4390  CI->getArgOperand(1));
4391  default:
4392  break;
4393  }
4394  break;
4395  }
4396 
4397  default:
4398  break;
4399  }
4400 
4401  return None;
4402 }
4403 
4404 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4405 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4406 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4407 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4408 /// follows one of the following patterns:
4409 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4410 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4411 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4412 /// we return the type of the truncation operation, and indicate whether the
4413 /// truncated type should be treated as signed/unsigned by setting
4414 /// \p Signed to true/false, respectively.
4415 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4416  bool &Signed, ScalarEvolution &SE) {
4417  // The case where Op == SymbolicPHI (that is, with no type conversions on
4418  // the way) is handled by the regular add recurrence creating logic and
4419  // would have already been triggered in createAddRecForPHI. Reaching it here
4420  // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4421  // because one of the other operands of the SCEVAddExpr updating this PHI is
4422  // not invariant).
4423  //
4424  // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4425  // this case predicates that allow us to prove that Op == SymbolicPHI will
4426  // be added.
4427  if (Op == SymbolicPHI)
4428  return nullptr;
4429 
4430  unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4431  unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4432  if (SourceBits != NewBits)
4433  return nullptr;
4434 
4437  if (!SExt && !ZExt)
4438  return nullptr;
4439  const SCEVTruncateExpr *Trunc =
4440  SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4441  : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4442  if (!Trunc)
4443  return nullptr;
4444  const SCEV *X = Trunc->getOperand();
4445  if (X != SymbolicPHI)
4446  return nullptr;
4447  Signed = SExt != nullptr;
4448  return Trunc->getType();
4449 }
4450 
4451 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4452  if (!PN->getType()->isIntegerTy())
4453  return nullptr;
4454  const Loop *L = LI.getLoopFor(PN->getParent());
4455  if (!L || L->getHeader() != PN->getParent())
4456  return nullptr;
4457  return L;
4458 }
4459 
4460 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4461 // computation that updates the phi follows the following pattern:
4462 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4463 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4464 // If so, try to see if it can be rewritten as an AddRecExpr under some
4465 // Predicates. If successful, return them as a pair. Also cache the results
4466 // of the analysis.
4467 //
4468 // Example usage scenario:
4469 // Say the Rewriter is called for the following SCEV:
4470 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4471 // where:
4472 // %X = phi i64 (%Start, %BEValue)
4473 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4474 // and call this function with %SymbolicPHI = %X.
4475 //
4476 // The analysis will find that the value coming around the backedge has
4477 // the following SCEV:
4478 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4479 // Upon concluding that this matches the desired pattern, the function
4480 // will return the pair {NewAddRec, SmallPredsVec} where:
4481 // NewAddRec = {%Start,+,%Step}
4482 // SmallPredsVec = {P1, P2, P3} as follows:
4483 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4484 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4485 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4486 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4487 // under the predicates {P1,P2,P3}.
4488 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4489 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4490 //
4491 // TODO's:
4492 //
4493 // 1) Extend the Induction descriptor to also support inductions that involve
4494 // casts: When needed (namely, when we are called in the context of the
4495 // vectorizer induction analysis), a Set of cast instructions will be
4496 // populated by this method, and provided back to isInductionPHI. This is
4497 // needed to allow the vectorizer to properly record them to be ignored by
4498 // the cost model and to avoid vectorizing them (otherwise these casts,
4499 // which are redundant under the runtime overflow checks, will be
4500 // vectorized, which can be costly).
4501 //
4502 // 2) Support additional induction/PHISCEV patterns: We also want to support
4503 // inductions where the sext-trunc / zext-trunc operations (partly) occur
4504 // after the induction update operation (the induction increment):
4505 //
4506 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4507 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4508 //
4509 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4510 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4511 //
4512 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4514 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4516 
4517  // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4518  // return an AddRec expression under some predicate.
4519 
4520  auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4521  const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4522  assert(L && "Expecting an integer loop header phi");
4523 
4524  // The loop may have multiple entrances or multiple exits; we can analyze
4525  // this phi as an addrec if it has a unique entry value and a unique
4526  // backedge value.
4527  Value *BEValueV = nullptr, *StartValueV = nullptr;
4528  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4529  Value *V = PN->getIncomingValue(i);
4530  if (L->contains(PN->getIncomingBlock(i))) {
4531  if (!BEValueV) {
4532  BEValueV = V;
4533  } else if (BEValueV != V) {
4534  BEValueV = nullptr;
4535  break;
4536  }
4537  } else if (!StartValueV) {
4538  StartValueV = V;
4539  } else if (StartValueV != V) {
4540  StartValueV = nullptr;
4541  break;
4542  }
4543  }
4544  if (!BEValueV || !StartValueV)
4545  return None;
4546 
4547  const SCEV *BEValue = getSCEV(BEValueV);
4548 
4549  // If the value coming around the backedge is an add with the symbolic
4550  // value we just inserted, possibly with casts that we can ignore under
4551  // an appropriate runtime guard, then we found a simple induction variable!
4552  const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4553  if (!Add)
4554  return None;
4555 
4556  // If there is a single occurrence of the symbolic value, possibly
4557  // casted, replace it with a recurrence.
4558  unsigned FoundIndex = Add->getNumOperands();
4559  Type *TruncTy = nullptr;
4560  bool Signed;
4561  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4562  if ((TruncTy =
4563  isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4564  if (FoundIndex == e) {
4565  FoundIndex = i;
4566  break;
4567  }
4568 
4569  if (FoundIndex == Add->getNumOperands())
4570  return None;
4571 
4572  // Create an add with everything but the specified operand.
4574  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4575  if (i != FoundIndex)
4576  Ops.push_back(Add->getOperand(i));
4577  const SCEV *Accum = getAddExpr(Ops);
4578 
4579  // The runtime checks will not be valid if the step amount is
4580  // varying inside the loop.
4581  if (!isLoopInvariant(Accum, L))
4582  return None;
4583 
4584  // *** Part2: Create the predicates
4585 
4586  // Analysis was successful: we have a phi-with-cast pattern for which we
4587  // can return an AddRec expression under the following predicates:
4588  //
4589  // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4590  // fits within the truncated type (does not overflow) for i = 0 to n-1.
4591  // P2: An Equal predicate that guarantees that
4592  // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4593  // P3: An Equal predicate that guarantees that
4594  // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4595  //
4596  // As we next prove, the above predicates guarantee that:
4597  // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4598  //
4599  //
4600  // More formally, we want to prove that:
4601  // Expr(i+1) = Start + (i+1) * Accum
4602  // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4603  //
4604  // Given that:
4605  // 1) Expr(0) = Start
4606  // 2) Expr(1) = Start + Accum
4607  // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4608  // 3) Induction hypothesis (step i):
4609  // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4610  //
4611  // Proof:
4612  // Expr(i+1) =
4613  // = Start + (i+1)*Accum
4614  // = (Start + i*Accum) + Accum
4615  // = Expr(i) + Accum
4616  // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4617  // :: from step i
4618  //
4619  // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4620  //
4621  // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4622  // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4623  // + Accum :: from P3
4624  //
4625  // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4626  // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4627  //
4628  // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4629  // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4630  //
4631  // By induction, the same applies to all iterations 1<=i<n:
4632  //
4633 
4634  // Create a truncated addrec for which we will add a no overflow check (P1).
4635  const SCEV *StartVal = getSCEV(StartValueV);
4636  const SCEV *PHISCEV =
4637  getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4638  getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4639 
4640  // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4641  // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4642  // will be constant.
4643  //
4644  // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4645  // add P1.
4646  if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4650  const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4651  Predicates.push_back(AddRecPred);
4652  }
4653 
4654  // Create the Equal Predicates P2,P3:
4655 
4656  // It is possible that the predicates P2 and/or P3 are computable at
4657  // compile time due to StartVal and/or Accum being constants.
4658  // If either one is, then we can check that now and escape if either P2
4659  // or P3 is false.
4660 
4661  // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4662  // for each of StartVal and Accum
4663  auto getExtendedExpr = [&](const SCEV *Expr,
4664  bool CreateSignExtend) -> const SCEV * {
4665  assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4666  const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4667  const SCEV *ExtendedExpr =
4668  CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4669  : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4670  return ExtendedExpr;
4671  };
4672 
4673  // Given:
4674  // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4675  // = getExtendedExpr(Expr)
4676  // Determine whether the predicate P: Expr == ExtendedExpr
4677  // is known to be false at compile time
4678  auto PredIsKnownFalse = [&](const SCEV *Expr,
4679  const SCEV *ExtendedExpr) -> bool {
4680  return Expr != ExtendedExpr &&
4681  isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4682  };
4683 
4684  const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4685  if (PredIsKnownFalse(StartVal, StartExtended)) {
4686  DEBUG(dbgs() << "P2 is compile-time false\n";);
4687  return None;
4688  }
4689 
4690  // The Step is always Signed (because the overflow checks are either
4691  // NSSW or NUSW)
4692  const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4693  if (PredIsKnownFalse(Accum, AccumExtended)) {
4694  DEBUG(dbgs() << "P3 is compile-time false\n";);
4695  return None;
4696  }
4697 
4698  auto AppendPredicate = [&](const SCEV *Expr,
4699  const SCEV *ExtendedExpr) -> void {
4700  if (Expr != ExtendedExpr &&
4701  !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4702  const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4703  DEBUG (dbgs() << "Added Predicate: " << *Pred);
4704  Predicates.push_back(Pred);
4705  }
4706  };
4707 
4708  AppendPredicate(StartVal, StartExtended);
4709  AppendPredicate(Accum, AccumExtended);
4710 
4711  // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4712  // which the casts had been folded away. The caller can rewrite SymbolicPHI
4713  // into NewAR if it will also add the runtime overflow checks specified in
4714  // Predicates.
4715  auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4716 
4717  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4718  std::make_pair(NewAR, Predicates);
4719  // Remember the result of the analysis for this SCEV at this locayyytion.
4720  PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4721  return PredRewrite;
4722 }
4723 
4726  auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4727  const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4728  if (!L)
4729  return None;
4730 
4731  // Check to see if we already analyzed this PHI.
4732  auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4733  if (I != PredicatedSCEVRewrites.end()) {
4734  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4735  I->second;
4736  // Analysis was done before and failed to create an AddRec:
4737  if (Rewrite.first == SymbolicPHI)
4738  return None;
4739  // Analysis was done before and succeeded to create an AddRec under
4740  // a predicate:
4741  assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4742  assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4743  return Rewrite;
4744  }
4745 
4747  Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4748 
4749  // Record in the cache that the analysis failed
4750  if (!Rewrite) {
4752  PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4753  return None;
4754  }
4755 
4756  return Rewrite;
4757 }
4758 
4759 // FIXME: This utility is currently required because the Rewriter currently
4760 // does not rewrite this expression:
4761 // {0, +, (sext ix (trunc iy to ix) to iy)}
4762 // into {0, +, %step},
4763 // even when the following Equal predicate exists:
4764 // "%step == (sext ix (trunc iy to ix) to iy)".
4766  const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4767  if (AR1 == AR2)
4768  return true;
4769 
4770  auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4771  if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4772  !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4773  return false;
4774  return true;
4775  };
4776 
4777  if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4778  !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4779  return false;
4780  return true;
4781 }
4782 
4783 /// A helper function for createAddRecFromPHI to handle simple cases.
4784 ///
4785 /// This function tries to find an AddRec expression for the simplest (yet most
4786 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4787 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4788 /// technique for finding the AddRec expression.
4789 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4790  Value *BEValueV,
4791  Value *StartValueV) {
4792  const Loop *L = LI.getLoopFor(PN->getParent());
4793  assert(L && L->getHeader() == PN->getParent());
4794  assert(BEValueV && StartValueV);
4795 
4796  auto BO = MatchBinaryOp(BEValueV, DT);
4797  if (!BO)
4798  return nullptr;
4799 
4800  if (BO->Opcode != Instruction::Add)
4801  return nullptr;
4802 
4803  const SCEV *Accum = nullptr;
4804  if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4805  Accum = getSCEV(BO->RHS);
4806  else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4807  Accum = getSCEV(BO->LHS);
4808 
4809  if (!Accum)
4810  return nullptr;
4811 
4813  if (BO->IsNUW)
4814  Flags = setFlags(Flags, SCEV::FlagNUW);
4815  if (BO->IsNSW)
4816  Flags = setFlags(Flags, SCEV::FlagNSW);
4817 
4818  const SCEV *StartVal = getSCEV(StartValueV);
4819  const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4820 
4821  ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4822 
4823  // We can add Flags to the post-inc expression only if we
4824  // know that it is *undefined behavior* for BEValueV to
4825  // overflow.
4826  if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4827  if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4828  (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4829 
4830  return PHISCEV;
4831 }
4832 
4833 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4834  const Loop *L = LI.getLoopFor(PN->getParent());
4835  if (!L || L->getHeader() != PN->getParent())
4836  return nullptr;
4837 
4838  // The loop may have multiple entrances or multiple exits; we can analyze
4839  // this phi as an addrec if it has a unique entry value and a unique
4840  // backedge value.
4841  Value *BEValueV = nullptr, *StartValueV = nullptr;
4842  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4843  Value *V = PN->getIncomingValue(i);
4844  if (L->contains(PN->getIncomingBlock(i))) {
4845  if (!BEValueV) {
4846  BEValueV = V;
4847  } else if (BEValueV != V) {
4848  BEValueV = nullptr;
4849  break;
4850  }
4851  } else if (!StartValueV) {
4852  StartValueV = V;
4853  } else if (StartValueV != V) {
4854  StartValueV = nullptr;
4855  break;
4856  }
4857  }
4858  if (!BEValueV || !StartValueV)
4859  return nullptr;
4860 
4861  assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4862  "PHI node already processed?");
4863 
4864  // First, try to find AddRec expression without creating a fictituos symbolic
4865  // value for PN.
4866  if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4867  return S;
4868 
4869  // Handle PHI node value symbolically.
4870  const SCEV *SymbolicName = getUnknown(PN);
4871  ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4872 
4873  // Using this symbolic name for the PHI, analyze the value coming around
4874  // the back-edge.
4875  const SCEV *BEValue = getSCEV(BEValueV);
4876 
4877  // NOTE: If BEValue is loop invariant, we know that the PHI node just
4878  // has a special value for the first iteration of the loop.
4879 
4880  // If the value coming around the backedge is an add with the symbolic
4881  // value we just inserted, then we found a simple induction variable!
4882  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4883  // If there is a single occurrence of the symbolic value, replace it
4884  // with a recurrence.
4885  unsigned FoundIndex = Add->getNumOperands();
4886  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4887  if (Add->getOperand(i) == SymbolicName)
4888  if (FoundIndex == e) {
4889  FoundIndex = i;
4890  break;
4891  }
4892 
4893  if (FoundIndex != Add->getNumOperands()) {
4894  // Create an add with everything but the specified operand.
4896  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4897  if (i != FoundIndex)
4898  Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4899  L, *this));
4900  const SCEV *Accum = getAddExpr(Ops);
4901 
4902  // This is not a valid addrec if the step amount is varying each
4903  // loop iteration, but is not itself an addrec in this loop.
4904  if (isLoopInvariant(Accum, L) ||
4905  (isa<SCEVAddRecExpr>(Accum) &&
4906  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4908 
4909  if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4910  if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4911  if (BO->IsNUW)
4912  Flags = setFlags(Flags, SCEV::FlagNUW);
4913  if (BO->IsNSW)
4914  Flags = setFlags(Flags, SCEV::FlagNSW);
4915  }
4916  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4917  // If the increment is an inbounds GEP, then we know the address
4918  // space cannot be wrapped around. We cannot make any guarantee
4919  // about signed or unsigned overflow because pointers are
4920  // unsigned but we may have a negative index from the base
4921  // pointer. We can guarantee that no unsigned wrap occurs if the
4922  // indices form a positive value.
4923  if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4924  Flags = setFlags(Flags, SCEV::FlagNW);
4925 
4926  const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4927  if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4928  Flags = setFlags(Flags, SCEV::FlagNUW);
4929  }
4930 
4931  // We cannot transfer nuw and nsw flags from subtraction
4932  // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4933  // for instance.
4934  }
4935 
4936  const SCEV *StartVal = getSCEV(StartValueV);
4937  const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4938 
4939  // Okay, for the entire analysis of this edge we assumed the PHI
4940  // to be symbolic. We now need to go back and purge all of the
4941  // entries for the scalars that use the symbolic expression.
4942  forgetSymbolicName(PN, SymbolicName);
4943  ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4944 
4945  // We can add Flags to the post-inc expression only if we
4946  // know that it is *undefined behavior* for BEValueV to
4947  // overflow.
4948  if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4949  if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4950  (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4951 
4952  return PHISCEV;
4953  }
4954  }
4955  } else {
4956  // Otherwise, this could be a loop like this:
4957  // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4958  // In this case, j = {1,+,1} and BEValue is j.
4959  // Because the other in-value of i (0) fits the evolution of BEValue
4960  // i really is an addrec evolution.
4961  //
4962  // We can generalize this saying that i is the shifted value of BEValue
4963  // by one iteration:
4964  // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4965  const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4966  const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
4967  if (Shifted != getCouldNotCompute() &&
4968  Start != getCouldNotCompute()) {
4969  const SCEV *StartVal = getSCEV(StartValueV);
4970  if (Start == StartVal) {
4971  // Okay, for the entire analysis of this edge we assumed the PHI
4972  // to be symbolic. We now need to go back and purge all of the
4973  // entries for the scalars that use the symbolic expression.
4974  forgetSymbolicName(PN, SymbolicName);
4975  ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4976  return Shifted;
4977  }
4978  }
4979  }
4980 
4981  // Remove the temporary PHI node SCEV that has been inserted while intending
4982  // to create an AddRecExpr for this PHI node. We can not keep this temporary
4983  // as it will prevent later (possibly simpler) SCEV expressions to be added
4984  // to the ValueExprMap.
4985  eraseValueFromMap(PN);
4986 
4987  return nullptr;
4988 }
4989 
4990 // Checks if the SCEV S is available at BB. S is considered available at BB
4991 // if S can be materialized at BB without introducing a fault.
4992 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4993  BasicBlock *BB) {
4994  struct CheckAvailable {
4995  bool TraversalDone = false;
4996  bool Available = true;
4997 
4998  const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4999  BasicBlock *BB = nullptr;
5000  DominatorTree &DT;
5001 
5002  CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5003  : L(L), BB(BB), DT(DT) {}
5004 
5005  bool setUnavailable() {
5006  TraversalDone = true;
5007  Available = false;
5008  return false;
5009  }
5010 
5011  bool follow(const SCEV *S) {
5012  switch (S->getSCEVType()) {
5013  case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5014  case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5015  // These expressions are available if their operand(s) is/are.
5016  return true;
5017 
5018  case scAddRecExpr: {
5019  // We allow add recurrences that are on the loop BB is in, or some
5020  // outer loop. This guarantees availability because the value of the
5021  // add recurrence at BB is simply the "current" value of the induction
5022  // variable. We can relax this in the future; for instance an add
5023  // recurrence on a sibling dominating loop is also available at BB.
5024  const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5025  if (L && (ARLoop == L || ARLoop->contains(L)))
5026  return true;
5027 
5028  return setUnavailable();
5029  }
5030 
5031  case scUnknown: {
5032  // For SCEVUnknown, we check for simple dominance.
5033  const auto *SU = cast<SCEVUnknown>(S);
5034  Value *V = SU->getValue();
5035 
5036  if (isa<Argument>(V))
5037  return false;
5038 
5039  if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5040  return false;
5041 
5042  return setUnavailable();
5043  }
5044 
5045  case scUDivExpr:
5046  case scCouldNotCompute:
5047  // We do not try to smart about these at all.
5048  return setUnavailable();
5049  }
5050  llvm_unreachable("switch should be fully covered!");
5051  }
5052 
5053  bool isDone() { return TraversalDone; }
5054  };
5055 
5056  CheckAvailable CA(L, BB, DT);
5058 
5059  ST.visitAll(S);
5060  return CA.Available;
5061 }
5062 
5063 // Try to match a control flow sequence that branches out at BI and merges back
5064 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5065 // match.
5067  Value *&C, Value *&LHS, Value *&RHS) {
5068  C = BI->getCondition();
5069 
5070  BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5071  BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5072 
5073  if (!LeftEdge.isSingleEdge())
5074  return false;
5075 
5076  assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5077 
5078  Use &LeftUse = Merge->getOperandUse(0);
5079  Use &RightUse = Merge->getOperandUse(1);
5080 
5081  if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5082  LHS = LeftUse;
5083  RHS = RightUse;
5084  return true;
5085  }
5086 
5087  if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5088  LHS = RightUse;
5089  RHS = LeftUse;
5090  return true;
5091  }
5092 
5093  return false;
5094 }
5095 
5096 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5097  auto IsReachable =
5098  [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5099  if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5100  const Loop *L = LI.getLoopFor(PN->getParent());
5101 
5102  // We don't want to break LCSSA, even in a SCEV expression tree.
5103  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5104  if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5105  return nullptr;
5106 
5107  // Try to match
5108  //
5109  // br %cond, label %left, label %right
5110  // left:
5111  // br label %merge
5112  // right:
5113  // br label %merge
5114  // merge:
5115  // V = phi [ %x, %left ], [ %y, %right ]
5116  //
5117  // as "select %cond, %x, %y"
5118 
5119  BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5120  assert(IDom && "At least the entry block should dominate PN");
5121 
5122  auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5123  Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5124 
5125  if (BI && BI->isConditional() &&
5126  BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5127  IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5128  IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5129  return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5130  }
5131 
5132  return nullptr;
5133 }
5134 
5135 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5136  if (const SCEV *S = createAddRecFromPHI(PN))
5137  return S;
5138 
5139  if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5140  return S;
5141 
5142  // If the PHI has a single incoming value, follow that value, unless the
5143  // PHI's incoming blocks are in a different loop, in which case doing so
5144  // risks breaking LCSSA form. Instcombine would normally zap these, but
5145  // it doesn't have DominatorTree information, so it may miss cases.
5146  if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5147  if (LI.replacementPreservesLCSSAForm(PN, V))
5148  return getSCEV(V);
5149 
5150  // If it's not a loop phi, we can't handle it yet.
5151  return getUnknown(PN);
5152 }
5153 
5154 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5155  Value *Cond,
5156  Value *TrueVal,
5157  Value *FalseVal) {
5158  // Handle "constant" branch or select. This can occur for instance when a
5159  // loop pass transforms an inner loop and moves on to process the outer loop.
5160  if (auto *CI = dyn_cast<ConstantInt>(Cond))
5161  return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5162 
5163  // Try to match some simple smax or umax patterns.
5164  auto *ICI = dyn_cast<ICmpInst>(Cond);
5165  if (!ICI)
5166  return getUnknown(I);
5167 
5168  Value *LHS = ICI->getOperand(0);
5169  Value *RHS = ICI->getOperand(1);
5170 
5171  switch (ICI->getPredicate()) {
5172  case ICmpInst::ICMP_SLT:
5173  case ICmpInst::ICMP_SLE:
5174  std::swap(LHS, RHS);
5176  case ICmpInst::ICMP_SGT:
5177  case ICmpInst::ICMP_SGE:
5178  // a >s b ? a+x : b+x -> smax(a, b)+x
5179  // a >s b ? b+x : a+x -> smin(a, b)+x
5180  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5181  const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5182  const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5183  const SCEV *LA = getSCEV(TrueVal);
5184  const SCEV *RA = getSCEV(FalseVal);
5185  const SCEV *LDiff = getMinusSCEV(LA, LS);
5186  const SCEV *RDiff = getMinusSCEV(RA, RS);
5187  if (LDiff == RDiff)
5188  return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5189  LDiff = getMinusSCEV(LA, RS);
5190  RDiff = getMinusSCEV(RA, LS);
5191  if (LDiff == RDiff)
5192  return getAddExpr(getSMinExpr(LS, RS), LDiff);
5193  }
5194  break;
5195  case ICmpInst::ICMP_ULT:
5196  case ICmpInst::ICMP_ULE:
5197  std::swap(LHS, RHS);
5199  case ICmpInst::ICMP_UGT:
5200  case ICmpInst::ICMP_UGE:
5201  // a >u b ? a+x : b+x -> umax(a, b)+x
5202  // a >u b ? b+x : a+x -> umin(a, b)+x
5203  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5204  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5205  const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5206  const SCEV *LA = getSCEV(TrueVal);
5207  const SCEV *RA = getSCEV(FalseVal);
5208  const SCEV *LDiff = getMinusSCEV(LA, LS);
5209  const SCEV *RDiff = getMinusSCEV(RA, RS);
5210  if (LDiff == RDiff)
5211  return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5212  LDiff = getMinusSCEV(LA, RS);
5213  RDiff = getMinusSCEV(RA, LS);
5214  if (LDiff == RDiff)
5215  return getAddExpr(getUMinExpr(LS, RS), LDiff);
5216  }
5217  break;
5218  case ICmpInst::ICMP_NE:
5219  // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5220  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5221  isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5222  const SCEV *One = getOne(I->getType());
5223  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5224  const SCEV *LA = getSCEV(TrueVal);
5225  const SCEV *RA = getSCEV(FalseVal);
5226  const SCEV *LDiff = getMinusSCEV(LA, LS);
5227  const SCEV *RDiff = getMinusSCEV(RA, One);
5228  if (LDiff == RDiff)
5229  return getAddExpr(getUMaxExpr(One, LS), LDiff);
5230  }
5231  break;
5232  case ICmpInst::ICMP_EQ:
5233  // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5234  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5235  isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5236  const SCEV *One = getOne(I->getType());
5237  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5238  const SCEV *LA = getSCEV(TrueVal);
5239  const SCEV *RA = getSCEV(FalseVal);
5240  const SCEV *LDiff = getMinusSCEV(LA, One);
5241  const SCEV *RDiff = getMinusSCEV(RA, LS);
5242  if (LDiff == RDiff)
5243  return getAddExpr(getUMaxExpr(One, LS), LDiff);
5244  }
5245  break;
5246  default:
5247  break;
5248  }
5249 
5250  return getUnknown(I);
5251 }
5252 
5253 /// Expand GEP instructions into add and multiply operations. This allows them
5254 /// to be analyzed by regular SCEV code.
5255 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5256  // Don't attempt to analyze GEPs over unsized objects.
5257  if (!GEP->getSourceElementType()->isSized())
5258  return getUnknown(GEP);
5259 
5260  SmallVector<const SCEV *, 4> IndexExprs;
5261  for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5262  IndexExprs.push_back(getSCEV(*Index));
5263  return getGEPExpr(GEP, IndexExprs);
5264 }
5265 
5266 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5267  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5268  return C->getAPInt().countTrailingZeros();
5269 
5270  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5271  return std::min(GetMinTrailingZeros(T->getOperand()),
5272  (uint32_t)getTypeSizeInBits(T->getType()));
5273 
5274  if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5275  uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5276  return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5277  ? getTypeSizeInBits(E->getType())
5278  : OpRes;
5279  }
5280 
5281  if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5282  uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5283  return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5284  ? getTypeSizeInBits(E->getType())
5285  : OpRes;
5286  }
5287 
5288  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5289  // The result is the min of all operands results.
5290  uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5291  for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5292  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5293  return MinOpRes;
5294  }
5295 
5296  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5297  // The result is the sum of all operands results.
5298  uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5299  uint32_t BitWidth = getTypeSizeInBits(M->getType());
5300  for (unsigned i = 1, e = M->getNumOperands();
5301  SumOpRes != BitWidth && i != e; ++i)
5302  SumOpRes =
5303  std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5304  return SumOpRes;
5305  }
5306 
5307  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5308  // The result is the min of all operands results.
5309  uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5310  for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5311  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5312  return MinOpRes;
5313  }
5314 
5315  if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5316  // The result is the min of all operands results.
5317  uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5318  for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5319  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5320  return MinOpRes;
5321  }
5322 
5323  if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5324  // The result is the min of all operands results.
5325  uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5326  for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5327  MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5328  return MinOpRes;
5329  }
5330 
5331  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5332  // For a SCEVUnknown, ask ValueTracking.
5333  KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5334  return Known.countMinTrailingZeros();
5335  }
5336 
5337  // SCEVUDivExpr
5338  return 0;
5339 }
5340 
5342  auto I = MinTrailingZerosCache.find(S);
5343  if (I != MinTrailingZerosCache.end())
5344  return I->second;
5345 
5346  uint32_t Result = GetMinTrailingZerosImpl(S);
5347  auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5348  assert(InsertPair.second && "Should insert a new key");
5349  return InsertPair.first->second;
5350 }
5351 
5352 /// Helper method to assign a range to V from metadata present in the IR.
5354  if (Instruction *I = dyn_cast<Instruction>(V))
5356  return getConstantRangeFromMetadata(*MD);
5357 
5358  return None;
5359 }
5360 
5361 /// Determine the range for a particular SCEV. If SignHint is
5362 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5363 /// with a "cleaner" unsigned (resp. signed) representation.
5364 const ConstantRange &
5365 ScalarEvolution::getRangeRef(const SCEV *S,
5366  ScalarEvolution::RangeSignHint SignHint) {
5368  SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5369  : SignedRanges;
5370 
5371  // See if we've computed this range already.
5373  if (I != Cache.end())
5374  return I->second;
5375 
5376  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5377  return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5378 
5379  unsigned BitWidth = getTypeSizeInBits(S->getType());
5380  ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5381 
5382  // If the value has known zeros, the maximum value will have those known zeros
5383  // as well.
5384  uint32_t TZ = GetMinTrailingZeros(S);
5385  if (TZ != 0) {
5386  if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5387  ConservativeResult =
5389  APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5390  else
5391  ConservativeResult = ConstantRange(
5392  APInt::getSignedMinValue(BitWidth),
5393  APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5394  }
5395 
5396  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5397  ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5398  for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5399  X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5400  return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5401  }
5402 
5403  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5404  ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5405  for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5406  X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5407  return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5408  }
5409 
5410  if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5411  ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5412  for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5413  X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5414  return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5415  }
5416 
5417  if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5418  ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5419  for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5420  X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5421  return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5422  }
5423 
5424  if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5425  ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5426  ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5427  return setRange(UDiv, SignHint,
5428  ConservativeResult.intersectWith(X.udiv(Y)));
5429  }
5430 
5431  if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5432  ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5433  return setRange(ZExt, SignHint,
5434  ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5435  }
5436 
5437  if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5438  ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5439  return setRange(SExt, SignHint,
5440  ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5441  }
5442 
5443  if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5444  ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5445  return setRange(Trunc, SignHint,
5446  ConservativeResult.intersectWith(X.truncate(BitWidth)));
5447  }
5448 
5449  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5450  // If there's no unsigned wrap, the value will never be less than its
5451  // initial value.
5452  if (AddRec->hasNoUnsignedWrap())
5453  if (const SCEVConstant *C = dyn_ca