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