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