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