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 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.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" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.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" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.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::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 //===----------------------------------------------------------------------===// 224 // SCEV class definitions 225 //===----------------------------------------------------------------------===// 226 227 //===----------------------------------------------------------------------===// 228 // Implementation of the SCEV class. 229 // 230 231 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 232 LLVM_DUMP_METHOD void SCEV::dump() const { 233 print(dbgs()); 234 dbgs() << '\n'; 235 } 236 #endif 237 238 void SCEV::print(raw_ostream &OS) const { 239 switch (static_cast<SCEVTypes>(getSCEVType())) { 240 case scConstant: 241 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 242 return; 243 case scTruncate: { 244 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 245 const SCEV *Op = Trunc->getOperand(); 246 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 247 << *Trunc->getType() << ")"; 248 return; 249 } 250 case scZeroExtend: { 251 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 252 const SCEV *Op = ZExt->getOperand(); 253 OS << "(zext " << *Op->getType() << " " << *Op << " to " 254 << *ZExt->getType() << ")"; 255 return; 256 } 257 case scSignExtend: { 258 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 259 const SCEV *Op = SExt->getOperand(); 260 OS << "(sext " << *Op->getType() << " " << *Op << " to " 261 << *SExt->getType() << ")"; 262 return; 263 } 264 case scAddRecExpr: { 265 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 266 OS << "{" << *AR->getOperand(0); 267 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 268 OS << ",+," << *AR->getOperand(i); 269 OS << "}<"; 270 if (AR->hasNoUnsignedWrap()) 271 OS << "nuw><"; 272 if (AR->hasNoSignedWrap()) 273 OS << "nsw><"; 274 if (AR->hasNoSelfWrap() && 275 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 276 OS << "nw><"; 277 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 278 OS << ">"; 279 return; 280 } 281 case scAddExpr: 282 case scMulExpr: 283 case scUMaxExpr: 284 case scSMaxExpr: 285 case scUMinExpr: 286 case scSMinExpr: { 287 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 288 const char *OpStr = nullptr; 289 switch (NAry->getSCEVType()) { 290 case scAddExpr: OpStr = " + "; break; 291 case scMulExpr: OpStr = " * "; break; 292 case scUMaxExpr: OpStr = " umax "; break; 293 case scSMaxExpr: OpStr = " smax "; break; 294 case scUMinExpr: 295 OpStr = " umin "; 296 break; 297 case scSMinExpr: 298 OpStr = " smin "; 299 break; 300 } 301 OS << "("; 302 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 303 I != E; ++I) { 304 OS << **I; 305 if (std::next(I) != E) 306 OS << OpStr; 307 } 308 OS << ")"; 309 switch (NAry->getSCEVType()) { 310 case scAddExpr: 311 case scMulExpr: 312 if (NAry->hasNoUnsignedWrap()) 313 OS << "<nuw>"; 314 if (NAry->hasNoSignedWrap()) 315 OS << "<nsw>"; 316 } 317 return; 318 } 319 case scUDivExpr: { 320 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 321 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 322 return; 323 } 324 case scUnknown: { 325 const SCEVUnknown *U = cast<SCEVUnknown>(this); 326 Type *AllocTy; 327 if (U->isSizeOf(AllocTy)) { 328 OS << "sizeof(" << *AllocTy << ")"; 329 return; 330 } 331 if (U->isAlignOf(AllocTy)) { 332 OS << "alignof(" << *AllocTy << ")"; 333 return; 334 } 335 336 Type *CTy; 337 Constant *FieldNo; 338 if (U->isOffsetOf(CTy, FieldNo)) { 339 OS << "offsetof(" << *CTy << ", "; 340 FieldNo->printAsOperand(OS, false); 341 OS << ")"; 342 return; 343 } 344 345 // Otherwise just print it normally. 346 U->getValue()->printAsOperand(OS, false); 347 return; 348 } 349 case scCouldNotCompute: 350 OS << "***COULDNOTCOMPUTE***"; 351 return; 352 } 353 llvm_unreachable("Unknown SCEV kind!"); 354 } 355 356 Type *SCEV::getType() const { 357 switch (static_cast<SCEVTypes>(getSCEVType())) { 358 case scConstant: 359 return cast<SCEVConstant>(this)->getType(); 360 case scTruncate: 361 case scZeroExtend: 362 case scSignExtend: 363 return cast<SCEVCastExpr>(this)->getType(); 364 case scAddRecExpr: 365 case scMulExpr: 366 case scUMaxExpr: 367 case scSMaxExpr: 368 case scUMinExpr: 369 case scSMinExpr: 370 return cast<SCEVNAryExpr>(this)->getType(); 371 case scAddExpr: 372 return cast<SCEVAddExpr>(this)->getType(); 373 case scUDivExpr: 374 return cast<SCEVUDivExpr>(this)->getType(); 375 case scUnknown: 376 return cast<SCEVUnknown>(this)->getType(); 377 case scCouldNotCompute: 378 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 379 } 380 llvm_unreachable("Unknown SCEV kind!"); 381 } 382 383 bool SCEV::isZero() const { 384 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 385 return SC->getValue()->isZero(); 386 return false; 387 } 388 389 bool SCEV::isOne() const { 390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 391 return SC->getValue()->isOne(); 392 return false; 393 } 394 395 bool SCEV::isAllOnesValue() const { 396 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 397 return SC->getValue()->isMinusOne(); 398 return false; 399 } 400 401 bool SCEV::isNonConstantNegative() const { 402 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 403 if (!Mul) return false; 404 405 // If there is a constant factor, it will be first. 406 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 407 if (!SC) return false; 408 409 // Return true if the value is negative, this matches things like (-42 * V). 410 return SC->getAPInt().isNegative(); 411 } 412 413 SCEVCouldNotCompute::SCEVCouldNotCompute() : 414 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 415 416 bool SCEVCouldNotCompute::classof(const SCEV *S) { 417 return S->getSCEVType() == scCouldNotCompute; 418 } 419 420 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 421 FoldingSetNodeID ID; 422 ID.AddInteger(scConstant); 423 ID.AddPointer(V); 424 void *IP = nullptr; 425 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 426 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 427 UniqueSCEVs.InsertNode(S, IP); 428 return S; 429 } 430 431 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 432 return getConstant(ConstantInt::get(getContext(), Val)); 433 } 434 435 const SCEV * 436 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 437 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 438 return getConstant(ConstantInt::get(ITy, V, isSigned)); 439 } 440 441 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 442 unsigned SCEVTy, const SCEV *op, Type *ty) 443 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 444 445 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 446 const SCEV *op, Type *ty) 447 : SCEVCastExpr(ID, scTruncate, op, ty) { 448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 449 "Cannot truncate non-integer value!"); 450 } 451 452 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 453 const SCEV *op, Type *ty) 454 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 456 "Cannot zero extend non-integer value!"); 457 } 458 459 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 460 const SCEV *op, Type *ty) 461 : SCEVCastExpr(ID, scSignExtend, op, ty) { 462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 463 "Cannot sign extend non-integer value!"); 464 } 465 466 void SCEVUnknown::deleted() { 467 // Clear this SCEVUnknown from various maps. 468 SE->forgetMemoizedResults(this); 469 470 // Remove this SCEVUnknown from the uniquing map. 471 SE->UniqueSCEVs.RemoveNode(this); 472 473 // Release the value. 474 setValPtr(nullptr); 475 } 476 477 void SCEVUnknown::allUsesReplacedWith(Value *New) { 478 // Remove this SCEVUnknown from the uniquing map. 479 SE->UniqueSCEVs.RemoveNode(this); 480 481 // Update this SCEVUnknown to point to the new value. This is needed 482 // because there may still be outstanding SCEVs which still point to 483 // this SCEVUnknown. 484 setValPtr(New); 485 } 486 487 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 488 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 489 if (VCE->getOpcode() == Instruction::PtrToInt) 490 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 491 if (CE->getOpcode() == Instruction::GetElementPtr && 492 CE->getOperand(0)->isNullValue() && 493 CE->getNumOperands() == 2) 494 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 495 if (CI->isOne()) { 496 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 497 ->getElementType(); 498 return true; 499 } 500 501 return false; 502 } 503 504 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 505 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 506 if (VCE->getOpcode() == Instruction::PtrToInt) 507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 508 if (CE->getOpcode() == Instruction::GetElementPtr && 509 CE->getOperand(0)->isNullValue()) { 510 Type *Ty = 511 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 512 if (StructType *STy = dyn_cast<StructType>(Ty)) 513 if (!STy->isPacked() && 514 CE->getNumOperands() == 3 && 515 CE->getOperand(1)->isNullValue()) { 516 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 517 if (CI->isOne() && 518 STy->getNumElements() == 2 && 519 STy->getElementType(0)->isIntegerTy(1)) { 520 AllocTy = STy->getElementType(1); 521 return true; 522 } 523 } 524 } 525 526 return false; 527 } 528 529 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 530 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 531 if (VCE->getOpcode() == Instruction::PtrToInt) 532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 533 if (CE->getOpcode() == Instruction::GetElementPtr && 534 CE->getNumOperands() == 3 && 535 CE->getOperand(0)->isNullValue() && 536 CE->getOperand(1)->isNullValue()) { 537 Type *Ty = 538 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 539 // Ignore vector types here so that ScalarEvolutionExpander doesn't 540 // emit getelementptrs that index into vectors. 541 if (Ty->isStructTy() || Ty->isArrayTy()) { 542 CTy = Ty; 543 FieldNo = CE->getOperand(2); 544 return true; 545 } 546 } 547 548 return false; 549 } 550 551 //===----------------------------------------------------------------------===// 552 // SCEV Utilities 553 //===----------------------------------------------------------------------===// 554 555 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 556 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 557 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 558 /// have been previously deemed to be "equally complex" by this routine. It is 559 /// intended to avoid exponential time complexity in cases like: 560 /// 561 /// %a = f(%x, %y) 562 /// %b = f(%a, %a) 563 /// %c = f(%b, %b) 564 /// 565 /// %d = f(%x, %y) 566 /// %e = f(%d, %d) 567 /// %f = f(%e, %e) 568 /// 569 /// CompareValueComplexity(%f, %c) 570 /// 571 /// Since we do not continue running this routine on expression trees once we 572 /// have seen unequal values, there is no need to track them in the cache. 573 static int 574 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 575 const LoopInfo *const LI, Value *LV, Value *RV, 576 unsigned Depth) { 577 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 578 return 0; 579 580 // Order pointer values after integer values. This helps SCEVExpander form 581 // GEPs. 582 bool LIsPointer = LV->getType()->isPointerTy(), 583 RIsPointer = RV->getType()->isPointerTy(); 584 if (LIsPointer != RIsPointer) 585 return (int)LIsPointer - (int)RIsPointer; 586 587 // Compare getValueID values. 588 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 589 if (LID != RID) 590 return (int)LID - (int)RID; 591 592 // Sort arguments by their position. 593 if (const auto *LA = dyn_cast<Argument>(LV)) { 594 const auto *RA = cast<Argument>(RV); 595 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 596 return (int)LArgNo - (int)RArgNo; 597 } 598 599 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 600 const auto *RGV = cast<GlobalValue>(RV); 601 602 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 603 auto LT = GV->getLinkage(); 604 return !(GlobalValue::isPrivateLinkage(LT) || 605 GlobalValue::isInternalLinkage(LT)); 606 }; 607 608 // Use the names to distinguish the two values, but only if the 609 // names are semantically important. 610 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 611 return LGV->getName().compare(RGV->getName()); 612 } 613 614 // For instructions, compare their loop depth, and their operand count. This 615 // is pretty loose. 616 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 617 const auto *RInst = cast<Instruction>(RV); 618 619 // Compare loop depths. 620 const BasicBlock *LParent = LInst->getParent(), 621 *RParent = RInst->getParent(); 622 if (LParent != RParent) { 623 unsigned LDepth = LI->getLoopDepth(LParent), 624 RDepth = LI->getLoopDepth(RParent); 625 if (LDepth != RDepth) 626 return (int)LDepth - (int)RDepth; 627 } 628 629 // Compare the number of operands. 630 unsigned LNumOps = LInst->getNumOperands(), 631 RNumOps = RInst->getNumOperands(); 632 if (LNumOps != RNumOps) 633 return (int)LNumOps - (int)RNumOps; 634 635 for (unsigned Idx : seq(0u, LNumOps)) { 636 int Result = 637 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 638 RInst->getOperand(Idx), Depth + 1); 639 if (Result != 0) 640 return Result; 641 } 642 } 643 644 EqCacheValue.unionSets(LV, RV); 645 return 0; 646 } 647 648 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 649 // than RHS, respectively. A three-way result allows recursive comparisons to be 650 // more efficient. 651 static int CompareSCEVComplexity( 652 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 653 EquivalenceClasses<const Value *> &EqCacheValue, 654 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 655 DominatorTree &DT, unsigned Depth = 0) { 656 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 657 if (LHS == RHS) 658 return 0; 659 660 // Primarily, sort the SCEVs by their getSCEVType(). 661 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 662 if (LType != RType) 663 return (int)LType - (int)RType; 664 665 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 666 return 0; 667 // Aside from the getSCEVType() ordering, the particular ordering 668 // isn't very important except that it's beneficial to be consistent, 669 // so that (a + b) and (b + a) don't end up as different expressions. 670 switch (static_cast<SCEVTypes>(LType)) { 671 case scUnknown: { 672 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 673 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 674 675 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 676 RU->getValue(), Depth + 1); 677 if (X == 0) 678 EqCacheSCEV.unionSets(LHS, RHS); 679 return X; 680 } 681 682 case scConstant: { 683 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 684 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 685 686 // Compare constant values. 687 const APInt &LA = LC->getAPInt(); 688 const APInt &RA = RC->getAPInt(); 689 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 690 if (LBitWidth != RBitWidth) 691 return (int)LBitWidth - (int)RBitWidth; 692 return LA.ult(RA) ? -1 : 1; 693 } 694 695 case scAddRecExpr: { 696 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 697 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 698 699 // There is always a dominance between two recs that are used by one SCEV, 700 // so we can safely sort recs by loop header dominance. We require such 701 // order in getAddExpr. 702 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 703 if (LLoop != RLoop) { 704 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 705 assert(LHead != RHead && "Two loops share the same header?"); 706 if (DT.dominates(LHead, RHead)) 707 return 1; 708 else 709 assert(DT.dominates(RHead, LHead) && 710 "No dominance between recurrences used by one SCEV?"); 711 return -1; 712 } 713 714 // Addrec complexity grows with operand count. 715 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 716 if (LNumOps != RNumOps) 717 return (int)LNumOps - (int)RNumOps; 718 719 // Lexicographically compare. 720 for (unsigned i = 0; i != LNumOps; ++i) { 721 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 722 LA->getOperand(i), RA->getOperand(i), DT, 723 Depth + 1); 724 if (X != 0) 725 return X; 726 } 727 EqCacheSCEV.unionSets(LHS, RHS); 728 return 0; 729 } 730 731 case scAddExpr: 732 case scMulExpr: 733 case scSMaxExpr: 734 case scUMaxExpr: 735 case scSMinExpr: 736 case scUMinExpr: { 737 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 738 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 739 740 // Lexicographically compare n-ary expressions. 741 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 742 if (LNumOps != RNumOps) 743 return (int)LNumOps - (int)RNumOps; 744 745 for (unsigned i = 0; i != LNumOps; ++i) { 746 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 747 LC->getOperand(i), RC->getOperand(i), DT, 748 Depth + 1); 749 if (X != 0) 750 return X; 751 } 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return 0; 754 } 755 756 case scUDivExpr: { 757 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 758 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 759 760 // Lexicographically compare udiv expressions. 761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 762 RC->getLHS(), DT, Depth + 1); 763 if (X != 0) 764 return X; 765 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 766 RC->getRHS(), DT, Depth + 1); 767 if (X == 0) 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return X; 770 } 771 772 case scTruncate: 773 case scZeroExtend: 774 case scSignExtend: { 775 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 776 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 777 778 // Compare cast expressions by operand. 779 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 780 LC->getOperand(), RC->getOperand(), DT, 781 Depth + 1); 782 if (X == 0) 783 EqCacheSCEV.unionSets(LHS, RHS); 784 return X; 785 } 786 787 case scCouldNotCompute: 788 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 789 } 790 llvm_unreachable("Unknown SCEV kind!"); 791 } 792 793 /// Given a list of SCEV objects, order them by their complexity, and group 794 /// objects of the same complexity together by value. When this routine is 795 /// finished, we know that any duplicates in the vector are consecutive and that 796 /// complexity is monotonically increasing. 797 /// 798 /// Note that we go take special precautions to ensure that we get deterministic 799 /// results from this routine. In other words, we don't want the results of 800 /// this to depend on where the addresses of various SCEV objects happened to 801 /// land in memory. 802 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 803 LoopInfo *LI, DominatorTree &DT) { 804 if (Ops.size() < 2) return; // Noop 805 806 EquivalenceClasses<const SCEV *> EqCacheSCEV; 807 EquivalenceClasses<const Value *> EqCacheValue; 808 if (Ops.size() == 2) { 809 // This is the common case, which also happens to be trivially simple. 810 // Special case it. 811 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 812 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 813 std::swap(LHS, RHS); 814 return; 815 } 816 817 // Do the rough sort by complexity. 818 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 819 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 820 0; 821 }); 822 823 // Now that we are sorted by complexity, group elements of the same 824 // complexity. Note that this is, at worst, N^2, but the vector is likely to 825 // be extremely short in practice. Note that we take this approach because we 826 // do not want to depend on the addresses of the objects we are grouping. 827 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 828 const SCEV *S = Ops[i]; 829 unsigned Complexity = S->getSCEVType(); 830 831 // If there are any objects of the same complexity and same value as this 832 // one, group them. 833 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 834 if (Ops[j] == S) { // Found a duplicate. 835 // Move it to immediately after i'th element. 836 std::swap(Ops[i+1], Ops[j]); 837 ++i; // no need to rescan it. 838 if (i == e-2) return; // Done! 839 } 840 } 841 } 842 } 843 844 // Returns the size of the SCEV S. 845 static inline int sizeOfSCEV(const SCEV *S) { 846 struct FindSCEVSize { 847 int Size = 0; 848 849 FindSCEVSize() = default; 850 851 bool follow(const SCEV *S) { 852 ++Size; 853 // Keep looking at all operands of S. 854 return true; 855 } 856 857 bool isDone() const { 858 return false; 859 } 860 }; 861 862 FindSCEVSize F; 863 SCEVTraversal<FindSCEVSize> ST(F); 864 ST.visitAll(S); 865 return F.Size; 866 } 867 868 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 869 /// nodes. 870 static bool isHugeExpression(const SCEV *S) { 871 return S->getExpressionSize() >= HugeExprThreshold; 872 } 873 874 /// Returns true of \p Ops contains a huge SCEV (see definition above). 875 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 876 return any_of(Ops, isHugeExpression); 877 } 878 879 namespace { 880 881 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 882 public: 883 // Computes the Quotient and Remainder of the division of Numerator by 884 // Denominator. 885 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 886 const SCEV *Denominator, const SCEV **Quotient, 887 const SCEV **Remainder) { 888 assert(Numerator && Denominator && "Uninitialized SCEV"); 889 890 SCEVDivision D(SE, Numerator, Denominator); 891 892 // Check for the trivial case here to avoid having to check for it in the 893 // rest of the code. 894 if (Numerator == Denominator) { 895 *Quotient = D.One; 896 *Remainder = D.Zero; 897 return; 898 } 899 900 if (Numerator->isZero()) { 901 *Quotient = D.Zero; 902 *Remainder = D.Zero; 903 return; 904 } 905 906 // A simple case when N/1. The quotient is N. 907 if (Denominator->isOne()) { 908 *Quotient = Numerator; 909 *Remainder = D.Zero; 910 return; 911 } 912 913 // Split the Denominator when it is a product. 914 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 915 const SCEV *Q, *R; 916 *Quotient = Numerator; 917 for (const SCEV *Op : T->operands()) { 918 divide(SE, *Quotient, Op, &Q, &R); 919 *Quotient = Q; 920 921 // Bail out when the Numerator is not divisible by one of the terms of 922 // the Denominator. 923 if (!R->isZero()) { 924 *Quotient = D.Zero; 925 *Remainder = Numerator; 926 return; 927 } 928 } 929 *Remainder = D.Zero; 930 return; 931 } 932 933 D.visit(Numerator); 934 *Quotient = D.Quotient; 935 *Remainder = D.Remainder; 936 } 937 938 // Except in the trivial case described above, we do not know how to divide 939 // Expr by Denominator for the following functions with empty implementation. 940 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 941 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 942 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 943 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 944 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 945 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 946 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 947 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 948 void visitUnknown(const SCEVUnknown *Numerator) {} 949 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 950 951 void visitConstant(const SCEVConstant *Numerator) { 952 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 953 APInt NumeratorVal = Numerator->getAPInt(); 954 APInt DenominatorVal = D->getAPInt(); 955 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 956 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 957 958 if (NumeratorBW > DenominatorBW) 959 DenominatorVal = DenominatorVal.sext(NumeratorBW); 960 else if (NumeratorBW < DenominatorBW) 961 NumeratorVal = NumeratorVal.sext(DenominatorBW); 962 963 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 964 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 965 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 966 Quotient = SE.getConstant(QuotientVal); 967 Remainder = SE.getConstant(RemainderVal); 968 return; 969 } 970 } 971 972 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 973 const SCEV *StartQ, *StartR, *StepQ, *StepR; 974 if (!Numerator->isAffine()) 975 return cannotDivide(Numerator); 976 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 977 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 978 // Bail out if the types do not match. 979 Type *Ty = Denominator->getType(); 980 if (Ty != StartQ->getType() || Ty != StartR->getType() || 981 Ty != StepQ->getType() || Ty != StepR->getType()) 982 return cannotDivide(Numerator); 983 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 984 Numerator->getNoWrapFlags()); 985 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 986 Numerator->getNoWrapFlags()); 987 } 988 989 void visitAddExpr(const SCEVAddExpr *Numerator) { 990 SmallVector<const SCEV *, 2> Qs, Rs; 991 Type *Ty = Denominator->getType(); 992 993 for (const SCEV *Op : Numerator->operands()) { 994 const SCEV *Q, *R; 995 divide(SE, Op, Denominator, &Q, &R); 996 997 // Bail out if types do not match. 998 if (Ty != Q->getType() || Ty != R->getType()) 999 return cannotDivide(Numerator); 1000 1001 Qs.push_back(Q); 1002 Rs.push_back(R); 1003 } 1004 1005 if (Qs.size() == 1) { 1006 Quotient = Qs[0]; 1007 Remainder = Rs[0]; 1008 return; 1009 } 1010 1011 Quotient = SE.getAddExpr(Qs); 1012 Remainder = SE.getAddExpr(Rs); 1013 } 1014 1015 void visitMulExpr(const SCEVMulExpr *Numerator) { 1016 SmallVector<const SCEV *, 2> Qs; 1017 Type *Ty = Denominator->getType(); 1018 1019 bool FoundDenominatorTerm = false; 1020 for (const SCEV *Op : Numerator->operands()) { 1021 // Bail out if types do not match. 1022 if (Ty != Op->getType()) 1023 return cannotDivide(Numerator); 1024 1025 if (FoundDenominatorTerm) { 1026 Qs.push_back(Op); 1027 continue; 1028 } 1029 1030 // Check whether Denominator divides one of the product operands. 1031 const SCEV *Q, *R; 1032 divide(SE, Op, Denominator, &Q, &R); 1033 if (!R->isZero()) { 1034 Qs.push_back(Op); 1035 continue; 1036 } 1037 1038 // Bail out if types do not match. 1039 if (Ty != Q->getType()) 1040 return cannotDivide(Numerator); 1041 1042 FoundDenominatorTerm = true; 1043 Qs.push_back(Q); 1044 } 1045 1046 if (FoundDenominatorTerm) { 1047 Remainder = Zero; 1048 if (Qs.size() == 1) 1049 Quotient = Qs[0]; 1050 else 1051 Quotient = SE.getMulExpr(Qs); 1052 return; 1053 } 1054 1055 if (!isa<SCEVUnknown>(Denominator)) 1056 return cannotDivide(Numerator); 1057 1058 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1059 ValueToValueMap RewriteMap; 1060 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1061 cast<SCEVConstant>(Zero)->getValue(); 1062 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1063 1064 if (Remainder->isZero()) { 1065 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1066 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1067 cast<SCEVConstant>(One)->getValue(); 1068 Quotient = 1069 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1070 return; 1071 } 1072 1073 // Quotient is (Numerator - Remainder) divided by Denominator. 1074 const SCEV *Q, *R; 1075 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1076 // This SCEV does not seem to simplify: fail the division here. 1077 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1078 return cannotDivide(Numerator); 1079 divide(SE, Diff, Denominator, &Q, &R); 1080 if (R != Zero) 1081 return cannotDivide(Numerator); 1082 Quotient = Q; 1083 } 1084 1085 private: 1086 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1087 const SCEV *Denominator) 1088 : SE(S), Denominator(Denominator) { 1089 Zero = SE.getZero(Denominator->getType()); 1090 One = SE.getOne(Denominator->getType()); 1091 1092 // We generally do not know how to divide Expr by Denominator. We 1093 // initialize the division to a "cannot divide" state to simplify the rest 1094 // of the code. 1095 cannotDivide(Numerator); 1096 } 1097 1098 // Convenience function for giving up on the division. We set the quotient to 1099 // be equal to zero and the remainder to be equal to the numerator. 1100 void cannotDivide(const SCEV *Numerator) { 1101 Quotient = Zero; 1102 Remainder = Numerator; 1103 } 1104 1105 ScalarEvolution &SE; 1106 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1107 }; 1108 1109 } // end anonymous namespace 1110 1111 //===----------------------------------------------------------------------===// 1112 // Simple SCEV method implementations 1113 //===----------------------------------------------------------------------===// 1114 1115 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1116 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1117 ScalarEvolution &SE, 1118 Type *ResultTy) { 1119 // Handle the simplest case efficiently. 1120 if (K == 1) 1121 return SE.getTruncateOrZeroExtend(It, ResultTy); 1122 1123 // We are using the following formula for BC(It, K): 1124 // 1125 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1126 // 1127 // Suppose, W is the bitwidth of the return value. We must be prepared for 1128 // overflow. Hence, we must assure that the result of our computation is 1129 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1130 // safe in modular arithmetic. 1131 // 1132 // However, this code doesn't use exactly that formula; the formula it uses 1133 // is something like the following, where T is the number of factors of 2 in 1134 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1135 // exponentiation: 1136 // 1137 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1138 // 1139 // This formula is trivially equivalent to the previous formula. However, 1140 // this formula can be implemented much more efficiently. The trick is that 1141 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1142 // arithmetic. To do exact division in modular arithmetic, all we have 1143 // to do is multiply by the inverse. Therefore, this step can be done at 1144 // width W. 1145 // 1146 // The next issue is how to safely do the division by 2^T. The way this 1147 // is done is by doing the multiplication step at a width of at least W + T 1148 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1149 // when we perform the division by 2^T (which is equivalent to a right shift 1150 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1151 // truncated out after the division by 2^T. 1152 // 1153 // In comparison to just directly using the first formula, this technique 1154 // is much more efficient; using the first formula requires W * K bits, 1155 // but this formula less than W + K bits. Also, the first formula requires 1156 // a division step, whereas this formula only requires multiplies and shifts. 1157 // 1158 // It doesn't matter whether the subtraction step is done in the calculation 1159 // width or the input iteration count's width; if the subtraction overflows, 1160 // the result must be zero anyway. We prefer here to do it in the width of 1161 // the induction variable because it helps a lot for certain cases; CodeGen 1162 // isn't smart enough to ignore the overflow, which leads to much less 1163 // efficient code if the width of the subtraction is wider than the native 1164 // register width. 1165 // 1166 // (It's possible to not widen at all by pulling out factors of 2 before 1167 // the multiplication; for example, K=2 can be calculated as 1168 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1169 // extra arithmetic, so it's not an obvious win, and it gets 1170 // much more complicated for K > 3.) 1171 1172 // Protection from insane SCEVs; this bound is conservative, 1173 // but it probably doesn't matter. 1174 if (K > 1000) 1175 return SE.getCouldNotCompute(); 1176 1177 unsigned W = SE.getTypeSizeInBits(ResultTy); 1178 1179 // Calculate K! / 2^T and T; we divide out the factors of two before 1180 // multiplying for calculating K! / 2^T to avoid overflow. 1181 // Other overflow doesn't matter because we only care about the bottom 1182 // W bits of the result. 1183 APInt OddFactorial(W, 1); 1184 unsigned T = 1; 1185 for (unsigned i = 3; i <= K; ++i) { 1186 APInt Mult(W, i); 1187 unsigned TwoFactors = Mult.countTrailingZeros(); 1188 T += TwoFactors; 1189 Mult.lshrInPlace(TwoFactors); 1190 OddFactorial *= Mult; 1191 } 1192 1193 // We need at least W + T bits for the multiplication step 1194 unsigned CalculationBits = W + T; 1195 1196 // Calculate 2^T, at width T+W. 1197 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1198 1199 // Calculate the multiplicative inverse of K! / 2^T; 1200 // this multiplication factor will perform the exact division by 1201 // K! / 2^T. 1202 APInt Mod = APInt::getSignedMinValue(W+1); 1203 APInt MultiplyFactor = OddFactorial.zext(W+1); 1204 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1205 MultiplyFactor = MultiplyFactor.trunc(W); 1206 1207 // Calculate the product, at width T+W 1208 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1209 CalculationBits); 1210 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1211 for (unsigned i = 1; i != K; ++i) { 1212 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1213 Dividend = SE.getMulExpr(Dividend, 1214 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1215 } 1216 1217 // Divide by 2^T 1218 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1219 1220 // Truncate the result, and divide by K! / 2^T. 1221 1222 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1223 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1224 } 1225 1226 /// Return the value of this chain of recurrences at the specified iteration 1227 /// number. We can evaluate this recurrence by multiplying each element in the 1228 /// chain by the binomial coefficient corresponding to it. In other words, we 1229 /// can evaluate {A,+,B,+,C,+,D} as: 1230 /// 1231 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1232 /// 1233 /// where BC(It, k) stands for binomial coefficient. 1234 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1235 ScalarEvolution &SE) const { 1236 const SCEV *Result = getStart(); 1237 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1238 // The computation is correct in the face of overflow provided that the 1239 // multiplication is performed _after_ the evaluation of the binomial 1240 // coefficient. 1241 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1242 if (isa<SCEVCouldNotCompute>(Coeff)) 1243 return Coeff; 1244 1245 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1246 } 1247 return Result; 1248 } 1249 1250 //===----------------------------------------------------------------------===// 1251 // SCEV Expression folder implementations 1252 //===----------------------------------------------------------------------===// 1253 1254 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1255 unsigned Depth) { 1256 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1257 "This is not a truncating conversion!"); 1258 assert(isSCEVable(Ty) && 1259 "This is not a conversion to a SCEVable type!"); 1260 Ty = getEffectiveSCEVType(Ty); 1261 1262 FoldingSetNodeID ID; 1263 ID.AddInteger(scTruncate); 1264 ID.AddPointer(Op); 1265 ID.AddPointer(Ty); 1266 void *IP = nullptr; 1267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1268 1269 // Fold if the operand is constant. 1270 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1271 return getConstant( 1272 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1273 1274 // trunc(trunc(x)) --> trunc(x) 1275 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1276 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1277 1278 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1279 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1280 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1281 1282 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1283 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1284 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1285 1286 if (Depth > MaxCastDepth) { 1287 SCEV *S = 1288 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1289 UniqueSCEVs.InsertNode(S, IP); 1290 addToLoopUseLists(S); 1291 return S; 1292 } 1293 1294 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1295 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1296 // if after transforming we have at most one truncate, not counting truncates 1297 // that replace other casts. 1298 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1299 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1300 SmallVector<const SCEV *, 4> Operands; 1301 unsigned numTruncs = 0; 1302 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1303 ++i) { 1304 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1305 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1306 numTruncs++; 1307 Operands.push_back(S); 1308 } 1309 if (numTruncs < 2) { 1310 if (isa<SCEVAddExpr>(Op)) 1311 return getAddExpr(Operands); 1312 else if (isa<SCEVMulExpr>(Op)) 1313 return getMulExpr(Operands); 1314 else 1315 llvm_unreachable("Unexpected SCEV type for Op."); 1316 } 1317 // Although we checked in the beginning that ID is not in the cache, it is 1318 // possible that during recursion and different modification ID was inserted 1319 // into the cache. So if we find it, just return it. 1320 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1321 return S; 1322 } 1323 1324 // If the input value is a chrec scev, truncate the chrec's operands. 1325 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1326 SmallVector<const SCEV *, 4> Operands; 1327 for (const SCEV *Op : AddRec->operands()) 1328 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1329 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1330 } 1331 1332 // The cast wasn't folded; create an explicit cast node. We can reuse 1333 // the existing insert position since if we get here, we won't have 1334 // made any changes which would invalidate it. 1335 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1336 Op, Ty); 1337 UniqueSCEVs.InsertNode(S, IP); 1338 addToLoopUseLists(S); 1339 return S; 1340 } 1341 1342 // Get the limit of a recurrence such that incrementing by Step cannot cause 1343 // signed overflow as long as the value of the recurrence within the 1344 // loop does not exceed this limit before incrementing. 1345 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1346 ICmpInst::Predicate *Pred, 1347 ScalarEvolution *SE) { 1348 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1349 if (SE->isKnownPositive(Step)) { 1350 *Pred = ICmpInst::ICMP_SLT; 1351 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1352 SE->getSignedRangeMax(Step)); 1353 } 1354 if (SE->isKnownNegative(Step)) { 1355 *Pred = ICmpInst::ICMP_SGT; 1356 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1357 SE->getSignedRangeMin(Step)); 1358 } 1359 return nullptr; 1360 } 1361 1362 // Get the limit of a recurrence such that incrementing by Step cannot cause 1363 // unsigned overflow as long as the value of the recurrence within the loop does 1364 // not exceed this limit before incrementing. 1365 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1366 ICmpInst::Predicate *Pred, 1367 ScalarEvolution *SE) { 1368 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1369 *Pred = ICmpInst::ICMP_ULT; 1370 1371 return SE->getConstant(APInt::getMinValue(BitWidth) - 1372 SE->getUnsignedRangeMax(Step)); 1373 } 1374 1375 namespace { 1376 1377 struct ExtendOpTraitsBase { 1378 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1379 unsigned); 1380 }; 1381 1382 // Used to make code generic over signed and unsigned overflow. 1383 template <typename ExtendOp> struct ExtendOpTraits { 1384 // Members present: 1385 // 1386 // static const SCEV::NoWrapFlags WrapType; 1387 // 1388 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1389 // 1390 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1391 // ICmpInst::Predicate *Pred, 1392 // ScalarEvolution *SE); 1393 }; 1394 1395 template <> 1396 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1397 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1398 1399 static const GetExtendExprTy GetExtendExpr; 1400 1401 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1402 ICmpInst::Predicate *Pred, 1403 ScalarEvolution *SE) { 1404 return getSignedOverflowLimitForStep(Step, Pred, SE); 1405 } 1406 }; 1407 1408 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1409 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1410 1411 template <> 1412 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1413 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1414 1415 static const GetExtendExprTy GetExtendExpr; 1416 1417 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1418 ICmpInst::Predicate *Pred, 1419 ScalarEvolution *SE) { 1420 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1421 } 1422 }; 1423 1424 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1425 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1426 1427 } // end anonymous namespace 1428 1429 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1430 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1431 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1432 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1433 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1434 // expression "Step + sext/zext(PreIncAR)" is congruent with 1435 // "sext/zext(PostIncAR)" 1436 template <typename ExtendOpTy> 1437 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1438 ScalarEvolution *SE, unsigned Depth) { 1439 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1440 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1441 1442 const Loop *L = AR->getLoop(); 1443 const SCEV *Start = AR->getStart(); 1444 const SCEV *Step = AR->getStepRecurrence(*SE); 1445 1446 // Check for a simple looking step prior to loop entry. 1447 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1448 if (!SA) 1449 return nullptr; 1450 1451 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1452 // subtraction is expensive. For this purpose, perform a quick and dirty 1453 // difference, by checking for Step in the operand list. 1454 SmallVector<const SCEV *, 4> DiffOps; 1455 for (const SCEV *Op : SA->operands()) 1456 if (Op != Step) 1457 DiffOps.push_back(Op); 1458 1459 if (DiffOps.size() == SA->getNumOperands()) 1460 return nullptr; 1461 1462 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1463 // `Step`: 1464 1465 // 1. NSW/NUW flags on the step increment. 1466 auto PreStartFlags = 1467 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1468 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1469 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1470 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1471 1472 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1473 // "S+X does not sign/unsign-overflow". 1474 // 1475 1476 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1477 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1478 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1479 return PreStart; 1480 1481 // 2. Direct overflow check on the step operation's expression. 1482 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1483 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1484 const SCEV *OperandExtendedStart = 1485 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1486 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1487 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1488 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1489 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1490 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1491 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1492 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1493 } 1494 return PreStart; 1495 } 1496 1497 // 3. Loop precondition. 1498 ICmpInst::Predicate Pred; 1499 const SCEV *OverflowLimit = 1500 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1501 1502 if (OverflowLimit && 1503 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1504 return PreStart; 1505 1506 return nullptr; 1507 } 1508 1509 // Get the normalized zero or sign extended expression for this AddRec's Start. 1510 template <typename ExtendOpTy> 1511 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1512 ScalarEvolution *SE, 1513 unsigned Depth) { 1514 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1515 1516 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1517 if (!PreStart) 1518 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1519 1520 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1521 Depth), 1522 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1523 } 1524 1525 // Try to prove away overflow by looking at "nearby" add recurrences. A 1526 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1527 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1528 // 1529 // Formally: 1530 // 1531 // {S,+,X} == {S-T,+,X} + T 1532 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1533 // 1534 // If ({S-T,+,X} + T) does not overflow ... (1) 1535 // 1536 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1537 // 1538 // If {S-T,+,X} does not overflow ... (2) 1539 // 1540 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1541 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1542 // 1543 // If (S-T)+T does not overflow ... (3) 1544 // 1545 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1546 // == {Ext(S),+,Ext(X)} == LHS 1547 // 1548 // Thus, if (1), (2) and (3) are true for some T, then 1549 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1550 // 1551 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1552 // does not overflow" restricted to the 0th iteration. Therefore we only need 1553 // to check for (1) and (2). 1554 // 1555 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1556 // is `Delta` (defined below). 1557 template <typename ExtendOpTy> 1558 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1559 const SCEV *Step, 1560 const Loop *L) { 1561 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1562 1563 // We restrict `Start` to a constant to prevent SCEV from spending too much 1564 // time here. It is correct (but more expensive) to continue with a 1565 // non-constant `Start` and do a general SCEV subtraction to compute 1566 // `PreStart` below. 1567 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1568 if (!StartC) 1569 return false; 1570 1571 APInt StartAI = StartC->getAPInt(); 1572 1573 for (unsigned Delta : {-2, -1, 1, 2}) { 1574 const SCEV *PreStart = getConstant(StartAI - Delta); 1575 1576 FoldingSetNodeID ID; 1577 ID.AddInteger(scAddRecExpr); 1578 ID.AddPointer(PreStart); 1579 ID.AddPointer(Step); 1580 ID.AddPointer(L); 1581 void *IP = nullptr; 1582 const auto *PreAR = 1583 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1584 1585 // Give up if we don't already have the add recurrence we need because 1586 // actually constructing an add recurrence is relatively expensive. 1587 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1588 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1589 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1590 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1591 DeltaS, &Pred, this); 1592 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1593 return true; 1594 } 1595 } 1596 1597 return false; 1598 } 1599 1600 // Finds an integer D for an expression (C + x + y + ...) such that the top 1601 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1602 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1603 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1604 // the (C + x + y + ...) expression is \p WholeAddExpr. 1605 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1606 const SCEVConstant *ConstantTerm, 1607 const SCEVAddExpr *WholeAddExpr) { 1608 const APInt C = ConstantTerm->getAPInt(); 1609 const unsigned BitWidth = C.getBitWidth(); 1610 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1611 uint32_t TZ = BitWidth; 1612 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1613 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1614 if (TZ) { 1615 // Set D to be as many least significant bits of C as possible while still 1616 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1617 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1618 } 1619 return APInt(BitWidth, 0); 1620 } 1621 1622 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1623 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1624 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1625 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1626 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1627 const APInt &ConstantStart, 1628 const SCEV *Step) { 1629 const unsigned BitWidth = ConstantStart.getBitWidth(); 1630 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1631 if (TZ) 1632 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1633 : ConstantStart; 1634 return APInt(BitWidth, 0); 1635 } 1636 1637 const SCEV * 1638 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1639 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1640 "This is not an extending conversion!"); 1641 assert(isSCEVable(Ty) && 1642 "This is not a conversion to a SCEVable type!"); 1643 Ty = getEffectiveSCEVType(Ty); 1644 1645 // Fold if the operand is constant. 1646 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1647 return getConstant( 1648 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1649 1650 // zext(zext(x)) --> zext(x) 1651 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1652 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1653 1654 // Before doing any expensive analysis, check to see if we've already 1655 // computed a SCEV for this Op and Ty. 1656 FoldingSetNodeID ID; 1657 ID.AddInteger(scZeroExtend); 1658 ID.AddPointer(Op); 1659 ID.AddPointer(Ty); 1660 void *IP = nullptr; 1661 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1662 if (Depth > MaxCastDepth) { 1663 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1664 Op, Ty); 1665 UniqueSCEVs.InsertNode(S, IP); 1666 addToLoopUseLists(S); 1667 return S; 1668 } 1669 1670 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1671 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1672 // It's possible the bits taken off by the truncate were all zero bits. If 1673 // so, we should be able to simplify this further. 1674 const SCEV *X = ST->getOperand(); 1675 ConstantRange CR = getUnsignedRange(X); 1676 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1677 unsigned NewBits = getTypeSizeInBits(Ty); 1678 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1679 CR.zextOrTrunc(NewBits))) 1680 return getTruncateOrZeroExtend(X, Ty, Depth); 1681 } 1682 1683 // If the input value is a chrec scev, and we can prove that the value 1684 // did not overflow the old, smaller, value, we can zero extend all of the 1685 // operands (often constants). This allows analysis of something like 1686 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1687 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1688 if (AR->isAffine()) { 1689 const SCEV *Start = AR->getStart(); 1690 const SCEV *Step = AR->getStepRecurrence(*this); 1691 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1692 const Loop *L = AR->getLoop(); 1693 1694 if (!AR->hasNoUnsignedWrap()) { 1695 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1696 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1697 } 1698 1699 // If we have special knowledge that this addrec won't overflow, 1700 // we don't need to do any further analysis. 1701 if (AR->hasNoUnsignedWrap()) 1702 return getAddRecExpr( 1703 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1704 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1705 1706 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1707 // Note that this serves two purposes: It filters out loops that are 1708 // simply not analyzable, and it covers the case where this code is 1709 // being called from within backedge-taken count analysis, such that 1710 // attempting to ask for the backedge-taken count would likely result 1711 // in infinite recursion. In the later case, the analysis code will 1712 // cope with a conservative value, and it will take care to purge 1713 // that value once it has finished. 1714 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1715 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1716 // Manually compute the final value for AR, checking for 1717 // overflow. 1718 1719 // Check whether the backedge-taken count can be losslessly casted to 1720 // the addrec's type. The count is always unsigned. 1721 const SCEV *CastedMaxBECount = 1722 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1723 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1724 CastedMaxBECount, MaxBECount->getType(), Depth); 1725 if (MaxBECount == RecastedMaxBECount) { 1726 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1727 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1728 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1729 SCEV::FlagAnyWrap, Depth + 1); 1730 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1731 SCEV::FlagAnyWrap, 1732 Depth + 1), 1733 WideTy, Depth + 1); 1734 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1735 const SCEV *WideMaxBECount = 1736 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1737 const SCEV *OperandExtendedAdd = 1738 getAddExpr(WideStart, 1739 getMulExpr(WideMaxBECount, 1740 getZeroExtendExpr(Step, WideTy, Depth + 1), 1741 SCEV::FlagAnyWrap, Depth + 1), 1742 SCEV::FlagAnyWrap, Depth + 1); 1743 if (ZAdd == OperandExtendedAdd) { 1744 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1745 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1746 // Return the expression with the addrec on the outside. 1747 return getAddRecExpr( 1748 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1749 Depth + 1), 1750 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1751 AR->getNoWrapFlags()); 1752 } 1753 // Similar to above, only this time treat the step value as signed. 1754 // This covers loops that count down. 1755 OperandExtendedAdd = 1756 getAddExpr(WideStart, 1757 getMulExpr(WideMaxBECount, 1758 getSignExtendExpr(Step, WideTy, Depth + 1), 1759 SCEV::FlagAnyWrap, Depth + 1), 1760 SCEV::FlagAnyWrap, Depth + 1); 1761 if (ZAdd == OperandExtendedAdd) { 1762 // Cache knowledge of AR NW, which is propagated to this AddRec. 1763 // Negative step causes unsigned wrap, but it still can't self-wrap. 1764 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1765 // Return the expression with the addrec on the outside. 1766 return getAddRecExpr( 1767 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1768 Depth + 1), 1769 getSignExtendExpr(Step, Ty, Depth + 1), L, 1770 AR->getNoWrapFlags()); 1771 } 1772 } 1773 } 1774 1775 // Normally, in the cases we can prove no-overflow via a 1776 // backedge guarding condition, we can also compute a backedge 1777 // taken count for the loop. The exceptions are assumptions and 1778 // guards present in the loop -- SCEV is not great at exploiting 1779 // these to compute max backedge taken counts, but can still use 1780 // these to prove lack of overflow. Use this fact to avoid 1781 // doing extra work that may not pay off. 1782 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1783 !AC.assumptions().empty()) { 1784 // If the backedge is guarded by a comparison with the pre-inc 1785 // value the addrec is safe. Also, if the entry is guarded by 1786 // a comparison with the start value and the backedge is 1787 // guarded by a comparison with the post-inc value, the addrec 1788 // is safe. 1789 if (isKnownPositive(Step)) { 1790 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1791 getUnsignedRangeMax(Step)); 1792 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1793 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1794 // Cache knowledge of AR NUW, which is propagated to this 1795 // AddRec. 1796 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1797 // Return the expression with the addrec on the outside. 1798 return getAddRecExpr( 1799 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1800 Depth + 1), 1801 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1802 AR->getNoWrapFlags()); 1803 } 1804 } else if (isKnownNegative(Step)) { 1805 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1806 getSignedRangeMin(Step)); 1807 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1808 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1809 // Cache knowledge of AR NW, which is propagated to this 1810 // AddRec. Negative step causes unsigned wrap, but it 1811 // still can't self-wrap. 1812 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1813 // Return the expression with the addrec on the outside. 1814 return getAddRecExpr( 1815 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1816 Depth + 1), 1817 getSignExtendExpr(Step, Ty, Depth + 1), L, 1818 AR->getNoWrapFlags()); 1819 } 1820 } 1821 } 1822 1823 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1824 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1825 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1826 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1827 const APInt &C = SC->getAPInt(); 1828 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1829 if (D != 0) { 1830 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1831 const SCEV *SResidual = 1832 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1833 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1834 return getAddExpr(SZExtD, SZExtR, 1835 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1836 Depth + 1); 1837 } 1838 } 1839 1840 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1841 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1842 return getAddRecExpr( 1843 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1844 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1845 } 1846 } 1847 1848 // zext(A % B) --> zext(A) % zext(B) 1849 { 1850 const SCEV *LHS; 1851 const SCEV *RHS; 1852 if (matchURem(Op, LHS, RHS)) 1853 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1854 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1855 } 1856 1857 // zext(A / B) --> zext(A) / zext(B). 1858 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1859 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1860 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1861 1862 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1863 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1864 if (SA->hasNoUnsignedWrap()) { 1865 // If the addition does not unsign overflow then we can, by definition, 1866 // commute the zero extension with the addition operation. 1867 SmallVector<const SCEV *, 4> Ops; 1868 for (const auto *Op : SA->operands()) 1869 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1870 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1871 } 1872 1873 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1874 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1875 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1876 // 1877 // Often address arithmetics contain expressions like 1878 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1879 // This transformation is useful while proving that such expressions are 1880 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1881 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1882 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1883 if (D != 0) { 1884 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1885 const SCEV *SResidual = 1886 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1887 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1888 return getAddExpr(SZExtD, SZExtR, 1889 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1890 Depth + 1); 1891 } 1892 } 1893 } 1894 1895 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1896 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1897 if (SM->hasNoUnsignedWrap()) { 1898 // If the multiply does not unsign overflow then we can, by definition, 1899 // commute the zero extension with the multiply operation. 1900 SmallVector<const SCEV *, 4> Ops; 1901 for (const auto *Op : SM->operands()) 1902 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1903 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1904 } 1905 1906 // zext(2^K * (trunc X to iN)) to iM -> 1907 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1908 // 1909 // Proof: 1910 // 1911 // zext(2^K * (trunc X to iN)) to iM 1912 // = zext((trunc X to iN) << K) to iM 1913 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1914 // (because shl removes the top K bits) 1915 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1916 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1917 // 1918 if (SM->getNumOperands() == 2) 1919 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1920 if (MulLHS->getAPInt().isPowerOf2()) 1921 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1922 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1923 MulLHS->getAPInt().logBase2(); 1924 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1925 return getMulExpr( 1926 getZeroExtendExpr(MulLHS, Ty), 1927 getZeroExtendExpr( 1928 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1929 SCEV::FlagNUW, Depth + 1); 1930 } 1931 } 1932 1933 // The cast wasn't folded; create an explicit cast node. 1934 // Recompute the insert position, as it may have been invalidated. 1935 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1936 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1937 Op, Ty); 1938 UniqueSCEVs.InsertNode(S, IP); 1939 addToLoopUseLists(S); 1940 return S; 1941 } 1942 1943 const SCEV * 1944 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1945 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1946 "This is not an extending conversion!"); 1947 assert(isSCEVable(Ty) && 1948 "This is not a conversion to a SCEVable type!"); 1949 Ty = getEffectiveSCEVType(Ty); 1950 1951 // Fold if the operand is constant. 1952 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1953 return getConstant( 1954 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1955 1956 // sext(sext(x)) --> sext(x) 1957 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1958 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1959 1960 // sext(zext(x)) --> zext(x) 1961 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1962 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1963 1964 // Before doing any expensive analysis, check to see if we've already 1965 // computed a SCEV for this Op and Ty. 1966 FoldingSetNodeID ID; 1967 ID.AddInteger(scSignExtend); 1968 ID.AddPointer(Op); 1969 ID.AddPointer(Ty); 1970 void *IP = nullptr; 1971 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1972 // Limit recursion depth. 1973 if (Depth > MaxCastDepth) { 1974 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1975 Op, Ty); 1976 UniqueSCEVs.InsertNode(S, IP); 1977 addToLoopUseLists(S); 1978 return S; 1979 } 1980 1981 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1982 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1983 // It's possible the bits taken off by the truncate were all sign bits. If 1984 // so, we should be able to simplify this further. 1985 const SCEV *X = ST->getOperand(); 1986 ConstantRange CR = getSignedRange(X); 1987 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1988 unsigned NewBits = getTypeSizeInBits(Ty); 1989 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1990 CR.sextOrTrunc(NewBits))) 1991 return getTruncateOrSignExtend(X, Ty, Depth); 1992 } 1993 1994 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1995 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1996 if (SA->hasNoSignedWrap()) { 1997 // If the addition does not sign overflow then we can, by definition, 1998 // commute the sign extension with the addition operation. 1999 SmallVector<const SCEV *, 4> Ops; 2000 for (const auto *Op : SA->operands()) 2001 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2002 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2003 } 2004 2005 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2006 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2007 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2008 // 2009 // For instance, this will bring two seemingly different expressions: 2010 // 1 + sext(5 + 20 * %x + 24 * %y) and 2011 // sext(6 + 20 * %x + 24 * %y) 2012 // to the same form: 2013 // 2 + sext(4 + 20 * %x + 24 * %y) 2014 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2015 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2016 if (D != 0) { 2017 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2018 const SCEV *SResidual = 2019 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2020 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2021 return getAddExpr(SSExtD, SSExtR, 2022 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2023 Depth + 1); 2024 } 2025 } 2026 } 2027 // If the input value is a chrec scev, and we can prove that the value 2028 // did not overflow the old, smaller, value, we can sign extend all of the 2029 // operands (often constants). This allows analysis of something like 2030 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2031 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2032 if (AR->isAffine()) { 2033 const SCEV *Start = AR->getStart(); 2034 const SCEV *Step = AR->getStepRecurrence(*this); 2035 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2036 const Loop *L = AR->getLoop(); 2037 2038 if (!AR->hasNoSignedWrap()) { 2039 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2040 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2041 } 2042 2043 // If we have special knowledge that this addrec won't overflow, 2044 // we don't need to do any further analysis. 2045 if (AR->hasNoSignedWrap()) 2046 return getAddRecExpr( 2047 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2048 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2049 2050 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2051 // Note that this serves two purposes: It filters out loops that are 2052 // simply not analyzable, and it covers the case where this code is 2053 // being called from within backedge-taken count analysis, such that 2054 // attempting to ask for the backedge-taken count would likely result 2055 // in infinite recursion. In the later case, the analysis code will 2056 // cope with a conservative value, and it will take care to purge 2057 // that value once it has finished. 2058 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2059 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2060 // Manually compute the final value for AR, checking for 2061 // overflow. 2062 2063 // Check whether the backedge-taken count can be losslessly casted to 2064 // the addrec's type. The count is always unsigned. 2065 const SCEV *CastedMaxBECount = 2066 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2067 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2068 CastedMaxBECount, MaxBECount->getType(), Depth); 2069 if (MaxBECount == RecastedMaxBECount) { 2070 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2071 // Check whether Start+Step*MaxBECount has no signed overflow. 2072 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2073 SCEV::FlagAnyWrap, Depth + 1); 2074 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2075 SCEV::FlagAnyWrap, 2076 Depth + 1), 2077 WideTy, Depth + 1); 2078 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2079 const SCEV *WideMaxBECount = 2080 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2081 const SCEV *OperandExtendedAdd = 2082 getAddExpr(WideStart, 2083 getMulExpr(WideMaxBECount, 2084 getSignExtendExpr(Step, WideTy, Depth + 1), 2085 SCEV::FlagAnyWrap, Depth + 1), 2086 SCEV::FlagAnyWrap, Depth + 1); 2087 if (SAdd == OperandExtendedAdd) { 2088 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2089 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2090 // Return the expression with the addrec on the outside. 2091 return getAddRecExpr( 2092 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2093 Depth + 1), 2094 getSignExtendExpr(Step, Ty, Depth + 1), L, 2095 AR->getNoWrapFlags()); 2096 } 2097 // Similar to above, only this time treat the step value as unsigned. 2098 // This covers loops that count up with an unsigned step. 2099 OperandExtendedAdd = 2100 getAddExpr(WideStart, 2101 getMulExpr(WideMaxBECount, 2102 getZeroExtendExpr(Step, WideTy, Depth + 1), 2103 SCEV::FlagAnyWrap, Depth + 1), 2104 SCEV::FlagAnyWrap, Depth + 1); 2105 if (SAdd == OperandExtendedAdd) { 2106 // If AR wraps around then 2107 // 2108 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2109 // => SAdd != OperandExtendedAdd 2110 // 2111 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2112 // (SAdd == OperandExtendedAdd => AR is NW) 2113 2114 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2115 2116 // Return the expression with the addrec on the outside. 2117 return getAddRecExpr( 2118 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2119 Depth + 1), 2120 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2121 AR->getNoWrapFlags()); 2122 } 2123 } 2124 } 2125 2126 // Normally, in the cases we can prove no-overflow via a 2127 // backedge guarding condition, we can also compute a backedge 2128 // taken count for the loop. The exceptions are assumptions and 2129 // guards present in the loop -- SCEV is not great at exploiting 2130 // these to compute max backedge taken counts, but can still use 2131 // these to prove lack of overflow. Use this fact to avoid 2132 // doing extra work that may not pay off. 2133 2134 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2135 !AC.assumptions().empty()) { 2136 // If the backedge is guarded by a comparison with the pre-inc 2137 // value the addrec is safe. Also, if the entry is guarded by 2138 // a comparison with the start value and the backedge is 2139 // guarded by a comparison with the post-inc value, the addrec 2140 // is safe. 2141 ICmpInst::Predicate Pred; 2142 const SCEV *OverflowLimit = 2143 getSignedOverflowLimitForStep(Step, &Pred, this); 2144 if (OverflowLimit && 2145 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2146 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2147 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2148 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2149 return getAddRecExpr( 2150 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2151 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2152 } 2153 } 2154 2155 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2156 // if D + (C - D + Step * n) could be proven to not signed wrap 2157 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2158 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2159 const APInt &C = SC->getAPInt(); 2160 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2161 if (D != 0) { 2162 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2163 const SCEV *SResidual = 2164 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2165 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2166 return getAddExpr(SSExtD, SSExtR, 2167 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2168 Depth + 1); 2169 } 2170 } 2171 2172 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2173 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2174 return getAddRecExpr( 2175 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2176 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2177 } 2178 } 2179 2180 // If the input value is provably positive and we could not simplify 2181 // away the sext build a zext instead. 2182 if (isKnownNonNegative(Op)) 2183 return getZeroExtendExpr(Op, Ty, Depth + 1); 2184 2185 // The cast wasn't folded; create an explicit cast node. 2186 // Recompute the insert position, as it may have been invalidated. 2187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2188 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2189 Op, Ty); 2190 UniqueSCEVs.InsertNode(S, IP); 2191 addToLoopUseLists(S); 2192 return S; 2193 } 2194 2195 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2196 /// unspecified bits out to the given type. 2197 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2198 Type *Ty) { 2199 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2200 "This is not an extending conversion!"); 2201 assert(isSCEVable(Ty) && 2202 "This is not a conversion to a SCEVable type!"); 2203 Ty = getEffectiveSCEVType(Ty); 2204 2205 // Sign-extend negative constants. 2206 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2207 if (SC->getAPInt().isNegative()) 2208 return getSignExtendExpr(Op, Ty); 2209 2210 // Peel off a truncate cast. 2211 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2212 const SCEV *NewOp = T->getOperand(); 2213 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2214 return getAnyExtendExpr(NewOp, Ty); 2215 return getTruncateOrNoop(NewOp, Ty); 2216 } 2217 2218 // Next try a zext cast. If the cast is folded, use it. 2219 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2220 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2221 return ZExt; 2222 2223 // Next try a sext cast. If the cast is folded, use it. 2224 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2225 if (!isa<SCEVSignExtendExpr>(SExt)) 2226 return SExt; 2227 2228 // Force the cast to be folded into the operands of an addrec. 2229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2230 SmallVector<const SCEV *, 4> Ops; 2231 for (const SCEV *Op : AR->operands()) 2232 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2233 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2234 } 2235 2236 // If the expression is obviously signed, use the sext cast value. 2237 if (isa<SCEVSMaxExpr>(Op)) 2238 return SExt; 2239 2240 // Absent any other information, use the zext cast value. 2241 return ZExt; 2242 } 2243 2244 /// Process the given Ops list, which is a list of operands to be added under 2245 /// the given scale, update the given map. This is a helper function for 2246 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2247 /// that would form an add expression like this: 2248 /// 2249 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2250 /// 2251 /// where A and B are constants, update the map with these values: 2252 /// 2253 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2254 /// 2255 /// and add 13 + A*B*29 to AccumulatedConstant. 2256 /// This will allow getAddRecExpr to produce this: 2257 /// 2258 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2259 /// 2260 /// This form often exposes folding opportunities that are hidden in 2261 /// the original operand list. 2262 /// 2263 /// Return true iff it appears that any interesting folding opportunities 2264 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2265 /// the common case where no interesting opportunities are present, and 2266 /// is also used as a check to avoid infinite recursion. 2267 static bool 2268 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2269 SmallVectorImpl<const SCEV *> &NewOps, 2270 APInt &AccumulatedConstant, 2271 const SCEV *const *Ops, size_t NumOperands, 2272 const APInt &Scale, 2273 ScalarEvolution &SE) { 2274 bool Interesting = false; 2275 2276 // Iterate over the add operands. They are sorted, with constants first. 2277 unsigned i = 0; 2278 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2279 ++i; 2280 // Pull a buried constant out to the outside. 2281 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2282 Interesting = true; 2283 AccumulatedConstant += Scale * C->getAPInt(); 2284 } 2285 2286 // Next comes everything else. We're especially interested in multiplies 2287 // here, but they're in the middle, so just visit the rest with one loop. 2288 for (; i != NumOperands; ++i) { 2289 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2290 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2291 APInt NewScale = 2292 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2293 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2294 // A multiplication of a constant with another add; recurse. 2295 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2296 Interesting |= 2297 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2298 Add->op_begin(), Add->getNumOperands(), 2299 NewScale, SE); 2300 } else { 2301 // A multiplication of a constant with some other value. Update 2302 // the map. 2303 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2304 const SCEV *Key = SE.getMulExpr(MulOps); 2305 auto Pair = M.insert({Key, NewScale}); 2306 if (Pair.second) { 2307 NewOps.push_back(Pair.first->first); 2308 } else { 2309 Pair.first->second += NewScale; 2310 // The map already had an entry for this value, which may indicate 2311 // a folding opportunity. 2312 Interesting = true; 2313 } 2314 } 2315 } else { 2316 // An ordinary operand. Update the map. 2317 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2318 M.insert({Ops[i], Scale}); 2319 if (Pair.second) { 2320 NewOps.push_back(Pair.first->first); 2321 } else { 2322 Pair.first->second += Scale; 2323 // The map already had an entry for this value, which may indicate 2324 // a folding opportunity. 2325 Interesting = true; 2326 } 2327 } 2328 } 2329 2330 return Interesting; 2331 } 2332 2333 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2334 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2335 // can't-overflow flags for the operation if possible. 2336 static SCEV::NoWrapFlags 2337 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2338 const ArrayRef<const SCEV *> Ops, 2339 SCEV::NoWrapFlags Flags) { 2340 using namespace std::placeholders; 2341 2342 using OBO = OverflowingBinaryOperator; 2343 2344 bool CanAnalyze = 2345 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2346 (void)CanAnalyze; 2347 assert(CanAnalyze && "don't call from other places!"); 2348 2349 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2350 SCEV::NoWrapFlags SignOrUnsignWrap = 2351 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2352 2353 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2354 auto IsKnownNonNegative = [&](const SCEV *S) { 2355 return SE->isKnownNonNegative(S); 2356 }; 2357 2358 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2359 Flags = 2360 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2361 2362 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2363 2364 if (SignOrUnsignWrap != SignOrUnsignMask && 2365 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2366 isa<SCEVConstant>(Ops[0])) { 2367 2368 auto Opcode = [&] { 2369 switch (Type) { 2370 case scAddExpr: 2371 return Instruction::Add; 2372 case scMulExpr: 2373 return Instruction::Mul; 2374 default: 2375 llvm_unreachable("Unexpected SCEV op."); 2376 } 2377 }(); 2378 2379 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2380 2381 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2382 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2383 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2384 Opcode, C, OBO::NoSignedWrap); 2385 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2387 } 2388 2389 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2390 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2391 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2392 Opcode, C, OBO::NoUnsignedWrap); 2393 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2394 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2395 } 2396 } 2397 2398 return Flags; 2399 } 2400 2401 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2402 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2403 } 2404 2405 /// Get a canonical add expression, or something simpler if possible. 2406 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2407 SCEV::NoWrapFlags Flags, 2408 unsigned Depth) { 2409 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2410 "only nuw or nsw allowed"); 2411 assert(!Ops.empty() && "Cannot get empty add!"); 2412 if (Ops.size() == 1) return Ops[0]; 2413 #ifndef NDEBUG 2414 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2415 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2416 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2417 "SCEVAddExpr operand types don't match!"); 2418 #endif 2419 2420 // Sort by complexity, this groups all similar expression types together. 2421 GroupByComplexity(Ops, &LI, DT); 2422 2423 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2424 2425 // If there are any constants, fold them together. 2426 unsigned Idx = 0; 2427 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2428 ++Idx; 2429 assert(Idx < Ops.size()); 2430 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2431 // We found two constants, fold them together! 2432 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2433 if (Ops.size() == 2) return Ops[0]; 2434 Ops.erase(Ops.begin()+1); // Erase the folded element 2435 LHSC = cast<SCEVConstant>(Ops[0]); 2436 } 2437 2438 // If we are left with a constant zero being added, strip it off. 2439 if (LHSC->getValue()->isZero()) { 2440 Ops.erase(Ops.begin()); 2441 --Idx; 2442 } 2443 2444 if (Ops.size() == 1) return Ops[0]; 2445 } 2446 2447 // Limit recursion calls depth. 2448 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2449 return getOrCreateAddExpr(Ops, Flags); 2450 2451 // Okay, check to see if the same value occurs in the operand list more than 2452 // once. If so, merge them together into an multiply expression. Since we 2453 // sorted the list, these values are required to be adjacent. 2454 Type *Ty = Ops[0]->getType(); 2455 bool FoundMatch = false; 2456 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2457 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2458 // Scan ahead to count how many equal operands there are. 2459 unsigned Count = 2; 2460 while (i+Count != e && Ops[i+Count] == Ops[i]) 2461 ++Count; 2462 // Merge the values into a multiply. 2463 const SCEV *Scale = getConstant(Ty, Count); 2464 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2465 if (Ops.size() == Count) 2466 return Mul; 2467 Ops[i] = Mul; 2468 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2469 --i; e -= Count - 1; 2470 FoundMatch = true; 2471 } 2472 if (FoundMatch) 2473 return getAddExpr(Ops, Flags, Depth + 1); 2474 2475 // Check for truncates. If all the operands are truncated from the same 2476 // type, see if factoring out the truncate would permit the result to be 2477 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2478 // if the contents of the resulting outer trunc fold to something simple. 2479 auto FindTruncSrcType = [&]() -> Type * { 2480 // We're ultimately looking to fold an addrec of truncs and muls of only 2481 // constants and truncs, so if we find any other types of SCEV 2482 // as operands of the addrec then we bail and return nullptr here. 2483 // Otherwise, we return the type of the operand of a trunc that we find. 2484 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2485 return T->getOperand()->getType(); 2486 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2487 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2488 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2489 return T->getOperand()->getType(); 2490 } 2491 return nullptr; 2492 }; 2493 if (auto *SrcType = FindTruncSrcType()) { 2494 SmallVector<const SCEV *, 8> LargeOps; 2495 bool Ok = true; 2496 // Check all the operands to see if they can be represented in the 2497 // source type of the truncate. 2498 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2500 if (T->getOperand()->getType() != SrcType) { 2501 Ok = false; 2502 break; 2503 } 2504 LargeOps.push_back(T->getOperand()); 2505 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2506 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2507 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2508 SmallVector<const SCEV *, 8> LargeMulOps; 2509 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2510 if (const SCEVTruncateExpr *T = 2511 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2512 if (T->getOperand()->getType() != SrcType) { 2513 Ok = false; 2514 break; 2515 } 2516 LargeMulOps.push_back(T->getOperand()); 2517 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2518 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2519 } else { 2520 Ok = false; 2521 break; 2522 } 2523 } 2524 if (Ok) 2525 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2526 } else { 2527 Ok = false; 2528 break; 2529 } 2530 } 2531 if (Ok) { 2532 // Evaluate the expression in the larger type. 2533 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2534 // If it folds to something simple, use it. Otherwise, don't. 2535 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2536 return getTruncateExpr(Fold, Ty); 2537 } 2538 } 2539 2540 // Skip past any other cast SCEVs. 2541 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2542 ++Idx; 2543 2544 // If there are add operands they would be next. 2545 if (Idx < Ops.size()) { 2546 bool DeletedAdd = false; 2547 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2548 if (Ops.size() > AddOpsInlineThreshold || 2549 Add->getNumOperands() > AddOpsInlineThreshold) 2550 break; 2551 // If we have an add, expand the add operands onto the end of the operands 2552 // list. 2553 Ops.erase(Ops.begin()+Idx); 2554 Ops.append(Add->op_begin(), Add->op_end()); 2555 DeletedAdd = true; 2556 } 2557 2558 // If we deleted at least one add, we added operands to the end of the list, 2559 // and they are not necessarily sorted. Recurse to resort and resimplify 2560 // any operands we just acquired. 2561 if (DeletedAdd) 2562 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2563 } 2564 2565 // Skip over the add expression until we get to a multiply. 2566 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2567 ++Idx; 2568 2569 // Check to see if there are any folding opportunities present with 2570 // operands multiplied by constant values. 2571 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2572 uint64_t BitWidth = getTypeSizeInBits(Ty); 2573 DenseMap<const SCEV *, APInt> M; 2574 SmallVector<const SCEV *, 8> NewOps; 2575 APInt AccumulatedConstant(BitWidth, 0); 2576 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2577 Ops.data(), Ops.size(), 2578 APInt(BitWidth, 1), *this)) { 2579 struct APIntCompare { 2580 bool operator()(const APInt &LHS, const APInt &RHS) const { 2581 return LHS.ult(RHS); 2582 } 2583 }; 2584 2585 // Some interesting folding opportunity is present, so its worthwhile to 2586 // re-generate the operands list. Group the operands by constant scale, 2587 // to avoid multiplying by the same constant scale multiple times. 2588 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2589 for (const SCEV *NewOp : NewOps) 2590 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2591 // Re-generate the operands list. 2592 Ops.clear(); 2593 if (AccumulatedConstant != 0) 2594 Ops.push_back(getConstant(AccumulatedConstant)); 2595 for (auto &MulOp : MulOpLists) 2596 if (MulOp.first != 0) 2597 Ops.push_back(getMulExpr( 2598 getConstant(MulOp.first), 2599 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2600 SCEV::FlagAnyWrap, Depth + 1)); 2601 if (Ops.empty()) 2602 return getZero(Ty); 2603 if (Ops.size() == 1) 2604 return Ops[0]; 2605 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2606 } 2607 } 2608 2609 // If we are adding something to a multiply expression, make sure the 2610 // something is not already an operand of the multiply. If so, merge it into 2611 // the multiply. 2612 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2613 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2614 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2615 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2616 if (isa<SCEVConstant>(MulOpSCEV)) 2617 continue; 2618 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2619 if (MulOpSCEV == Ops[AddOp]) { 2620 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2621 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2622 if (Mul->getNumOperands() != 2) { 2623 // If the multiply has more than two operands, we must get the 2624 // Y*Z term. 2625 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2626 Mul->op_begin()+MulOp); 2627 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2628 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2629 } 2630 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2631 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2632 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2633 SCEV::FlagAnyWrap, Depth + 1); 2634 if (Ops.size() == 2) return OuterMul; 2635 if (AddOp < Idx) { 2636 Ops.erase(Ops.begin()+AddOp); 2637 Ops.erase(Ops.begin()+Idx-1); 2638 } else { 2639 Ops.erase(Ops.begin()+Idx); 2640 Ops.erase(Ops.begin()+AddOp-1); 2641 } 2642 Ops.push_back(OuterMul); 2643 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2644 } 2645 2646 // Check this multiply against other multiplies being added together. 2647 for (unsigned OtherMulIdx = Idx+1; 2648 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2649 ++OtherMulIdx) { 2650 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2651 // If MulOp occurs in OtherMul, we can fold the two multiplies 2652 // together. 2653 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2654 OMulOp != e; ++OMulOp) 2655 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2656 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2657 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2658 if (Mul->getNumOperands() != 2) { 2659 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2660 Mul->op_begin()+MulOp); 2661 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2662 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2663 } 2664 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2665 if (OtherMul->getNumOperands() != 2) { 2666 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2667 OtherMul->op_begin()+OMulOp); 2668 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2669 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2672 const SCEV *InnerMulSum = 2673 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2674 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2675 SCEV::FlagAnyWrap, Depth + 1); 2676 if (Ops.size() == 2) return OuterMul; 2677 Ops.erase(Ops.begin()+Idx); 2678 Ops.erase(Ops.begin()+OtherMulIdx-1); 2679 Ops.push_back(OuterMul); 2680 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2681 } 2682 } 2683 } 2684 } 2685 2686 // If there are any add recurrences in the operands list, see if any other 2687 // added values are loop invariant. If so, we can fold them into the 2688 // recurrence. 2689 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2690 ++Idx; 2691 2692 // Scan over all recurrences, trying to fold loop invariants into them. 2693 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2694 // Scan all of the other operands to this add and add them to the vector if 2695 // they are loop invariant w.r.t. the recurrence. 2696 SmallVector<const SCEV *, 8> LIOps; 2697 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2698 const Loop *AddRecLoop = AddRec->getLoop(); 2699 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2700 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2701 LIOps.push_back(Ops[i]); 2702 Ops.erase(Ops.begin()+i); 2703 --i; --e; 2704 } 2705 2706 // If we found some loop invariants, fold them into the recurrence. 2707 if (!LIOps.empty()) { 2708 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2709 LIOps.push_back(AddRec->getStart()); 2710 2711 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2712 AddRec->op_end()); 2713 // This follows from the fact that the no-wrap flags on the outer add 2714 // expression are applicable on the 0th iteration, when the add recurrence 2715 // will be equal to its start value. 2716 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2717 2718 // Build the new addrec. Propagate the NUW and NSW flags if both the 2719 // outer add and the inner addrec are guaranteed to have no overflow. 2720 // Always propagate NW. 2721 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2722 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2723 2724 // If all of the other operands were loop invariant, we are done. 2725 if (Ops.size() == 1) return NewRec; 2726 2727 // Otherwise, add the folded AddRec by the non-invariant parts. 2728 for (unsigned i = 0;; ++i) 2729 if (Ops[i] == AddRec) { 2730 Ops[i] = NewRec; 2731 break; 2732 } 2733 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2734 } 2735 2736 // Okay, if there weren't any loop invariants to be folded, check to see if 2737 // there are multiple AddRec's with the same loop induction variable being 2738 // added together. If so, we can fold them. 2739 for (unsigned OtherIdx = Idx+1; 2740 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2741 ++OtherIdx) { 2742 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2743 // so that the 1st found AddRecExpr is dominated by all others. 2744 assert(DT.dominates( 2745 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2746 AddRec->getLoop()->getHeader()) && 2747 "AddRecExprs are not sorted in reverse dominance order?"); 2748 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2749 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2750 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2751 AddRec->op_end()); 2752 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2753 ++OtherIdx) { 2754 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2755 if (OtherAddRec->getLoop() == AddRecLoop) { 2756 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2757 i != e; ++i) { 2758 if (i >= AddRecOps.size()) { 2759 AddRecOps.append(OtherAddRec->op_begin()+i, 2760 OtherAddRec->op_end()); 2761 break; 2762 } 2763 SmallVector<const SCEV *, 2> TwoOps = { 2764 AddRecOps[i], OtherAddRec->getOperand(i)}; 2765 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2766 } 2767 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2768 } 2769 } 2770 // Step size has changed, so we cannot guarantee no self-wraparound. 2771 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2772 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2773 } 2774 } 2775 2776 // Otherwise couldn't fold anything into this recurrence. Move onto the 2777 // next one. 2778 } 2779 2780 // Okay, it looks like we really DO need an add expr. Check to see if we 2781 // already have one, otherwise create a new one. 2782 return getOrCreateAddExpr(Ops, Flags); 2783 } 2784 2785 const SCEV * 2786 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2787 SCEV::NoWrapFlags Flags) { 2788 FoldingSetNodeID ID; 2789 ID.AddInteger(scAddExpr); 2790 for (const SCEV *Op : Ops) 2791 ID.AddPointer(Op); 2792 void *IP = nullptr; 2793 SCEVAddExpr *S = 2794 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2795 if (!S) { 2796 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2797 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2798 S = new (SCEVAllocator) 2799 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2800 UniqueSCEVs.InsertNode(S, IP); 2801 addToLoopUseLists(S); 2802 } 2803 S->setNoWrapFlags(Flags); 2804 return S; 2805 } 2806 2807 const SCEV * 2808 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2809 const Loop *L, SCEV::NoWrapFlags Flags) { 2810 FoldingSetNodeID ID; 2811 ID.AddInteger(scAddRecExpr); 2812 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2813 ID.AddPointer(Ops[i]); 2814 ID.AddPointer(L); 2815 void *IP = nullptr; 2816 SCEVAddRecExpr *S = 2817 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2818 if (!S) { 2819 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2820 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2821 S = new (SCEVAllocator) 2822 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2823 UniqueSCEVs.InsertNode(S, IP); 2824 addToLoopUseLists(S); 2825 } 2826 S->setNoWrapFlags(Flags); 2827 return S; 2828 } 2829 2830 const SCEV * 2831 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2832 SCEV::NoWrapFlags Flags) { 2833 FoldingSetNodeID ID; 2834 ID.AddInteger(scMulExpr); 2835 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2836 ID.AddPointer(Ops[i]); 2837 void *IP = nullptr; 2838 SCEVMulExpr *S = 2839 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2840 if (!S) { 2841 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2842 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2843 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2844 O, Ops.size()); 2845 UniqueSCEVs.InsertNode(S, IP); 2846 addToLoopUseLists(S); 2847 } 2848 S->setNoWrapFlags(Flags); 2849 return S; 2850 } 2851 2852 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2853 uint64_t k = i*j; 2854 if (j > 1 && k / j != i) Overflow = true; 2855 return k; 2856 } 2857 2858 /// Compute the result of "n choose k", the binomial coefficient. If an 2859 /// intermediate computation overflows, Overflow will be set and the return will 2860 /// be garbage. Overflow is not cleared on absence of overflow. 2861 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2862 // We use the multiplicative formula: 2863 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2864 // At each iteration, we take the n-th term of the numeral and divide by the 2865 // (k-n)th term of the denominator. This division will always produce an 2866 // integral result, and helps reduce the chance of overflow in the 2867 // intermediate computations. However, we can still overflow even when the 2868 // final result would fit. 2869 2870 if (n == 0 || n == k) return 1; 2871 if (k > n) return 0; 2872 2873 if (k > n/2) 2874 k = n-k; 2875 2876 uint64_t r = 1; 2877 for (uint64_t i = 1; i <= k; ++i) { 2878 r = umul_ov(r, n-(i-1), Overflow); 2879 r /= i; 2880 } 2881 return r; 2882 } 2883 2884 /// Determine if any of the operands in this SCEV are a constant or if 2885 /// any of the add or multiply expressions in this SCEV contain a constant. 2886 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2887 struct FindConstantInAddMulChain { 2888 bool FoundConstant = false; 2889 2890 bool follow(const SCEV *S) { 2891 FoundConstant |= isa<SCEVConstant>(S); 2892 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2893 } 2894 2895 bool isDone() const { 2896 return FoundConstant; 2897 } 2898 }; 2899 2900 FindConstantInAddMulChain F; 2901 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2902 ST.visitAll(StartExpr); 2903 return F.FoundConstant; 2904 } 2905 2906 /// Get a canonical multiply expression, or something simpler if possible. 2907 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2908 SCEV::NoWrapFlags Flags, 2909 unsigned Depth) { 2910 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2911 "only nuw or nsw allowed"); 2912 assert(!Ops.empty() && "Cannot get empty mul!"); 2913 if (Ops.size() == 1) return Ops[0]; 2914 #ifndef NDEBUG 2915 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2916 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2917 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2918 "SCEVMulExpr operand types don't match!"); 2919 #endif 2920 2921 // Sort by complexity, this groups all similar expression types together. 2922 GroupByComplexity(Ops, &LI, DT); 2923 2924 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2925 2926 // Limit recursion calls depth. 2927 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2928 return getOrCreateMulExpr(Ops, Flags); 2929 2930 // If there are any constants, fold them together. 2931 unsigned Idx = 0; 2932 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2933 2934 if (Ops.size() == 2) 2935 // C1*(C2+V) -> C1*C2 + C1*V 2936 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2937 // If any of Add's ops are Adds or Muls with a constant, apply this 2938 // transformation as well. 2939 // 2940 // TODO: There are some cases where this transformation is not 2941 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2942 // this transformation should be narrowed down. 2943 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2944 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2945 SCEV::FlagAnyWrap, Depth + 1), 2946 getMulExpr(LHSC, Add->getOperand(1), 2947 SCEV::FlagAnyWrap, Depth + 1), 2948 SCEV::FlagAnyWrap, Depth + 1); 2949 2950 ++Idx; 2951 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2952 // We found two constants, fold them together! 2953 ConstantInt *Fold = 2954 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2955 Ops[0] = getConstant(Fold); 2956 Ops.erase(Ops.begin()+1); // Erase the folded element 2957 if (Ops.size() == 1) return Ops[0]; 2958 LHSC = cast<SCEVConstant>(Ops[0]); 2959 } 2960 2961 // If we are left with a constant one being multiplied, strip it off. 2962 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2963 Ops.erase(Ops.begin()); 2964 --Idx; 2965 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2966 // If we have a multiply of zero, it will always be zero. 2967 return Ops[0]; 2968 } else if (Ops[0]->isAllOnesValue()) { 2969 // If we have a mul by -1 of an add, try distributing the -1 among the 2970 // add operands. 2971 if (Ops.size() == 2) { 2972 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2973 SmallVector<const SCEV *, 4> NewOps; 2974 bool AnyFolded = false; 2975 for (const SCEV *AddOp : Add->operands()) { 2976 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2977 Depth + 1); 2978 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2979 NewOps.push_back(Mul); 2980 } 2981 if (AnyFolded) 2982 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2983 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2984 // Negation preserves a recurrence's no self-wrap property. 2985 SmallVector<const SCEV *, 4> Operands; 2986 for (const SCEV *AddRecOp : AddRec->operands()) 2987 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2988 Depth + 1)); 2989 2990 return getAddRecExpr(Operands, AddRec->getLoop(), 2991 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2992 } 2993 } 2994 } 2995 2996 if (Ops.size() == 1) 2997 return Ops[0]; 2998 } 2999 3000 // Skip over the add expression until we get to a multiply. 3001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3002 ++Idx; 3003 3004 // If there are mul operands inline them all into this expression. 3005 if (Idx < Ops.size()) { 3006 bool DeletedMul = false; 3007 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3008 if (Ops.size() > MulOpsInlineThreshold) 3009 break; 3010 // If we have an mul, expand the mul operands onto the end of the 3011 // operands list. 3012 Ops.erase(Ops.begin()+Idx); 3013 Ops.append(Mul->op_begin(), Mul->op_end()); 3014 DeletedMul = true; 3015 } 3016 3017 // If we deleted at least one mul, we added operands to the end of the 3018 // list, and they are not necessarily sorted. Recurse to resort and 3019 // resimplify any operands we just acquired. 3020 if (DeletedMul) 3021 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3022 } 3023 3024 // If there are any add recurrences in the operands list, see if any other 3025 // added values are loop invariant. If so, we can fold them into the 3026 // recurrence. 3027 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3028 ++Idx; 3029 3030 // Scan over all recurrences, trying to fold loop invariants into them. 3031 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3032 // Scan all of the other operands to this mul and add them to the vector 3033 // if they are loop invariant w.r.t. the recurrence. 3034 SmallVector<const SCEV *, 8> LIOps; 3035 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3036 const Loop *AddRecLoop = AddRec->getLoop(); 3037 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3038 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3039 LIOps.push_back(Ops[i]); 3040 Ops.erase(Ops.begin()+i); 3041 --i; --e; 3042 } 3043 3044 // If we found some loop invariants, fold them into the recurrence. 3045 if (!LIOps.empty()) { 3046 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3047 SmallVector<const SCEV *, 4> NewOps; 3048 NewOps.reserve(AddRec->getNumOperands()); 3049 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3050 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3051 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3052 SCEV::FlagAnyWrap, Depth + 1)); 3053 3054 // Build the new addrec. Propagate the NUW and NSW flags if both the 3055 // outer mul and the inner addrec are guaranteed to have no overflow. 3056 // 3057 // No self-wrap cannot be guaranteed after changing the step size, but 3058 // will be inferred if either NUW or NSW is true. 3059 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3060 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3061 3062 // If all of the other operands were loop invariant, we are done. 3063 if (Ops.size() == 1) return NewRec; 3064 3065 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3066 for (unsigned i = 0;; ++i) 3067 if (Ops[i] == AddRec) { 3068 Ops[i] = NewRec; 3069 break; 3070 } 3071 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3072 } 3073 3074 // Okay, if there weren't any loop invariants to be folded, check to see 3075 // if there are multiple AddRec's with the same loop induction variable 3076 // being multiplied together. If so, we can fold them. 3077 3078 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3079 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3080 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3081 // ]]],+,...up to x=2n}. 3082 // Note that the arguments to choose() are always integers with values 3083 // known at compile time, never SCEV objects. 3084 // 3085 // The implementation avoids pointless extra computations when the two 3086 // addrec's are of different length (mathematically, it's equivalent to 3087 // an infinite stream of zeros on the right). 3088 bool OpsModified = false; 3089 for (unsigned OtherIdx = Idx+1; 3090 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3091 ++OtherIdx) { 3092 const SCEVAddRecExpr *OtherAddRec = 3093 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3094 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3095 continue; 3096 3097 // Limit max number of arguments to avoid creation of unreasonably big 3098 // SCEVAddRecs with very complex operands. 3099 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3100 MaxAddRecSize || isHugeExpression(AddRec) || 3101 isHugeExpression(OtherAddRec)) 3102 continue; 3103 3104 bool Overflow = false; 3105 Type *Ty = AddRec->getType(); 3106 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3107 SmallVector<const SCEV*, 7> AddRecOps; 3108 for (int x = 0, xe = AddRec->getNumOperands() + 3109 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3110 SmallVector <const SCEV *, 7> SumOps; 3111 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3112 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3113 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3114 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3115 z < ze && !Overflow; ++z) { 3116 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3117 uint64_t Coeff; 3118 if (LargerThan64Bits) 3119 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3120 else 3121 Coeff = Coeff1*Coeff2; 3122 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3123 const SCEV *Term1 = AddRec->getOperand(y-z); 3124 const SCEV *Term2 = OtherAddRec->getOperand(z); 3125 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3126 SCEV::FlagAnyWrap, Depth + 1)); 3127 } 3128 } 3129 if (SumOps.empty()) 3130 SumOps.push_back(getZero(Ty)); 3131 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3132 } 3133 if (!Overflow) { 3134 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3135 SCEV::FlagAnyWrap); 3136 if (Ops.size() == 2) return NewAddRec; 3137 Ops[Idx] = NewAddRec; 3138 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3139 OpsModified = true; 3140 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3141 if (!AddRec) 3142 break; 3143 } 3144 } 3145 if (OpsModified) 3146 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3147 3148 // Otherwise couldn't fold anything into this recurrence. Move onto the 3149 // next one. 3150 } 3151 3152 // Okay, it looks like we really DO need an mul expr. Check to see if we 3153 // already have one, otherwise create a new one. 3154 return getOrCreateMulExpr(Ops, Flags); 3155 } 3156 3157 /// Represents an unsigned remainder expression based on unsigned division. 3158 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3159 const SCEV *RHS) { 3160 assert(getEffectiveSCEVType(LHS->getType()) == 3161 getEffectiveSCEVType(RHS->getType()) && 3162 "SCEVURemExpr operand types don't match!"); 3163 3164 // Short-circuit easy cases 3165 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3166 // If constant is one, the result is trivial 3167 if (RHSC->getValue()->isOne()) 3168 return getZero(LHS->getType()); // X urem 1 --> 0 3169 3170 // If constant is a power of two, fold into a zext(trunc(LHS)). 3171 if (RHSC->getAPInt().isPowerOf2()) { 3172 Type *FullTy = LHS->getType(); 3173 Type *TruncTy = 3174 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3175 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3176 } 3177 } 3178 3179 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3180 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3181 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3182 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3183 } 3184 3185 /// Get a canonical unsigned division expression, or something simpler if 3186 /// possible. 3187 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3188 const SCEV *RHS) { 3189 assert(getEffectiveSCEVType(LHS->getType()) == 3190 getEffectiveSCEVType(RHS->getType()) && 3191 "SCEVUDivExpr operand types don't match!"); 3192 3193 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3194 if (RHSC->getValue()->isOne()) 3195 return LHS; // X udiv 1 --> x 3196 // If the denominator is zero, the result of the udiv is undefined. Don't 3197 // try to analyze it, because the resolution chosen here may differ from 3198 // the resolution chosen in other parts of the compiler. 3199 if (!RHSC->getValue()->isZero()) { 3200 // Determine if the division can be folded into the operands of 3201 // its operands. 3202 // TODO: Generalize this to non-constants by using known-bits information. 3203 Type *Ty = LHS->getType(); 3204 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3205 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3206 // For non-power-of-two values, effectively round the value up to the 3207 // nearest power of two. 3208 if (!RHSC->getAPInt().isPowerOf2()) 3209 ++MaxShiftAmt; 3210 IntegerType *ExtTy = 3211 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3213 if (const SCEVConstant *Step = 3214 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3215 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3216 const APInt &StepInt = Step->getAPInt(); 3217 const APInt &DivInt = RHSC->getAPInt(); 3218 if (!StepInt.urem(DivInt) && 3219 getZeroExtendExpr(AR, ExtTy) == 3220 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3221 getZeroExtendExpr(Step, ExtTy), 3222 AR->getLoop(), SCEV::FlagAnyWrap)) { 3223 SmallVector<const SCEV *, 4> Operands; 3224 for (const SCEV *Op : AR->operands()) 3225 Operands.push_back(getUDivExpr(Op, RHS)); 3226 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3227 } 3228 /// Get a canonical UDivExpr for a recurrence. 3229 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3230 // We can currently only fold X%N if X is constant. 3231 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3232 if (StartC && !DivInt.urem(StepInt) && 3233 getZeroExtendExpr(AR, ExtTy) == 3234 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3235 getZeroExtendExpr(Step, ExtTy), 3236 AR->getLoop(), SCEV::FlagAnyWrap)) { 3237 const APInt &StartInt = StartC->getAPInt(); 3238 const APInt &StartRem = StartInt.urem(StepInt); 3239 if (StartRem != 0) 3240 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3241 AR->getLoop(), SCEV::FlagNW); 3242 } 3243 } 3244 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3245 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3246 SmallVector<const SCEV *, 4> Operands; 3247 for (const SCEV *Op : M->operands()) 3248 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3249 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3250 // Find an operand that's safely divisible. 3251 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3252 const SCEV *Op = M->getOperand(i); 3253 const SCEV *Div = getUDivExpr(Op, RHSC); 3254 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3255 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3256 M->op_end()); 3257 Operands[i] = Div; 3258 return getMulExpr(Operands); 3259 } 3260 } 3261 } 3262 3263 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3264 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3265 if (auto *DivisorConstant = 3266 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3267 bool Overflow = false; 3268 APInt NewRHS = 3269 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3270 if (Overflow) { 3271 return getConstant(RHSC->getType(), 0, false); 3272 } 3273 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3274 } 3275 } 3276 3277 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3278 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3279 SmallVector<const SCEV *, 4> Operands; 3280 for (const SCEV *Op : A->operands()) 3281 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3282 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3283 Operands.clear(); 3284 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3285 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3286 if (isa<SCEVUDivExpr>(Op) || 3287 getMulExpr(Op, RHS) != A->getOperand(i)) 3288 break; 3289 Operands.push_back(Op); 3290 } 3291 if (Operands.size() == A->getNumOperands()) 3292 return getAddExpr(Operands); 3293 } 3294 } 3295 3296 // Fold if both operands are constant. 3297 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3298 Constant *LHSCV = LHSC->getValue(); 3299 Constant *RHSCV = RHSC->getValue(); 3300 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3301 RHSCV))); 3302 } 3303 } 3304 } 3305 3306 FoldingSetNodeID ID; 3307 ID.AddInteger(scUDivExpr); 3308 ID.AddPointer(LHS); 3309 ID.AddPointer(RHS); 3310 void *IP = nullptr; 3311 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3312 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3313 LHS, RHS); 3314 UniqueSCEVs.InsertNode(S, IP); 3315 addToLoopUseLists(S); 3316 return S; 3317 } 3318 3319 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3320 APInt A = C1->getAPInt().abs(); 3321 APInt B = C2->getAPInt().abs(); 3322 uint32_t ABW = A.getBitWidth(); 3323 uint32_t BBW = B.getBitWidth(); 3324 3325 if (ABW > BBW) 3326 B = B.zext(ABW); 3327 else if (ABW < BBW) 3328 A = A.zext(BBW); 3329 3330 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3331 } 3332 3333 /// Get a canonical unsigned division expression, or something simpler if 3334 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3335 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3336 /// it's not exact because the udiv may be clearing bits. 3337 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3338 const SCEV *RHS) { 3339 // TODO: we could try to find factors in all sorts of things, but for now we 3340 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3341 // end of this file for inspiration. 3342 3343 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3344 if (!Mul || !Mul->hasNoUnsignedWrap()) 3345 return getUDivExpr(LHS, RHS); 3346 3347 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3348 // If the mulexpr multiplies by a constant, then that constant must be the 3349 // first element of the mulexpr. 3350 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3351 if (LHSCst == RHSCst) { 3352 SmallVector<const SCEV *, 2> Operands; 3353 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3354 return getMulExpr(Operands); 3355 } 3356 3357 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3358 // that there's a factor provided by one of the other terms. We need to 3359 // check. 3360 APInt Factor = gcd(LHSCst, RHSCst); 3361 if (!Factor.isIntN(1)) { 3362 LHSCst = 3363 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3364 RHSCst = 3365 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3366 SmallVector<const SCEV *, 2> Operands; 3367 Operands.push_back(LHSCst); 3368 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3369 LHS = getMulExpr(Operands); 3370 RHS = RHSCst; 3371 Mul = dyn_cast<SCEVMulExpr>(LHS); 3372 if (!Mul) 3373 return getUDivExactExpr(LHS, RHS); 3374 } 3375 } 3376 } 3377 3378 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3379 if (Mul->getOperand(i) == RHS) { 3380 SmallVector<const SCEV *, 2> Operands; 3381 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3382 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3383 return getMulExpr(Operands); 3384 } 3385 } 3386 3387 return getUDivExpr(LHS, RHS); 3388 } 3389 3390 /// Get an add recurrence expression for the specified loop. Simplify the 3391 /// expression as much as possible. 3392 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3393 const Loop *L, 3394 SCEV::NoWrapFlags Flags) { 3395 SmallVector<const SCEV *, 4> Operands; 3396 Operands.push_back(Start); 3397 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3398 if (StepChrec->getLoop() == L) { 3399 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3400 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3401 } 3402 3403 Operands.push_back(Step); 3404 return getAddRecExpr(Operands, L, Flags); 3405 } 3406 3407 /// Get an add recurrence expression for the specified loop. Simplify the 3408 /// expression as much as possible. 3409 const SCEV * 3410 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3411 const Loop *L, SCEV::NoWrapFlags Flags) { 3412 if (Operands.size() == 1) return Operands[0]; 3413 #ifndef NDEBUG 3414 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3415 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3416 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3417 "SCEVAddRecExpr operand types don't match!"); 3418 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3419 assert(isLoopInvariant(Operands[i], L) && 3420 "SCEVAddRecExpr operand is not loop-invariant!"); 3421 #endif 3422 3423 if (Operands.back()->isZero()) { 3424 Operands.pop_back(); 3425 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3426 } 3427 3428 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3429 // use that information to infer NUW and NSW flags. However, computing a 3430 // BE count requires calling getAddRecExpr, so we may not yet have a 3431 // meaningful BE count at this point (and if we don't, we'd be stuck 3432 // with a SCEVCouldNotCompute as the cached BE count). 3433 3434 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3435 3436 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3437 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3438 const Loop *NestedLoop = NestedAR->getLoop(); 3439 if (L->contains(NestedLoop) 3440 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3441 : (!NestedLoop->contains(L) && 3442 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3443 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3444 NestedAR->op_end()); 3445 Operands[0] = NestedAR->getStart(); 3446 // AddRecs require their operands be loop-invariant with respect to their 3447 // loops. Don't perform this transformation if it would break this 3448 // requirement. 3449 bool AllInvariant = all_of( 3450 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3451 3452 if (AllInvariant) { 3453 // Create a recurrence for the outer loop with the same step size. 3454 // 3455 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3456 // inner recurrence has the same property. 3457 SCEV::NoWrapFlags OuterFlags = 3458 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3459 3460 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3461 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3462 return isLoopInvariant(Op, NestedLoop); 3463 }); 3464 3465 if (AllInvariant) { 3466 // Ok, both add recurrences are valid after the transformation. 3467 // 3468 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3469 // the outer recurrence has the same property. 3470 SCEV::NoWrapFlags InnerFlags = 3471 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3472 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3473 } 3474 } 3475 // Reset Operands to its original state. 3476 Operands[0] = NestedAR; 3477 } 3478 } 3479 3480 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3481 // already have one, otherwise create a new one. 3482 return getOrCreateAddRecExpr(Operands, L, Flags); 3483 } 3484 3485 const SCEV * 3486 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3487 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3488 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3489 // getSCEV(Base)->getType() has the same address space as Base->getType() 3490 // because SCEV::getType() preserves the address space. 3491 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3492 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3493 // instruction to its SCEV, because the Instruction may be guarded by control 3494 // flow and the no-overflow bits may not be valid for the expression in any 3495 // context. This can be fixed similarly to how these flags are handled for 3496 // adds. 3497 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3498 : SCEV::FlagAnyWrap; 3499 3500 const SCEV *TotalOffset = getZero(IntPtrTy); 3501 // The array size is unimportant. The first thing we do on CurTy is getting 3502 // its element type. 3503 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3504 for (const SCEV *IndexExpr : IndexExprs) { 3505 // Compute the (potentially symbolic) offset in bytes for this index. 3506 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3507 // For a struct, add the member offset. 3508 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3509 unsigned FieldNo = Index->getZExtValue(); 3510 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3511 3512 // Add the field offset to the running total offset. 3513 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3514 3515 // Update CurTy to the type of the field at Index. 3516 CurTy = STy->getTypeAtIndex(Index); 3517 } else { 3518 // Update CurTy to its element type. 3519 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3520 // For an array, add the element offset, explicitly scaled. 3521 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3522 // Getelementptr indices are signed. 3523 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3524 3525 // Multiply the index by the element size to compute the element offset. 3526 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3527 3528 // Add the element offset to the running total offset. 3529 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3530 } 3531 } 3532 3533 // Add the total offset from all the GEP indices to the base. 3534 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3535 } 3536 3537 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3538 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3539 ArrayRef<const SCEV *> Ops) { 3540 FoldingSetNodeID ID; 3541 void *IP = nullptr; 3542 ID.AddInteger(SCEVType); 3543 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3544 ID.AddPointer(Ops[i]); 3545 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3546 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3547 } 3548 3549 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3550 SmallVectorImpl<const SCEV *> &Ops) { 3551 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3552 if (Ops.size() == 1) return Ops[0]; 3553 #ifndef NDEBUG 3554 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3555 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3556 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3557 "Operand types don't match!"); 3558 #endif 3559 3560 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3561 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3562 3563 // Sort by complexity, this groups all similar expression types together. 3564 GroupByComplexity(Ops, &LI, DT); 3565 3566 // Check if we have created the same expression before. 3567 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3568 return S; 3569 } 3570 3571 // If there are any constants, fold them together. 3572 unsigned Idx = 0; 3573 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3574 ++Idx; 3575 assert(Idx < Ops.size()); 3576 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3577 if (Kind == scSMaxExpr) 3578 return APIntOps::smax(LHS, RHS); 3579 else if (Kind == scSMinExpr) 3580 return APIntOps::smin(LHS, RHS); 3581 else if (Kind == scUMaxExpr) 3582 return APIntOps::umax(LHS, RHS); 3583 else if (Kind == scUMinExpr) 3584 return APIntOps::umin(LHS, RHS); 3585 llvm_unreachable("Unknown SCEV min/max opcode"); 3586 }; 3587 3588 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3589 // We found two constants, fold them together! 3590 ConstantInt *Fold = ConstantInt::get( 3591 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3592 Ops[0] = getConstant(Fold); 3593 Ops.erase(Ops.begin()+1); // Erase the folded element 3594 if (Ops.size() == 1) return Ops[0]; 3595 LHSC = cast<SCEVConstant>(Ops[0]); 3596 } 3597 3598 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3599 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3600 3601 if (IsMax ? IsMinV : IsMaxV) { 3602 // If we are left with a constant minimum(/maximum)-int, strip it off. 3603 Ops.erase(Ops.begin()); 3604 --Idx; 3605 } else if (IsMax ? IsMaxV : IsMinV) { 3606 // If we have a max(/min) with a constant maximum(/minimum)-int, 3607 // it will always be the extremum. 3608 return LHSC; 3609 } 3610 3611 if (Ops.size() == 1) return Ops[0]; 3612 } 3613 3614 // Find the first operation of the same kind 3615 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3616 ++Idx; 3617 3618 // Check to see if one of the operands is of the same kind. If so, expand its 3619 // operands onto our operand list, and recurse to simplify. 3620 if (Idx < Ops.size()) { 3621 bool DeletedAny = false; 3622 while (Ops[Idx]->getSCEVType() == Kind) { 3623 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3624 Ops.erase(Ops.begin()+Idx); 3625 Ops.append(SMME->op_begin(), SMME->op_end()); 3626 DeletedAny = true; 3627 } 3628 3629 if (DeletedAny) 3630 return getMinMaxExpr(Kind, Ops); 3631 } 3632 3633 // Okay, check to see if the same value occurs in the operand list twice. If 3634 // so, delete one. Since we sorted the list, these values are required to 3635 // be adjacent. 3636 llvm::CmpInst::Predicate GEPred = 3637 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3638 llvm::CmpInst::Predicate LEPred = 3639 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3640 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3641 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3642 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3643 if (Ops[i] == Ops[i + 1] || 3644 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3645 // X op Y op Y --> X op Y 3646 // X op Y --> X, if we know X, Y are ordered appropriately 3647 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3648 --i; 3649 --e; 3650 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3651 Ops[i + 1])) { 3652 // X op Y --> Y, if we know X, Y are ordered appropriately 3653 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3654 --i; 3655 --e; 3656 } 3657 } 3658 3659 if (Ops.size() == 1) return Ops[0]; 3660 3661 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3662 3663 // Okay, it looks like we really DO need an expr. Check to see if we 3664 // already have one, otherwise create a new one. 3665 const SCEV *ExistingSCEV; 3666 FoldingSetNodeID ID; 3667 void *IP; 3668 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3669 if (ExistingSCEV) 3670 return ExistingSCEV; 3671 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3672 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3673 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3674 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3675 3676 UniqueSCEVs.InsertNode(S, IP); 3677 addToLoopUseLists(S); 3678 return S; 3679 } 3680 3681 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3682 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3683 return getSMaxExpr(Ops); 3684 } 3685 3686 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3687 return getMinMaxExpr(scSMaxExpr, Ops); 3688 } 3689 3690 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3691 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3692 return getUMaxExpr(Ops); 3693 } 3694 3695 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3696 return getMinMaxExpr(scUMaxExpr, Ops); 3697 } 3698 3699 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3700 const SCEV *RHS) { 3701 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3702 return getSMinExpr(Ops); 3703 } 3704 3705 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3706 return getMinMaxExpr(scSMinExpr, Ops); 3707 } 3708 3709 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3710 const SCEV *RHS) { 3711 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3712 return getUMinExpr(Ops); 3713 } 3714 3715 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3716 return getMinMaxExpr(scUMinExpr, Ops); 3717 } 3718 3719 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3720 // We can bypass creating a target-independent 3721 // constant expression and then folding it back into a ConstantInt. 3722 // This is just a compile-time optimization. 3723 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3724 } 3725 3726 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3727 StructType *STy, 3728 unsigned FieldNo) { 3729 // We can bypass creating a target-independent 3730 // constant expression and then folding it back into a ConstantInt. 3731 // This is just a compile-time optimization. 3732 return getConstant( 3733 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3734 } 3735 3736 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3737 // Don't attempt to do anything other than create a SCEVUnknown object 3738 // here. createSCEV only calls getUnknown after checking for all other 3739 // interesting possibilities, and any other code that calls getUnknown 3740 // is doing so in order to hide a value from SCEV canonicalization. 3741 3742 FoldingSetNodeID ID; 3743 ID.AddInteger(scUnknown); 3744 ID.AddPointer(V); 3745 void *IP = nullptr; 3746 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3747 assert(cast<SCEVUnknown>(S)->getValue() == V && 3748 "Stale SCEVUnknown in uniquing map!"); 3749 return S; 3750 } 3751 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3752 FirstUnknown); 3753 FirstUnknown = cast<SCEVUnknown>(S); 3754 UniqueSCEVs.InsertNode(S, IP); 3755 return S; 3756 } 3757 3758 //===----------------------------------------------------------------------===// 3759 // Basic SCEV Analysis and PHI Idiom Recognition Code 3760 // 3761 3762 /// Test if values of the given type are analyzable within the SCEV 3763 /// framework. This primarily includes integer types, and it can optionally 3764 /// include pointer types if the ScalarEvolution class has access to 3765 /// target-specific information. 3766 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3767 // Integers and pointers are always SCEVable. 3768 return Ty->isIntOrPtrTy(); 3769 } 3770 3771 /// Return the size in bits of the specified type, for which isSCEVable must 3772 /// return true. 3773 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3774 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3775 if (Ty->isPointerTy()) 3776 return getDataLayout().getIndexTypeSizeInBits(Ty); 3777 return getDataLayout().getTypeSizeInBits(Ty); 3778 } 3779 3780 /// Return a type with the same bitwidth as the given type and which represents 3781 /// how SCEV will treat the given type, for which isSCEVable must return 3782 /// true. For pointer types, this is the pointer-sized integer type. 3783 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3784 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3785 3786 if (Ty->isIntegerTy()) 3787 return Ty; 3788 3789 // The only other support type is pointer. 3790 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3791 return getDataLayout().getIntPtrType(Ty); 3792 } 3793 3794 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3795 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3796 } 3797 3798 const SCEV *ScalarEvolution::getCouldNotCompute() { 3799 return CouldNotCompute.get(); 3800 } 3801 3802 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3803 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3804 auto *SU = dyn_cast<SCEVUnknown>(S); 3805 return SU && SU->getValue() == nullptr; 3806 }); 3807 3808 return !ContainsNulls; 3809 } 3810 3811 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3812 HasRecMapType::iterator I = HasRecMap.find(S); 3813 if (I != HasRecMap.end()) 3814 return I->second; 3815 3816 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3817 HasRecMap.insert({S, FoundAddRec}); 3818 return FoundAddRec; 3819 } 3820 3821 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3822 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3823 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3824 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3825 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3826 if (!Add) 3827 return {S, nullptr}; 3828 3829 if (Add->getNumOperands() != 2) 3830 return {S, nullptr}; 3831 3832 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3833 if (!ConstOp) 3834 return {S, nullptr}; 3835 3836 return {Add->getOperand(1), ConstOp->getValue()}; 3837 } 3838 3839 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3840 /// by the value and offset from any ValueOffsetPair in the set. 3841 SetVector<ScalarEvolution::ValueOffsetPair> * 3842 ScalarEvolution::getSCEVValues(const SCEV *S) { 3843 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3844 if (SI == ExprValueMap.end()) 3845 return nullptr; 3846 #ifndef NDEBUG 3847 if (VerifySCEVMap) { 3848 // Check there is no dangling Value in the set returned. 3849 for (const auto &VE : SI->second) 3850 assert(ValueExprMap.count(VE.first)); 3851 } 3852 #endif 3853 return &SI->second; 3854 } 3855 3856 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3857 /// cannot be used separately. eraseValueFromMap should be used to remove 3858 /// V from ValueExprMap and ExprValueMap at the same time. 3859 void ScalarEvolution::eraseValueFromMap(Value *V) { 3860 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3861 if (I != ValueExprMap.end()) { 3862 const SCEV *S = I->second; 3863 // Remove {V, 0} from the set of ExprValueMap[S] 3864 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3865 SV->remove({V, nullptr}); 3866 3867 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3868 const SCEV *Stripped; 3869 ConstantInt *Offset; 3870 std::tie(Stripped, Offset) = splitAddExpr(S); 3871 if (Offset != nullptr) { 3872 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3873 SV->remove({V, Offset}); 3874 } 3875 ValueExprMap.erase(V); 3876 } 3877 } 3878 3879 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3880 /// TODO: In reality it is better to check the poison recursively 3881 /// but this is better than nothing. 3882 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3883 if (auto *I = dyn_cast<Instruction>(V)) { 3884 if (isa<OverflowingBinaryOperator>(I)) { 3885 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3886 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3887 return true; 3888 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3889 return true; 3890 } 3891 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3892 return true; 3893 } 3894 return false; 3895 } 3896 3897 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3898 /// create a new one. 3899 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3900 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3901 3902 const SCEV *S = getExistingSCEV(V); 3903 if (S == nullptr) { 3904 S = createSCEV(V); 3905 // During PHI resolution, it is possible to create two SCEVs for the same 3906 // V, so it is needed to double check whether V->S is inserted into 3907 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3908 std::pair<ValueExprMapType::iterator, bool> Pair = 3909 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3910 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3911 ExprValueMap[S].insert({V, nullptr}); 3912 3913 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3914 // ExprValueMap. 3915 const SCEV *Stripped = S; 3916 ConstantInt *Offset = nullptr; 3917 std::tie(Stripped, Offset) = splitAddExpr(S); 3918 // If stripped is SCEVUnknown, don't bother to save 3919 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3920 // increase the complexity of the expansion code. 3921 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3922 // because it may generate add/sub instead of GEP in SCEV expansion. 3923 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3924 !isa<GetElementPtrInst>(V)) 3925 ExprValueMap[Stripped].insert({V, Offset}); 3926 } 3927 } 3928 return S; 3929 } 3930 3931 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3932 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3933 3934 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3935 if (I != ValueExprMap.end()) { 3936 const SCEV *S = I->second; 3937 if (checkValidity(S)) 3938 return S; 3939 eraseValueFromMap(V); 3940 forgetMemoizedResults(S); 3941 } 3942 return nullptr; 3943 } 3944 3945 /// Return a SCEV corresponding to -V = -1*V 3946 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3947 SCEV::NoWrapFlags Flags) { 3948 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3949 return getConstant( 3950 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3951 3952 Type *Ty = V->getType(); 3953 Ty = getEffectiveSCEVType(Ty); 3954 return getMulExpr( 3955 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3956 } 3957 3958 /// If Expr computes ~A, return A else return nullptr 3959 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3960 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3961 if (!Add || Add->getNumOperands() != 2 || 3962 !Add->getOperand(0)->isAllOnesValue()) 3963 return nullptr; 3964 3965 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3966 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3967 !AddRHS->getOperand(0)->isAllOnesValue()) 3968 return nullptr; 3969 3970 return AddRHS->getOperand(1); 3971 } 3972 3973 /// Return a SCEV corresponding to ~V = -1-V 3974 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3975 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3976 return getConstant( 3977 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3978 3979 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3980 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3981 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3982 SmallVector<const SCEV *, 2> MatchedOperands; 3983 for (const SCEV *Operand : MME->operands()) { 3984 const SCEV *Matched = MatchNotExpr(Operand); 3985 if (!Matched) 3986 return (const SCEV *)nullptr; 3987 MatchedOperands.push_back(Matched); 3988 } 3989 return getMinMaxExpr( 3990 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3991 MatchedOperands); 3992 }; 3993 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3994 return Replaced; 3995 } 3996 3997 Type *Ty = V->getType(); 3998 Ty = getEffectiveSCEVType(Ty); 3999 const SCEV *AllOnes = 4000 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4001 return getMinusSCEV(AllOnes, V); 4002 } 4003 4004 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4005 SCEV::NoWrapFlags Flags, 4006 unsigned Depth) { 4007 // Fast path: X - X --> 0. 4008 if (LHS == RHS) 4009 return getZero(LHS->getType()); 4010 4011 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4012 // makes it so that we cannot make much use of NUW. 4013 auto AddFlags = SCEV::FlagAnyWrap; 4014 const bool RHSIsNotMinSigned = 4015 !getSignedRangeMin(RHS).isMinSignedValue(); 4016 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4017 // Let M be the minimum representable signed value. Then (-1)*RHS 4018 // signed-wraps if and only if RHS is M. That can happen even for 4019 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4020 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4021 // (-1)*RHS, we need to prove that RHS != M. 4022 // 4023 // If LHS is non-negative and we know that LHS - RHS does not 4024 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4025 // either by proving that RHS > M or that LHS >= 0. 4026 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4027 AddFlags = SCEV::FlagNSW; 4028 } 4029 } 4030 4031 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4032 // RHS is NSW and LHS >= 0. 4033 // 4034 // The difficulty here is that the NSW flag may have been proven 4035 // relative to a loop that is to be found in a recurrence in LHS and 4036 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4037 // larger scope than intended. 4038 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4039 4040 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4041 } 4042 4043 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4044 unsigned Depth) { 4045 Type *SrcTy = V->getType(); 4046 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4047 "Cannot truncate or zero extend with non-integer arguments!"); 4048 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4049 return V; // No conversion 4050 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4051 return getTruncateExpr(V, Ty, Depth); 4052 return getZeroExtendExpr(V, Ty, Depth); 4053 } 4054 4055 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4056 unsigned Depth) { 4057 Type *SrcTy = V->getType(); 4058 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4059 "Cannot truncate or zero extend with non-integer arguments!"); 4060 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4061 return V; // No conversion 4062 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4063 return getTruncateExpr(V, Ty, Depth); 4064 return getSignExtendExpr(V, Ty, Depth); 4065 } 4066 4067 const SCEV * 4068 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4069 Type *SrcTy = V->getType(); 4070 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4071 "Cannot noop or zero extend with non-integer arguments!"); 4072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4073 "getNoopOrZeroExtend cannot truncate!"); 4074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4075 return V; // No conversion 4076 return getZeroExtendExpr(V, Ty); 4077 } 4078 4079 const SCEV * 4080 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4081 Type *SrcTy = V->getType(); 4082 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4083 "Cannot noop or sign extend with non-integer arguments!"); 4084 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4085 "getNoopOrSignExtend cannot truncate!"); 4086 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4087 return V; // No conversion 4088 return getSignExtendExpr(V, Ty); 4089 } 4090 4091 const SCEV * 4092 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4093 Type *SrcTy = V->getType(); 4094 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4095 "Cannot noop or any extend with non-integer arguments!"); 4096 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4097 "getNoopOrAnyExtend cannot truncate!"); 4098 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4099 return V; // No conversion 4100 return getAnyExtendExpr(V, Ty); 4101 } 4102 4103 const SCEV * 4104 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4105 Type *SrcTy = V->getType(); 4106 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4107 "Cannot truncate or noop with non-integer arguments!"); 4108 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4109 "getTruncateOrNoop cannot extend!"); 4110 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4111 return V; // No conversion 4112 return getTruncateExpr(V, Ty); 4113 } 4114 4115 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4116 const SCEV *RHS) { 4117 const SCEV *PromotedLHS = LHS; 4118 const SCEV *PromotedRHS = RHS; 4119 4120 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4121 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4122 else 4123 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4124 4125 return getUMaxExpr(PromotedLHS, PromotedRHS); 4126 } 4127 4128 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4129 const SCEV *RHS) { 4130 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4131 return getUMinFromMismatchedTypes(Ops); 4132 } 4133 4134 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4135 SmallVectorImpl<const SCEV *> &Ops) { 4136 assert(!Ops.empty() && "At least one operand must be!"); 4137 // Trivial case. 4138 if (Ops.size() == 1) 4139 return Ops[0]; 4140 4141 // Find the max type first. 4142 Type *MaxType = nullptr; 4143 for (auto *S : Ops) 4144 if (MaxType) 4145 MaxType = getWiderType(MaxType, S->getType()); 4146 else 4147 MaxType = S->getType(); 4148 4149 // Extend all ops to max type. 4150 SmallVector<const SCEV *, 2> PromotedOps; 4151 for (auto *S : Ops) 4152 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4153 4154 // Generate umin. 4155 return getUMinExpr(PromotedOps); 4156 } 4157 4158 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4159 // A pointer operand may evaluate to a nonpointer expression, such as null. 4160 if (!V->getType()->isPointerTy()) 4161 return V; 4162 4163 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4164 return getPointerBase(Cast->getOperand()); 4165 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4166 const SCEV *PtrOp = nullptr; 4167 for (const SCEV *NAryOp : NAry->operands()) { 4168 if (NAryOp->getType()->isPointerTy()) { 4169 // Cannot find the base of an expression with multiple pointer operands. 4170 if (PtrOp) 4171 return V; 4172 PtrOp = NAryOp; 4173 } 4174 } 4175 if (!PtrOp) 4176 return V; 4177 return getPointerBase(PtrOp); 4178 } 4179 return V; 4180 } 4181 4182 /// Push users of the given Instruction onto the given Worklist. 4183 static void 4184 PushDefUseChildren(Instruction *I, 4185 SmallVectorImpl<Instruction *> &Worklist) { 4186 // Push the def-use children onto the Worklist stack. 4187 for (User *U : I->users()) 4188 Worklist.push_back(cast<Instruction>(U)); 4189 } 4190 4191 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4192 SmallVector<Instruction *, 16> Worklist; 4193 PushDefUseChildren(PN, Worklist); 4194 4195 SmallPtrSet<Instruction *, 8> Visited; 4196 Visited.insert(PN); 4197 while (!Worklist.empty()) { 4198 Instruction *I = Worklist.pop_back_val(); 4199 if (!Visited.insert(I).second) 4200 continue; 4201 4202 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4203 if (It != ValueExprMap.end()) { 4204 const SCEV *Old = It->second; 4205 4206 // Short-circuit the def-use traversal if the symbolic name 4207 // ceases to appear in expressions. 4208 if (Old != SymName && !hasOperand(Old, SymName)) 4209 continue; 4210 4211 // SCEVUnknown for a PHI either means that it has an unrecognized 4212 // structure, it's a PHI that's in the progress of being computed 4213 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4214 // additional loop trip count information isn't going to change anything. 4215 // In the second case, createNodeForPHI will perform the necessary 4216 // updates on its own when it gets to that point. In the third, we do 4217 // want to forget the SCEVUnknown. 4218 if (!isa<PHINode>(I) || 4219 !isa<SCEVUnknown>(Old) || 4220 (I != PN && Old == SymName)) { 4221 eraseValueFromMap(It->first); 4222 forgetMemoizedResults(Old); 4223 } 4224 } 4225 4226 PushDefUseChildren(I, Worklist); 4227 } 4228 } 4229 4230 namespace { 4231 4232 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4233 /// expression in case its Loop is L. If it is not L then 4234 /// if IgnoreOtherLoops is true then use AddRec itself 4235 /// otherwise rewrite cannot be done. 4236 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4237 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4238 public: 4239 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4240 bool IgnoreOtherLoops = true) { 4241 SCEVInitRewriter Rewriter(L, SE); 4242 const SCEV *Result = Rewriter.visit(S); 4243 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4244 return SE.getCouldNotCompute(); 4245 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4246 ? SE.getCouldNotCompute() 4247 : Result; 4248 } 4249 4250 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4251 if (!SE.isLoopInvariant(Expr, L)) 4252 SeenLoopVariantSCEVUnknown = true; 4253 return Expr; 4254 } 4255 4256 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4257 // Only re-write AddRecExprs for this loop. 4258 if (Expr->getLoop() == L) 4259 return Expr->getStart(); 4260 SeenOtherLoops = true; 4261 return Expr; 4262 } 4263 4264 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4265 4266 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4267 4268 private: 4269 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4270 : SCEVRewriteVisitor(SE), L(L) {} 4271 4272 const Loop *L; 4273 bool SeenLoopVariantSCEVUnknown = false; 4274 bool SeenOtherLoops = false; 4275 }; 4276 4277 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4278 /// increment expression in case its Loop is L. If it is not L then 4279 /// use AddRec itself. 4280 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4281 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4282 public: 4283 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4284 SCEVPostIncRewriter Rewriter(L, SE); 4285 const SCEV *Result = Rewriter.visit(S); 4286 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4287 ? SE.getCouldNotCompute() 4288 : Result; 4289 } 4290 4291 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4292 if (!SE.isLoopInvariant(Expr, L)) 4293 SeenLoopVariantSCEVUnknown = true; 4294 return Expr; 4295 } 4296 4297 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4298 // Only re-write AddRecExprs for this loop. 4299 if (Expr->getLoop() == L) 4300 return Expr->getPostIncExpr(SE); 4301 SeenOtherLoops = true; 4302 return Expr; 4303 } 4304 4305 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4306 4307 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4308 4309 private: 4310 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4311 : SCEVRewriteVisitor(SE), L(L) {} 4312 4313 const Loop *L; 4314 bool SeenLoopVariantSCEVUnknown = false; 4315 bool SeenOtherLoops = false; 4316 }; 4317 4318 /// This class evaluates the compare condition by matching it against the 4319 /// condition of loop latch. If there is a match we assume a true value 4320 /// for the condition while building SCEV nodes. 4321 class SCEVBackedgeConditionFolder 4322 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4323 public: 4324 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4325 ScalarEvolution &SE) { 4326 bool IsPosBECond = false; 4327 Value *BECond = nullptr; 4328 if (BasicBlock *Latch = L->getLoopLatch()) { 4329 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4330 if (BI && BI->isConditional()) { 4331 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4332 "Both outgoing branches should not target same header!"); 4333 BECond = BI->getCondition(); 4334 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4335 } else { 4336 return S; 4337 } 4338 } 4339 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4340 return Rewriter.visit(S); 4341 } 4342 4343 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4344 const SCEV *Result = Expr; 4345 bool InvariantF = SE.isLoopInvariant(Expr, L); 4346 4347 if (!InvariantF) { 4348 Instruction *I = cast<Instruction>(Expr->getValue()); 4349 switch (I->getOpcode()) { 4350 case Instruction::Select: { 4351 SelectInst *SI = cast<SelectInst>(I); 4352 Optional<const SCEV *> Res = 4353 compareWithBackedgeCondition(SI->getCondition()); 4354 if (Res.hasValue()) { 4355 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4356 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4357 } 4358 break; 4359 } 4360 default: { 4361 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4362 if (Res.hasValue()) 4363 Result = Res.getValue(); 4364 break; 4365 } 4366 } 4367 } 4368 return Result; 4369 } 4370 4371 private: 4372 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4373 bool IsPosBECond, ScalarEvolution &SE) 4374 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4375 IsPositiveBECond(IsPosBECond) {} 4376 4377 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4378 4379 const Loop *L; 4380 /// Loop back condition. 4381 Value *BackedgeCond = nullptr; 4382 /// Set to true if loop back is on positive branch condition. 4383 bool IsPositiveBECond; 4384 }; 4385 4386 Optional<const SCEV *> 4387 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4388 4389 // If value matches the backedge condition for loop latch, 4390 // then return a constant evolution node based on loopback 4391 // branch taken. 4392 if (BackedgeCond == IC) 4393 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4394 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4395 return None; 4396 } 4397 4398 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4399 public: 4400 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4401 ScalarEvolution &SE) { 4402 SCEVShiftRewriter Rewriter(L, SE); 4403 const SCEV *Result = Rewriter.visit(S); 4404 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4405 } 4406 4407 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4408 // Only allow AddRecExprs for this loop. 4409 if (!SE.isLoopInvariant(Expr, L)) 4410 Valid = false; 4411 return Expr; 4412 } 4413 4414 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4415 if (Expr->getLoop() == L && Expr->isAffine()) 4416 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4417 Valid = false; 4418 return Expr; 4419 } 4420 4421 bool isValid() { return Valid; } 4422 4423 private: 4424 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4425 : SCEVRewriteVisitor(SE), L(L) {} 4426 4427 const Loop *L; 4428 bool Valid = true; 4429 }; 4430 4431 } // end anonymous namespace 4432 4433 SCEV::NoWrapFlags 4434 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4435 if (!AR->isAffine()) 4436 return SCEV::FlagAnyWrap; 4437 4438 using OBO = OverflowingBinaryOperator; 4439 4440 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4441 4442 if (!AR->hasNoSignedWrap()) { 4443 ConstantRange AddRecRange = getSignedRange(AR); 4444 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4445 4446 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4447 Instruction::Add, IncRange, OBO::NoSignedWrap); 4448 if (NSWRegion.contains(AddRecRange)) 4449 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4450 } 4451 4452 if (!AR->hasNoUnsignedWrap()) { 4453 ConstantRange AddRecRange = getUnsignedRange(AR); 4454 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4455 4456 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4457 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4458 if (NUWRegion.contains(AddRecRange)) 4459 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4460 } 4461 4462 return Result; 4463 } 4464 4465 namespace { 4466 4467 /// Represents an abstract binary operation. This may exist as a 4468 /// normal instruction or constant expression, or may have been 4469 /// derived from an expression tree. 4470 struct BinaryOp { 4471 unsigned Opcode; 4472 Value *LHS; 4473 Value *RHS; 4474 bool IsNSW = false; 4475 bool IsNUW = false; 4476 4477 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4478 /// constant expression. 4479 Operator *Op = nullptr; 4480 4481 explicit BinaryOp(Operator *Op) 4482 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4483 Op(Op) { 4484 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4485 IsNSW = OBO->hasNoSignedWrap(); 4486 IsNUW = OBO->hasNoUnsignedWrap(); 4487 } 4488 } 4489 4490 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4491 bool IsNUW = false) 4492 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4493 }; 4494 4495 } // end anonymous namespace 4496 4497 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4498 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4499 auto *Op = dyn_cast<Operator>(V); 4500 if (!Op) 4501 return None; 4502 4503 // Implementation detail: all the cleverness here should happen without 4504 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4505 // SCEV expressions when possible, and we should not break that. 4506 4507 switch (Op->getOpcode()) { 4508 case Instruction::Add: 4509 case Instruction::Sub: 4510 case Instruction::Mul: 4511 case Instruction::UDiv: 4512 case Instruction::URem: 4513 case Instruction::And: 4514 case Instruction::Or: 4515 case Instruction::AShr: 4516 case Instruction::Shl: 4517 return BinaryOp(Op); 4518 4519 case Instruction::Xor: 4520 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4521 // If the RHS of the xor is a signmask, then this is just an add. 4522 // Instcombine turns add of signmask into xor as a strength reduction step. 4523 if (RHSC->getValue().isSignMask()) 4524 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4525 return BinaryOp(Op); 4526 4527 case Instruction::LShr: 4528 // Turn logical shift right of a constant into a unsigned divide. 4529 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4530 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4531 4532 // If the shift count is not less than the bitwidth, the result of 4533 // the shift is undefined. Don't try to analyze it, because the 4534 // resolution chosen here may differ from the resolution chosen in 4535 // other parts of the compiler. 4536 if (SA->getValue().ult(BitWidth)) { 4537 Constant *X = 4538 ConstantInt::get(SA->getContext(), 4539 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4540 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4541 } 4542 } 4543 return BinaryOp(Op); 4544 4545 case Instruction::ExtractValue: { 4546 auto *EVI = cast<ExtractValueInst>(Op); 4547 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4548 break; 4549 4550 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4551 if (!WO) 4552 break; 4553 4554 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4555 bool Signed = WO->isSigned(); 4556 // TODO: Should add nuw/nsw flags for mul as well. 4557 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4558 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4559 4560 // Now that we know that all uses of the arithmetic-result component of 4561 // CI are guarded by the overflow check, we can go ahead and pretend 4562 // that the arithmetic is non-overflowing. 4563 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4564 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4565 } 4566 4567 default: 4568 break; 4569 } 4570 4571 return None; 4572 } 4573 4574 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4575 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4576 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4577 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4578 /// follows one of the following patterns: 4579 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4580 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4581 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4582 /// we return the type of the truncation operation, and indicate whether the 4583 /// truncated type should be treated as signed/unsigned by setting 4584 /// \p Signed to true/false, respectively. 4585 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4586 bool &Signed, ScalarEvolution &SE) { 4587 // The case where Op == SymbolicPHI (that is, with no type conversions on 4588 // the way) is handled by the regular add recurrence creating logic and 4589 // would have already been triggered in createAddRecForPHI. Reaching it here 4590 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4591 // because one of the other operands of the SCEVAddExpr updating this PHI is 4592 // not invariant). 4593 // 4594 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4595 // this case predicates that allow us to prove that Op == SymbolicPHI will 4596 // be added. 4597 if (Op == SymbolicPHI) 4598 return nullptr; 4599 4600 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4601 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4602 if (SourceBits != NewBits) 4603 return nullptr; 4604 4605 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4606 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4607 if (!SExt && !ZExt) 4608 return nullptr; 4609 const SCEVTruncateExpr *Trunc = 4610 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4611 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4612 if (!Trunc) 4613 return nullptr; 4614 const SCEV *X = Trunc->getOperand(); 4615 if (X != SymbolicPHI) 4616 return nullptr; 4617 Signed = SExt != nullptr; 4618 return Trunc->getType(); 4619 } 4620 4621 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4622 if (!PN->getType()->isIntegerTy()) 4623 return nullptr; 4624 const Loop *L = LI.getLoopFor(PN->getParent()); 4625 if (!L || L->getHeader() != PN->getParent()) 4626 return nullptr; 4627 return L; 4628 } 4629 4630 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4631 // computation that updates the phi follows the following pattern: 4632 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4633 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4634 // If so, try to see if it can be rewritten as an AddRecExpr under some 4635 // Predicates. If successful, return them as a pair. Also cache the results 4636 // of the analysis. 4637 // 4638 // Example usage scenario: 4639 // Say the Rewriter is called for the following SCEV: 4640 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4641 // where: 4642 // %X = phi i64 (%Start, %BEValue) 4643 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4644 // and call this function with %SymbolicPHI = %X. 4645 // 4646 // The analysis will find that the value coming around the backedge has 4647 // the following SCEV: 4648 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4649 // Upon concluding that this matches the desired pattern, the function 4650 // will return the pair {NewAddRec, SmallPredsVec} where: 4651 // NewAddRec = {%Start,+,%Step} 4652 // SmallPredsVec = {P1, P2, P3} as follows: 4653 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4654 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4655 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4656 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4657 // under the predicates {P1,P2,P3}. 4658 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4659 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4660 // 4661 // TODO's: 4662 // 4663 // 1) Extend the Induction descriptor to also support inductions that involve 4664 // casts: When needed (namely, when we are called in the context of the 4665 // vectorizer induction analysis), a Set of cast instructions will be 4666 // populated by this method, and provided back to isInductionPHI. This is 4667 // needed to allow the vectorizer to properly record them to be ignored by 4668 // the cost model and to avoid vectorizing them (otherwise these casts, 4669 // which are redundant under the runtime overflow checks, will be 4670 // vectorized, which can be costly). 4671 // 4672 // 2) Support additional induction/PHISCEV patterns: We also want to support 4673 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4674 // after the induction update operation (the induction increment): 4675 // 4676 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4677 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4678 // 4679 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4680 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4681 // 4682 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4683 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4684 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4685 SmallVector<const SCEVPredicate *, 3> Predicates; 4686 4687 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4688 // return an AddRec expression under some predicate. 4689 4690 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4691 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4692 assert(L && "Expecting an integer loop header phi"); 4693 4694 // The loop may have multiple entrances or multiple exits; we can analyze 4695 // this phi as an addrec if it has a unique entry value and a unique 4696 // backedge value. 4697 Value *BEValueV = nullptr, *StartValueV = nullptr; 4698 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4699 Value *V = PN->getIncomingValue(i); 4700 if (L->contains(PN->getIncomingBlock(i))) { 4701 if (!BEValueV) { 4702 BEValueV = V; 4703 } else if (BEValueV != V) { 4704 BEValueV = nullptr; 4705 break; 4706 } 4707 } else if (!StartValueV) { 4708 StartValueV = V; 4709 } else if (StartValueV != V) { 4710 StartValueV = nullptr; 4711 break; 4712 } 4713 } 4714 if (!BEValueV || !StartValueV) 4715 return None; 4716 4717 const SCEV *BEValue = getSCEV(BEValueV); 4718 4719 // If the value coming around the backedge is an add with the symbolic 4720 // value we just inserted, possibly with casts that we can ignore under 4721 // an appropriate runtime guard, then we found a simple induction variable! 4722 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4723 if (!Add) 4724 return None; 4725 4726 // If there is a single occurrence of the symbolic value, possibly 4727 // casted, replace it with a recurrence. 4728 unsigned FoundIndex = Add->getNumOperands(); 4729 Type *TruncTy = nullptr; 4730 bool Signed; 4731 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4732 if ((TruncTy = 4733 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4734 if (FoundIndex == e) { 4735 FoundIndex = i; 4736 break; 4737 } 4738 4739 if (FoundIndex == Add->getNumOperands()) 4740 return None; 4741 4742 // Create an add with everything but the specified operand. 4743 SmallVector<const SCEV *, 8> Ops; 4744 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4745 if (i != FoundIndex) 4746 Ops.push_back(Add->getOperand(i)); 4747 const SCEV *Accum = getAddExpr(Ops); 4748 4749 // The runtime checks will not be valid if the step amount is 4750 // varying inside the loop. 4751 if (!isLoopInvariant(Accum, L)) 4752 return None; 4753 4754 // *** Part2: Create the predicates 4755 4756 // Analysis was successful: we have a phi-with-cast pattern for which we 4757 // can return an AddRec expression under the following predicates: 4758 // 4759 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4760 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4761 // P2: An Equal predicate that guarantees that 4762 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4763 // P3: An Equal predicate that guarantees that 4764 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4765 // 4766 // As we next prove, the above predicates guarantee that: 4767 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4768 // 4769 // 4770 // More formally, we want to prove that: 4771 // Expr(i+1) = Start + (i+1) * Accum 4772 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4773 // 4774 // Given that: 4775 // 1) Expr(0) = Start 4776 // 2) Expr(1) = Start + Accum 4777 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4778 // 3) Induction hypothesis (step i): 4779 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4780 // 4781 // Proof: 4782 // Expr(i+1) = 4783 // = Start + (i+1)*Accum 4784 // = (Start + i*Accum) + Accum 4785 // = Expr(i) + Accum 4786 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4787 // :: from step i 4788 // 4789 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4790 // 4791 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4792 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4793 // + Accum :: from P3 4794 // 4795 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4796 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4797 // 4798 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4799 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4800 // 4801 // By induction, the same applies to all iterations 1<=i<n: 4802 // 4803 4804 // Create a truncated addrec for which we will add a no overflow check (P1). 4805 const SCEV *StartVal = getSCEV(StartValueV); 4806 const SCEV *PHISCEV = 4807 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4808 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4809 4810 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4811 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4812 // will be constant. 4813 // 4814 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4815 // add P1. 4816 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4817 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4818 Signed ? SCEVWrapPredicate::IncrementNSSW 4819 : SCEVWrapPredicate::IncrementNUSW; 4820 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4821 Predicates.push_back(AddRecPred); 4822 } 4823 4824 // Create the Equal Predicates P2,P3: 4825 4826 // It is possible that the predicates P2 and/or P3 are computable at 4827 // compile time due to StartVal and/or Accum being constants. 4828 // If either one is, then we can check that now and escape if either P2 4829 // or P3 is false. 4830 4831 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4832 // for each of StartVal and Accum 4833 auto getExtendedExpr = [&](const SCEV *Expr, 4834 bool CreateSignExtend) -> const SCEV * { 4835 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4836 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4837 const SCEV *ExtendedExpr = 4838 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4839 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4840 return ExtendedExpr; 4841 }; 4842 4843 // Given: 4844 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4845 // = getExtendedExpr(Expr) 4846 // Determine whether the predicate P: Expr == ExtendedExpr 4847 // is known to be false at compile time 4848 auto PredIsKnownFalse = [&](const SCEV *Expr, 4849 const SCEV *ExtendedExpr) -> bool { 4850 return Expr != ExtendedExpr && 4851 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4852 }; 4853 4854 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4855 if (PredIsKnownFalse(StartVal, StartExtended)) { 4856 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4857 return None; 4858 } 4859 4860 // The Step is always Signed (because the overflow checks are either 4861 // NSSW or NUSW) 4862 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4863 if (PredIsKnownFalse(Accum, AccumExtended)) { 4864 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4865 return None; 4866 } 4867 4868 auto AppendPredicate = [&](const SCEV *Expr, 4869 const SCEV *ExtendedExpr) -> void { 4870 if (Expr != ExtendedExpr && 4871 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4872 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4873 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4874 Predicates.push_back(Pred); 4875 } 4876 }; 4877 4878 AppendPredicate(StartVal, StartExtended); 4879 AppendPredicate(Accum, AccumExtended); 4880 4881 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4882 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4883 // into NewAR if it will also add the runtime overflow checks specified in 4884 // Predicates. 4885 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4886 4887 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4888 std::make_pair(NewAR, Predicates); 4889 // Remember the result of the analysis for this SCEV at this locayyytion. 4890 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4891 return PredRewrite; 4892 } 4893 4894 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4895 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4896 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4897 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4898 if (!L) 4899 return None; 4900 4901 // Check to see if we already analyzed this PHI. 4902 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4903 if (I != PredicatedSCEVRewrites.end()) { 4904 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4905 I->second; 4906 // Analysis was done before and failed to create an AddRec: 4907 if (Rewrite.first == SymbolicPHI) 4908 return None; 4909 // Analysis was done before and succeeded to create an AddRec under 4910 // a predicate: 4911 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4912 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4913 return Rewrite; 4914 } 4915 4916 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4917 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4918 4919 // Record in the cache that the analysis failed 4920 if (!Rewrite) { 4921 SmallVector<const SCEVPredicate *, 3> Predicates; 4922 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4923 return None; 4924 } 4925 4926 return Rewrite; 4927 } 4928 4929 // FIXME: This utility is currently required because the Rewriter currently 4930 // does not rewrite this expression: 4931 // {0, +, (sext ix (trunc iy to ix) to iy)} 4932 // into {0, +, %step}, 4933 // even when the following Equal predicate exists: 4934 // "%step == (sext ix (trunc iy to ix) to iy)". 4935 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4936 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4937 if (AR1 == AR2) 4938 return true; 4939 4940 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4941 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4942 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4943 return false; 4944 return true; 4945 }; 4946 4947 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4948 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4949 return false; 4950 return true; 4951 } 4952 4953 /// A helper function for createAddRecFromPHI to handle simple cases. 4954 /// 4955 /// This function tries to find an AddRec expression for the simplest (yet most 4956 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4957 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4958 /// technique for finding the AddRec expression. 4959 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4960 Value *BEValueV, 4961 Value *StartValueV) { 4962 const Loop *L = LI.getLoopFor(PN->getParent()); 4963 assert(L && L->getHeader() == PN->getParent()); 4964 assert(BEValueV && StartValueV); 4965 4966 auto BO = MatchBinaryOp(BEValueV, DT); 4967 if (!BO) 4968 return nullptr; 4969 4970 if (BO->Opcode != Instruction::Add) 4971 return nullptr; 4972 4973 const SCEV *Accum = nullptr; 4974 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4975 Accum = getSCEV(BO->RHS); 4976 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4977 Accum = getSCEV(BO->LHS); 4978 4979 if (!Accum) 4980 return nullptr; 4981 4982 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4983 if (BO->IsNUW) 4984 Flags = setFlags(Flags, SCEV::FlagNUW); 4985 if (BO->IsNSW) 4986 Flags = setFlags(Flags, SCEV::FlagNSW); 4987 4988 const SCEV *StartVal = getSCEV(StartValueV); 4989 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4990 4991 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4992 4993 // We can add Flags to the post-inc expression only if we 4994 // know that it is *undefined behavior* for BEValueV to 4995 // overflow. 4996 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4997 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4998 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4999 5000 return PHISCEV; 5001 } 5002 5003 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5004 const Loop *L = LI.getLoopFor(PN->getParent()); 5005 if (!L || L->getHeader() != PN->getParent()) 5006 return nullptr; 5007 5008 // The loop may have multiple entrances or multiple exits; we can analyze 5009 // this phi as an addrec if it has a unique entry value and a unique 5010 // backedge value. 5011 Value *BEValueV = nullptr, *StartValueV = nullptr; 5012 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5013 Value *V = PN->getIncomingValue(i); 5014 if (L->contains(PN->getIncomingBlock(i))) { 5015 if (!BEValueV) { 5016 BEValueV = V; 5017 } else if (BEValueV != V) { 5018 BEValueV = nullptr; 5019 break; 5020 } 5021 } else if (!StartValueV) { 5022 StartValueV = V; 5023 } else if (StartValueV != V) { 5024 StartValueV = nullptr; 5025 break; 5026 } 5027 } 5028 if (!BEValueV || !StartValueV) 5029 return nullptr; 5030 5031 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5032 "PHI node already processed?"); 5033 5034 // First, try to find AddRec expression without creating a fictituos symbolic 5035 // value for PN. 5036 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5037 return S; 5038 5039 // Handle PHI node value symbolically. 5040 const SCEV *SymbolicName = getUnknown(PN); 5041 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5042 5043 // Using this symbolic name for the PHI, analyze the value coming around 5044 // the back-edge. 5045 const SCEV *BEValue = getSCEV(BEValueV); 5046 5047 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5048 // has a special value for the first iteration of the loop. 5049 5050 // If the value coming around the backedge is an add with the symbolic 5051 // value we just inserted, then we found a simple induction variable! 5052 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5053 // If there is a single occurrence of the symbolic value, replace it 5054 // with a recurrence. 5055 unsigned FoundIndex = Add->getNumOperands(); 5056 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5057 if (Add->getOperand(i) == SymbolicName) 5058 if (FoundIndex == e) { 5059 FoundIndex = i; 5060 break; 5061 } 5062 5063 if (FoundIndex != Add->getNumOperands()) { 5064 // Create an add with everything but the specified operand. 5065 SmallVector<const SCEV *, 8> Ops; 5066 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5067 if (i != FoundIndex) 5068 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5069 L, *this)); 5070 const SCEV *Accum = getAddExpr(Ops); 5071 5072 // This is not a valid addrec if the step amount is varying each 5073 // loop iteration, but is not itself an addrec in this loop. 5074 if (isLoopInvariant(Accum, L) || 5075 (isa<SCEVAddRecExpr>(Accum) && 5076 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5077 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5078 5079 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5080 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5081 if (BO->IsNUW) 5082 Flags = setFlags(Flags, SCEV::FlagNUW); 5083 if (BO->IsNSW) 5084 Flags = setFlags(Flags, SCEV::FlagNSW); 5085 } 5086 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5087 // If the increment is an inbounds GEP, then we know the address 5088 // space cannot be wrapped around. We cannot make any guarantee 5089 // about signed or unsigned overflow because pointers are 5090 // unsigned but we may have a negative index from the base 5091 // pointer. We can guarantee that no unsigned wrap occurs if the 5092 // indices form a positive value. 5093 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5094 Flags = setFlags(Flags, SCEV::FlagNW); 5095 5096 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5097 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5098 Flags = setFlags(Flags, SCEV::FlagNUW); 5099 } 5100 5101 // We cannot transfer nuw and nsw flags from subtraction 5102 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5103 // for instance. 5104 } 5105 5106 const SCEV *StartVal = getSCEV(StartValueV); 5107 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5108 5109 // Okay, for the entire analysis of this edge we assumed the PHI 5110 // to be symbolic. We now need to go back and purge all of the 5111 // entries for the scalars that use the symbolic expression. 5112 forgetSymbolicName(PN, SymbolicName); 5113 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5114 5115 // We can add Flags to the post-inc expression only if we 5116 // know that it is *undefined behavior* for BEValueV to 5117 // overflow. 5118 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5119 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5120 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5121 5122 return PHISCEV; 5123 } 5124 } 5125 } else { 5126 // Otherwise, this could be a loop like this: 5127 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5128 // In this case, j = {1,+,1} and BEValue is j. 5129 // Because the other in-value of i (0) fits the evolution of BEValue 5130 // i really is an addrec evolution. 5131 // 5132 // We can generalize this saying that i is the shifted value of BEValue 5133 // by one iteration: 5134 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5135 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5136 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5137 if (Shifted != getCouldNotCompute() && 5138 Start != getCouldNotCompute()) { 5139 const SCEV *StartVal = getSCEV(StartValueV); 5140 if (Start == StartVal) { 5141 // Okay, for the entire analysis of this edge we assumed the PHI 5142 // to be symbolic. We now need to go back and purge all of the 5143 // entries for the scalars that use the symbolic expression. 5144 forgetSymbolicName(PN, SymbolicName); 5145 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5146 return Shifted; 5147 } 5148 } 5149 } 5150 5151 // Remove the temporary PHI node SCEV that has been inserted while intending 5152 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5153 // as it will prevent later (possibly simpler) SCEV expressions to be added 5154 // to the ValueExprMap. 5155 eraseValueFromMap(PN); 5156 5157 return nullptr; 5158 } 5159 5160 // Checks if the SCEV S is available at BB. S is considered available at BB 5161 // if S can be materialized at BB without introducing a fault. 5162 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5163 BasicBlock *BB) { 5164 struct CheckAvailable { 5165 bool TraversalDone = false; 5166 bool Available = true; 5167 5168 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5169 BasicBlock *BB = nullptr; 5170 DominatorTree &DT; 5171 5172 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5173 : L(L), BB(BB), DT(DT) {} 5174 5175 bool setUnavailable() { 5176 TraversalDone = true; 5177 Available = false; 5178 return false; 5179 } 5180 5181 bool follow(const SCEV *S) { 5182 switch (S->getSCEVType()) { 5183 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5184 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5185 case scUMinExpr: 5186 case scSMinExpr: 5187 // These expressions are available if their operand(s) is/are. 5188 return true; 5189 5190 case scAddRecExpr: { 5191 // We allow add recurrences that are on the loop BB is in, or some 5192 // outer loop. This guarantees availability because the value of the 5193 // add recurrence at BB is simply the "current" value of the induction 5194 // variable. We can relax this in the future; for instance an add 5195 // recurrence on a sibling dominating loop is also available at BB. 5196 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5197 if (L && (ARLoop == L || ARLoop->contains(L))) 5198 return true; 5199 5200 return setUnavailable(); 5201 } 5202 5203 case scUnknown: { 5204 // For SCEVUnknown, we check for simple dominance. 5205 const auto *SU = cast<SCEVUnknown>(S); 5206 Value *V = SU->getValue(); 5207 5208 if (isa<Argument>(V)) 5209 return false; 5210 5211 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5212 return false; 5213 5214 return setUnavailable(); 5215 } 5216 5217 case scUDivExpr: 5218 case scCouldNotCompute: 5219 // We do not try to smart about these at all. 5220 return setUnavailable(); 5221 } 5222 llvm_unreachable("switch should be fully covered!"); 5223 } 5224 5225 bool isDone() { return TraversalDone; } 5226 }; 5227 5228 CheckAvailable CA(L, BB, DT); 5229 SCEVTraversal<CheckAvailable> ST(CA); 5230 5231 ST.visitAll(S); 5232 return CA.Available; 5233 } 5234 5235 // Try to match a control flow sequence that branches out at BI and merges back 5236 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5237 // match. 5238 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5239 Value *&C, Value *&LHS, Value *&RHS) { 5240 C = BI->getCondition(); 5241 5242 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5243 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5244 5245 if (!LeftEdge.isSingleEdge()) 5246 return false; 5247 5248 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5249 5250 Use &LeftUse = Merge->getOperandUse(0); 5251 Use &RightUse = Merge->getOperandUse(1); 5252 5253 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5254 LHS = LeftUse; 5255 RHS = RightUse; 5256 return true; 5257 } 5258 5259 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5260 LHS = RightUse; 5261 RHS = LeftUse; 5262 return true; 5263 } 5264 5265 return false; 5266 } 5267 5268 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5269 auto IsReachable = 5270 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5271 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5272 const Loop *L = LI.getLoopFor(PN->getParent()); 5273 5274 // We don't want to break LCSSA, even in a SCEV expression tree. 5275 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5276 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5277 return nullptr; 5278 5279 // Try to match 5280 // 5281 // br %cond, label %left, label %right 5282 // left: 5283 // br label %merge 5284 // right: 5285 // br label %merge 5286 // merge: 5287 // V = phi [ %x, %left ], [ %y, %right ] 5288 // 5289 // as "select %cond, %x, %y" 5290 5291 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5292 assert(IDom && "At least the entry block should dominate PN"); 5293 5294 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5295 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5296 5297 if (BI && BI->isConditional() && 5298 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5299 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5300 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5301 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5302 } 5303 5304 return nullptr; 5305 } 5306 5307 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5308 if (const SCEV *S = createAddRecFromPHI(PN)) 5309 return S; 5310 5311 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5312 return S; 5313 5314 // If the PHI has a single incoming value, follow that value, unless the 5315 // PHI's incoming blocks are in a different loop, in which case doing so 5316 // risks breaking LCSSA form. Instcombine would normally zap these, but 5317 // it doesn't have DominatorTree information, so it may miss cases. 5318 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5319 if (LI.replacementPreservesLCSSAForm(PN, V)) 5320 return getSCEV(V); 5321 5322 // If it's not a loop phi, we can't handle it yet. 5323 return getUnknown(PN); 5324 } 5325 5326 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5327 Value *Cond, 5328 Value *TrueVal, 5329 Value *FalseVal) { 5330 // Handle "constant" branch or select. This can occur for instance when a 5331 // loop pass transforms an inner loop and moves on to process the outer loop. 5332 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5333 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5334 5335 // Try to match some simple smax or umax patterns. 5336 auto *ICI = dyn_cast<ICmpInst>(Cond); 5337 if (!ICI) 5338 return getUnknown(I); 5339 5340 Value *LHS = ICI->getOperand(0); 5341 Value *RHS = ICI->getOperand(1); 5342 5343 switch (ICI->getPredicate()) { 5344 case ICmpInst::ICMP_SLT: 5345 case ICmpInst::ICMP_SLE: 5346 std::swap(LHS, RHS); 5347 LLVM_FALLTHROUGH; 5348 case ICmpInst::ICMP_SGT: 5349 case ICmpInst::ICMP_SGE: 5350 // a >s b ? a+x : b+x -> smax(a, b)+x 5351 // a >s b ? b+x : a+x -> smin(a, b)+x 5352 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5353 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5354 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5355 const SCEV *LA = getSCEV(TrueVal); 5356 const SCEV *RA = getSCEV(FalseVal); 5357 const SCEV *LDiff = getMinusSCEV(LA, LS); 5358 const SCEV *RDiff = getMinusSCEV(RA, RS); 5359 if (LDiff == RDiff) 5360 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5361 LDiff = getMinusSCEV(LA, RS); 5362 RDiff = getMinusSCEV(RA, LS); 5363 if (LDiff == RDiff) 5364 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5365 } 5366 break; 5367 case ICmpInst::ICMP_ULT: 5368 case ICmpInst::ICMP_ULE: 5369 std::swap(LHS, RHS); 5370 LLVM_FALLTHROUGH; 5371 case ICmpInst::ICMP_UGT: 5372 case ICmpInst::ICMP_UGE: 5373 // a >u b ? a+x : b+x -> umax(a, b)+x 5374 // a >u b ? b+x : a+x -> umin(a, b)+x 5375 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5376 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5377 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5378 const SCEV *LA = getSCEV(TrueVal); 5379 const SCEV *RA = getSCEV(FalseVal); 5380 const SCEV *LDiff = getMinusSCEV(LA, LS); 5381 const SCEV *RDiff = getMinusSCEV(RA, RS); 5382 if (LDiff == RDiff) 5383 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5384 LDiff = getMinusSCEV(LA, RS); 5385 RDiff = getMinusSCEV(RA, LS); 5386 if (LDiff == RDiff) 5387 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5388 } 5389 break; 5390 case ICmpInst::ICMP_NE: 5391 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5392 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5393 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5394 const SCEV *One = getOne(I->getType()); 5395 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5396 const SCEV *LA = getSCEV(TrueVal); 5397 const SCEV *RA = getSCEV(FalseVal); 5398 const SCEV *LDiff = getMinusSCEV(LA, LS); 5399 const SCEV *RDiff = getMinusSCEV(RA, One); 5400 if (LDiff == RDiff) 5401 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5402 } 5403 break; 5404 case ICmpInst::ICMP_EQ: 5405 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5406 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5407 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5408 const SCEV *One = getOne(I->getType()); 5409 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5410 const SCEV *LA = getSCEV(TrueVal); 5411 const SCEV *RA = getSCEV(FalseVal); 5412 const SCEV *LDiff = getMinusSCEV(LA, One); 5413 const SCEV *RDiff = getMinusSCEV(RA, LS); 5414 if (LDiff == RDiff) 5415 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5416 } 5417 break; 5418 default: 5419 break; 5420 } 5421 5422 return getUnknown(I); 5423 } 5424 5425 /// Expand GEP instructions into add and multiply operations. This allows them 5426 /// to be analyzed by regular SCEV code. 5427 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5428 // Don't attempt to analyze GEPs over unsized objects. 5429 if (!GEP->getSourceElementType()->isSized()) 5430 return getUnknown(GEP); 5431 5432 SmallVector<const SCEV *, 4> IndexExprs; 5433 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5434 IndexExprs.push_back(getSCEV(*Index)); 5435 return getGEPExpr(GEP, IndexExprs); 5436 } 5437 5438 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5439 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5440 return C->getAPInt().countTrailingZeros(); 5441 5442 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5443 return std::min(GetMinTrailingZeros(T->getOperand()), 5444 (uint32_t)getTypeSizeInBits(T->getType())); 5445 5446 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5447 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5448 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5449 ? getTypeSizeInBits(E->getType()) 5450 : OpRes; 5451 } 5452 5453 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5454 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5455 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5456 ? getTypeSizeInBits(E->getType()) 5457 : OpRes; 5458 } 5459 5460 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5461 // The result is the min of all operands results. 5462 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5463 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5464 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5465 return MinOpRes; 5466 } 5467 5468 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5469 // The result is the sum of all operands results. 5470 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5471 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5472 for (unsigned i = 1, e = M->getNumOperands(); 5473 SumOpRes != BitWidth && i != e; ++i) 5474 SumOpRes = 5475 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5476 return SumOpRes; 5477 } 5478 5479 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5480 // The result is the min of all operands results. 5481 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5482 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5483 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5484 return MinOpRes; 5485 } 5486 5487 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5488 // The result is the min of all operands results. 5489 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5490 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5491 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5492 return MinOpRes; 5493 } 5494 5495 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5496 // The result is the min of all operands results. 5497 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5498 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5500 return MinOpRes; 5501 } 5502 5503 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5504 // For a SCEVUnknown, ask ValueTracking. 5505 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5506 return Known.countMinTrailingZeros(); 5507 } 5508 5509 // SCEVUDivExpr 5510 return 0; 5511 } 5512 5513 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5514 auto I = MinTrailingZerosCache.find(S); 5515 if (I != MinTrailingZerosCache.end()) 5516 return I->second; 5517 5518 uint32_t Result = GetMinTrailingZerosImpl(S); 5519 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5520 assert(InsertPair.second && "Should insert a new key"); 5521 return InsertPair.first->second; 5522 } 5523 5524 /// Helper method to assign a range to V from metadata present in the IR. 5525 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5526 if (Instruction *I = dyn_cast<Instruction>(V)) 5527 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5528 return getConstantRangeFromMetadata(*MD); 5529 5530 return None; 5531 } 5532 5533 /// Determine the range for a particular SCEV. If SignHint is 5534 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5535 /// with a "cleaner" unsigned (resp. signed) representation. 5536 const ConstantRange & 5537 ScalarEvolution::getRangeRef(const SCEV *S, 5538 ScalarEvolution::RangeSignHint SignHint) { 5539 DenseMap<const SCEV *, ConstantRange> &Cache = 5540 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5541 : SignedRanges; 5542 ConstantRange::PreferredRangeType RangeType = 5543 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5544 ? ConstantRange::Unsigned : ConstantRange::Signed; 5545 5546 // See if we've computed this range already. 5547 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5548 if (I != Cache.end()) 5549 return I->second; 5550 5551 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5552 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5553 5554 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5555 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5556 5557 // If the value has known zeros, the maximum value will have those known zeros 5558 // as well. 5559 uint32_t TZ = GetMinTrailingZeros(S); 5560 if (TZ != 0) { 5561 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5562 ConservativeResult = 5563 ConstantRange(APInt::getMinValue(BitWidth), 5564 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5565 else 5566 ConservativeResult = ConstantRange( 5567 APInt::getSignedMinValue(BitWidth), 5568 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5569 } 5570 5571 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5572 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5573 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5574 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5575 return setRange(Add, SignHint, 5576 ConservativeResult.intersectWith(X, RangeType)); 5577 } 5578 5579 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5580 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5581 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5582 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5583 return setRange(Mul, SignHint, 5584 ConservativeResult.intersectWith(X, RangeType)); 5585 } 5586 5587 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5588 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5589 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5590 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5591 return setRange(SMax, SignHint, 5592 ConservativeResult.intersectWith(X, RangeType)); 5593 } 5594 5595 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5596 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5597 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5598 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5599 return setRange(UMax, SignHint, 5600 ConservativeResult.intersectWith(X, RangeType)); 5601 } 5602 5603 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5604 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5605 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5606 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5607 return setRange(SMin, SignHint, 5608 ConservativeResult.intersectWith(X, RangeType)); 5609 } 5610 5611 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5612 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5613 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5614 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5615 return setRange(UMin, SignHint, 5616 ConservativeResult.intersectWith(X, RangeType)); 5617 } 5618 5619 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5620 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5621 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5622 return setRange(UDiv, SignHint, 5623 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5624 } 5625 5626 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5627 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5628 return setRange(ZExt, SignHint, 5629 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5630 RangeType)); 5631 } 5632 5633 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5634 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5635 return setRange(SExt, SignHint, 5636 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5637 RangeType)); 5638 } 5639 5640 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5641 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5642 return setRange(Trunc, SignHint, 5643 ConservativeResult.intersectWith(X.truncate(BitWidth), 5644 RangeType)); 5645 } 5646 5647 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5648 // If there's no unsigned wrap, the value will never be less than its 5649 // initial value. 5650 if (AddRec->hasNoUnsignedWrap()) 5651 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5652 if (!C->getValue()->isZero()) 5653 ConservativeResult = ConservativeResult.intersectWith( 5654 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType); 5655 5656 // If there's no signed wrap, and all the operands have the same sign or 5657 // zero, the value won't ever change sign. 5658 if (AddRec->hasNoSignedWrap()) { 5659 bool AllNonNeg = true; 5660 bool AllNonPos = true; 5661 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5662 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5663 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5664 } 5665 if (AllNonNeg) 5666 ConservativeResult = ConservativeResult.intersectWith( 5667 ConstantRange(APInt(BitWidth, 0), 5668 APInt::getSignedMinValue(BitWidth)), RangeType); 5669 else if (AllNonPos) 5670 ConservativeResult = ConservativeResult.intersectWith( 5671 ConstantRange(APInt::getSignedMinValue(BitWidth), 5672 APInt(BitWidth, 1)), RangeType); 5673 } 5674 5675 // TODO: non-affine addrec 5676 if (AddRec->isAffine()) { 5677 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5678 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5679 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5680 auto RangeFromAffine = getRangeForAffineAR( 5681 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5682 BitWidth); 5683 if (!RangeFromAffine.isFullSet()) 5684 ConservativeResult = 5685 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5686 5687 auto RangeFromFactoring = getRangeViaFactoring( 5688 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5689 BitWidth); 5690 if (!RangeFromFactoring.isFullSet()) 5691 ConservativeResult = 5692 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5693 } 5694 } 5695 5696 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5697 } 5698 5699 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5700 // Check if the IR explicitly contains !range metadata. 5701 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5702 if (MDRange.hasValue()) 5703 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5704 RangeType); 5705 5706 // Split here to avoid paying the compile-time cost of calling both 5707 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5708 // if needed. 5709 const DataLayout &DL = getDataLayout(); 5710 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5711 // For a SCEVUnknown, ask ValueTracking. 5712 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5713 if (Known.One != ~Known.Zero + 1) 5714 ConservativeResult = 5715 ConservativeResult.intersectWith( 5716 ConstantRange(Known.One, ~Known.Zero + 1), RangeType); 5717 } else { 5718 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5719 "generalize as needed!"); 5720 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5721 if (NS > 1) 5722 ConservativeResult = ConservativeResult.intersectWith( 5723 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5724 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5725 RangeType); 5726 } 5727 5728 // A range of Phi is a subset of union of all ranges of its input. 5729 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5730 // Make sure that we do not run over cycled Phis. 5731 if (PendingPhiRanges.insert(Phi).second) { 5732 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5733 for (auto &Op : Phi->operands()) { 5734 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5735 RangeFromOps = RangeFromOps.unionWith(OpRange); 5736 // No point to continue if we already have a full set. 5737 if (RangeFromOps.isFullSet()) 5738 break; 5739 } 5740 ConservativeResult = 5741 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5742 bool Erased = PendingPhiRanges.erase(Phi); 5743 assert(Erased && "Failed to erase Phi properly?"); 5744 (void) Erased; 5745 } 5746 } 5747 5748 return setRange(U, SignHint, std::move(ConservativeResult)); 5749 } 5750 5751 return setRange(S, SignHint, std::move(ConservativeResult)); 5752 } 5753 5754 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5755 // values that the expression can take. Initially, the expression has a value 5756 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5757 // argument defines if we treat Step as signed or unsigned. 5758 static ConstantRange getRangeForAffineARHelper(APInt Step, 5759 const ConstantRange &StartRange, 5760 const APInt &MaxBECount, 5761 unsigned BitWidth, bool Signed) { 5762 // If either Step or MaxBECount is 0, then the expression won't change, and we 5763 // just need to return the initial range. 5764 if (Step == 0 || MaxBECount == 0) 5765 return StartRange; 5766 5767 // If we don't know anything about the initial value (i.e. StartRange is 5768 // FullRange), then we don't know anything about the final range either. 5769 // Return FullRange. 5770 if (StartRange.isFullSet()) 5771 return ConstantRange::getFull(BitWidth); 5772 5773 // If Step is signed and negative, then we use its absolute value, but we also 5774 // note that we're moving in the opposite direction. 5775 bool Descending = Signed && Step.isNegative(); 5776 5777 if (Signed) 5778 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5779 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5780 // This equations hold true due to the well-defined wrap-around behavior of 5781 // APInt. 5782 Step = Step.abs(); 5783 5784 // Check if Offset is more than full span of BitWidth. If it is, the 5785 // expression is guaranteed to overflow. 5786 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5787 return ConstantRange::getFull(BitWidth); 5788 5789 // Offset is by how much the expression can change. Checks above guarantee no 5790 // overflow here. 5791 APInt Offset = Step * MaxBECount; 5792 5793 // Minimum value of the final range will match the minimal value of StartRange 5794 // if the expression is increasing and will be decreased by Offset otherwise. 5795 // Maximum value of the final range will match the maximal value of StartRange 5796 // if the expression is decreasing and will be increased by Offset otherwise. 5797 APInt StartLower = StartRange.getLower(); 5798 APInt StartUpper = StartRange.getUpper() - 1; 5799 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5800 : (StartUpper + std::move(Offset)); 5801 5802 // It's possible that the new minimum/maximum value will fall into the initial 5803 // range (due to wrap around). This means that the expression can take any 5804 // value in this bitwidth, and we have to return full range. 5805 if (StartRange.contains(MovedBoundary)) 5806 return ConstantRange::getFull(BitWidth); 5807 5808 APInt NewLower = 5809 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5810 APInt NewUpper = 5811 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5812 NewUpper += 1; 5813 5814 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5815 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5816 } 5817 5818 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5819 const SCEV *Step, 5820 const SCEV *MaxBECount, 5821 unsigned BitWidth) { 5822 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5823 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5824 "Precondition!"); 5825 5826 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5827 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5828 5829 // First, consider step signed. 5830 ConstantRange StartSRange = getSignedRange(Start); 5831 ConstantRange StepSRange = getSignedRange(Step); 5832 5833 // If Step can be both positive and negative, we need to find ranges for the 5834 // maximum absolute step values in both directions and union them. 5835 ConstantRange SR = 5836 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5837 MaxBECountValue, BitWidth, /* Signed = */ true); 5838 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5839 StartSRange, MaxBECountValue, 5840 BitWidth, /* Signed = */ true)); 5841 5842 // Next, consider step unsigned. 5843 ConstantRange UR = getRangeForAffineARHelper( 5844 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5845 MaxBECountValue, BitWidth, /* Signed = */ false); 5846 5847 // Finally, intersect signed and unsigned ranges. 5848 return SR.intersectWith(UR, ConstantRange::Smallest); 5849 } 5850 5851 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5852 const SCEV *Step, 5853 const SCEV *MaxBECount, 5854 unsigned BitWidth) { 5855 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5856 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5857 5858 struct SelectPattern { 5859 Value *Condition = nullptr; 5860 APInt TrueValue; 5861 APInt FalseValue; 5862 5863 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5864 const SCEV *S) { 5865 Optional<unsigned> CastOp; 5866 APInt Offset(BitWidth, 0); 5867 5868 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5869 "Should be!"); 5870 5871 // Peel off a constant offset: 5872 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5873 // In the future we could consider being smarter here and handle 5874 // {Start+Step,+,Step} too. 5875 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5876 return; 5877 5878 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5879 S = SA->getOperand(1); 5880 } 5881 5882 // Peel off a cast operation 5883 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5884 CastOp = SCast->getSCEVType(); 5885 S = SCast->getOperand(); 5886 } 5887 5888 using namespace llvm::PatternMatch; 5889 5890 auto *SU = dyn_cast<SCEVUnknown>(S); 5891 const APInt *TrueVal, *FalseVal; 5892 if (!SU || 5893 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5894 m_APInt(FalseVal)))) { 5895 Condition = nullptr; 5896 return; 5897 } 5898 5899 TrueValue = *TrueVal; 5900 FalseValue = *FalseVal; 5901 5902 // Re-apply the cast we peeled off earlier 5903 if (CastOp.hasValue()) 5904 switch (*CastOp) { 5905 default: 5906 llvm_unreachable("Unknown SCEV cast type!"); 5907 5908 case scTruncate: 5909 TrueValue = TrueValue.trunc(BitWidth); 5910 FalseValue = FalseValue.trunc(BitWidth); 5911 break; 5912 case scZeroExtend: 5913 TrueValue = TrueValue.zext(BitWidth); 5914 FalseValue = FalseValue.zext(BitWidth); 5915 break; 5916 case scSignExtend: 5917 TrueValue = TrueValue.sext(BitWidth); 5918 FalseValue = FalseValue.sext(BitWidth); 5919 break; 5920 } 5921 5922 // Re-apply the constant offset we peeled off earlier 5923 TrueValue += Offset; 5924 FalseValue += Offset; 5925 } 5926 5927 bool isRecognized() { return Condition != nullptr; } 5928 }; 5929 5930 SelectPattern StartPattern(*this, BitWidth, Start); 5931 if (!StartPattern.isRecognized()) 5932 return ConstantRange::getFull(BitWidth); 5933 5934 SelectPattern StepPattern(*this, BitWidth, Step); 5935 if (!StepPattern.isRecognized()) 5936 return ConstantRange::getFull(BitWidth); 5937 5938 if (StartPattern.Condition != StepPattern.Condition) { 5939 // We don't handle this case today; but we could, by considering four 5940 // possibilities below instead of two. I'm not sure if there are cases where 5941 // that will help over what getRange already does, though. 5942 return ConstantRange::getFull(BitWidth); 5943 } 5944 5945 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5946 // construct arbitrary general SCEV expressions here. This function is called 5947 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5948 // say) can end up caching a suboptimal value. 5949 5950 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5951 // C2352 and C2512 (otherwise it isn't needed). 5952 5953 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5954 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5955 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5956 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5957 5958 ConstantRange TrueRange = 5959 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5960 ConstantRange FalseRange = 5961 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5962 5963 return TrueRange.unionWith(FalseRange); 5964 } 5965 5966 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5967 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5968 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5969 5970 // Return early if there are no flags to propagate to the SCEV. 5971 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5972 if (BinOp->hasNoUnsignedWrap()) 5973 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5974 if (BinOp->hasNoSignedWrap()) 5975 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5976 if (Flags == SCEV::FlagAnyWrap) 5977 return SCEV::FlagAnyWrap; 5978 5979 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5980 } 5981 5982 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5983 // Here we check that I is in the header of the innermost loop containing I, 5984 // since we only deal with instructions in the loop header. The actual loop we 5985 // need to check later will come from an add recurrence, but getting that 5986 // requires computing the SCEV of the operands, which can be expensive. This 5987 // check we can do cheaply to rule out some cases early. 5988 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5989 if (InnermostContainingLoop == nullptr || 5990 InnermostContainingLoop->getHeader() != I->getParent()) 5991 return false; 5992 5993 // Only proceed if we can prove that I does not yield poison. 5994 if (!programUndefinedIfFullPoison(I)) 5995 return false; 5996 5997 // At this point we know that if I is executed, then it does not wrap 5998 // according to at least one of NSW or NUW. If I is not executed, then we do 5999 // not know if the calculation that I represents would wrap. Multiple 6000 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6001 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6002 // derived from other instructions that map to the same SCEV. We cannot make 6003 // that guarantee for cases where I is not executed. So we need to find the 6004 // loop that I is considered in relation to and prove that I is executed for 6005 // every iteration of that loop. That implies that the value that I 6006 // calculates does not wrap anywhere in the loop, so then we can apply the 6007 // flags to the SCEV. 6008 // 6009 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6010 // from different loops, so that we know which loop to prove that I is 6011 // executed in. 6012 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6013 // I could be an extractvalue from a call to an overflow intrinsic. 6014 // TODO: We can do better here in some cases. 6015 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6016 return false; 6017 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6018 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6019 bool AllOtherOpsLoopInvariant = true; 6020 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6021 ++OtherOpIndex) { 6022 if (OtherOpIndex != OpIndex) { 6023 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6024 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6025 AllOtherOpsLoopInvariant = false; 6026 break; 6027 } 6028 } 6029 } 6030 if (AllOtherOpsLoopInvariant && 6031 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6032 return true; 6033 } 6034 } 6035 return false; 6036 } 6037 6038 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6039 // If we know that \c I can never be poison period, then that's enough. 6040 if (isSCEVExprNeverPoison(I)) 6041 return true; 6042 6043 // For an add recurrence specifically, we assume that infinite loops without 6044 // side effects are undefined behavior, and then reason as follows: 6045 // 6046 // If the add recurrence is poison in any iteration, it is poison on all 6047 // future iterations (since incrementing poison yields poison). If the result 6048 // of the add recurrence is fed into the loop latch condition and the loop 6049 // does not contain any throws or exiting blocks other than the latch, we now 6050 // have the ability to "choose" whether the backedge is taken or not (by 6051 // choosing a sufficiently evil value for the poison feeding into the branch) 6052 // for every iteration including and after the one in which \p I first became 6053 // poison. There are two possibilities (let's call the iteration in which \p 6054 // I first became poison as K): 6055 // 6056 // 1. In the set of iterations including and after K, the loop body executes 6057 // no side effects. In this case executing the backege an infinte number 6058 // of times will yield undefined behavior. 6059 // 6060 // 2. In the set of iterations including and after K, the loop body executes 6061 // at least one side effect. In this case, that specific instance of side 6062 // effect is control dependent on poison, which also yields undefined 6063 // behavior. 6064 6065 auto *ExitingBB = L->getExitingBlock(); 6066 auto *LatchBB = L->getLoopLatch(); 6067 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6068 return false; 6069 6070 SmallPtrSet<const Instruction *, 16> Pushed; 6071 SmallVector<const Instruction *, 8> PoisonStack; 6072 6073 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6074 // things that are known to be fully poison under that assumption go on the 6075 // PoisonStack. 6076 Pushed.insert(I); 6077 PoisonStack.push_back(I); 6078 6079 bool LatchControlDependentOnPoison = false; 6080 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6081 const Instruction *Poison = PoisonStack.pop_back_val(); 6082 6083 for (auto *PoisonUser : Poison->users()) { 6084 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6085 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6086 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6087 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6088 assert(BI->isConditional() && "Only possibility!"); 6089 if (BI->getParent() == LatchBB) { 6090 LatchControlDependentOnPoison = true; 6091 break; 6092 } 6093 } 6094 } 6095 } 6096 6097 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6098 } 6099 6100 ScalarEvolution::LoopProperties 6101 ScalarEvolution::getLoopProperties(const Loop *L) { 6102 using LoopProperties = ScalarEvolution::LoopProperties; 6103 6104 auto Itr = LoopPropertiesCache.find(L); 6105 if (Itr == LoopPropertiesCache.end()) { 6106 auto HasSideEffects = [](Instruction *I) { 6107 if (auto *SI = dyn_cast<StoreInst>(I)) 6108 return !SI->isSimple(); 6109 6110 return I->mayHaveSideEffects(); 6111 }; 6112 6113 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6114 /*HasNoSideEffects*/ true}; 6115 6116 for (auto *BB : L->getBlocks()) 6117 for (auto &I : *BB) { 6118 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6119 LP.HasNoAbnormalExits = false; 6120 if (HasSideEffects(&I)) 6121 LP.HasNoSideEffects = false; 6122 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6123 break; // We're already as pessimistic as we can get. 6124 } 6125 6126 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6127 assert(InsertPair.second && "We just checked!"); 6128 Itr = InsertPair.first; 6129 } 6130 6131 return Itr->second; 6132 } 6133 6134 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6135 if (!isSCEVable(V->getType())) 6136 return getUnknown(V); 6137 6138 if (Instruction *I = dyn_cast<Instruction>(V)) { 6139 // Don't attempt to analyze instructions in blocks that aren't 6140 // reachable. Such instructions don't matter, and they aren't required 6141 // to obey basic rules for definitions dominating uses which this 6142 // analysis depends on. 6143 if (!DT.isReachableFromEntry(I->getParent())) 6144 return getUnknown(UndefValue::get(V->getType())); 6145 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6146 return getConstant(CI); 6147 else if (isa<ConstantPointerNull>(V)) 6148 return getZero(V->getType()); 6149 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6150 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6151 else if (!isa<ConstantExpr>(V)) 6152 return getUnknown(V); 6153 6154 Operator *U = cast<Operator>(V); 6155 if (auto BO = MatchBinaryOp(U, DT)) { 6156 switch (BO->Opcode) { 6157 case Instruction::Add: { 6158 // The simple thing to do would be to just call getSCEV on both operands 6159 // and call getAddExpr with the result. However if we're looking at a 6160 // bunch of things all added together, this can be quite inefficient, 6161 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6162 // Instead, gather up all the operands and make a single getAddExpr call. 6163 // LLVM IR canonical form means we need only traverse the left operands. 6164 SmallVector<const SCEV *, 4> AddOps; 6165 do { 6166 if (BO->Op) { 6167 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6168 AddOps.push_back(OpSCEV); 6169 break; 6170 } 6171 6172 // If a NUW or NSW flag can be applied to the SCEV for this 6173 // addition, then compute the SCEV for this addition by itself 6174 // with a separate call to getAddExpr. We need to do that 6175 // instead of pushing the operands of the addition onto AddOps, 6176 // since the flags are only known to apply to this particular 6177 // addition - they may not apply to other additions that can be 6178 // formed with operands from AddOps. 6179 const SCEV *RHS = getSCEV(BO->RHS); 6180 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6181 if (Flags != SCEV::FlagAnyWrap) { 6182 const SCEV *LHS = getSCEV(BO->LHS); 6183 if (BO->Opcode == Instruction::Sub) 6184 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6185 else 6186 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6187 break; 6188 } 6189 } 6190 6191 if (BO->Opcode == Instruction::Sub) 6192 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6193 else 6194 AddOps.push_back(getSCEV(BO->RHS)); 6195 6196 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6197 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6198 NewBO->Opcode != Instruction::Sub)) { 6199 AddOps.push_back(getSCEV(BO->LHS)); 6200 break; 6201 } 6202 BO = NewBO; 6203 } while (true); 6204 6205 return getAddExpr(AddOps); 6206 } 6207 6208 case Instruction::Mul: { 6209 SmallVector<const SCEV *, 4> MulOps; 6210 do { 6211 if (BO->Op) { 6212 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6213 MulOps.push_back(OpSCEV); 6214 break; 6215 } 6216 6217 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6218 if (Flags != SCEV::FlagAnyWrap) { 6219 MulOps.push_back( 6220 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6221 break; 6222 } 6223 } 6224 6225 MulOps.push_back(getSCEV(BO->RHS)); 6226 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6227 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6228 MulOps.push_back(getSCEV(BO->LHS)); 6229 break; 6230 } 6231 BO = NewBO; 6232 } while (true); 6233 6234 return getMulExpr(MulOps); 6235 } 6236 case Instruction::UDiv: 6237 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6238 case Instruction::URem: 6239 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6240 case Instruction::Sub: { 6241 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6242 if (BO->Op) 6243 Flags = getNoWrapFlagsFromUB(BO->Op); 6244 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6245 } 6246 case Instruction::And: 6247 // For an expression like x&255 that merely masks off the high bits, 6248 // use zext(trunc(x)) as the SCEV expression. 6249 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6250 if (CI->isZero()) 6251 return getSCEV(BO->RHS); 6252 if (CI->isMinusOne()) 6253 return getSCEV(BO->LHS); 6254 const APInt &A = CI->getValue(); 6255 6256 // Instcombine's ShrinkDemandedConstant may strip bits out of 6257 // constants, obscuring what would otherwise be a low-bits mask. 6258 // Use computeKnownBits to compute what ShrinkDemandedConstant 6259 // knew about to reconstruct a low-bits mask value. 6260 unsigned LZ = A.countLeadingZeros(); 6261 unsigned TZ = A.countTrailingZeros(); 6262 unsigned BitWidth = A.getBitWidth(); 6263 KnownBits Known(BitWidth); 6264 computeKnownBits(BO->LHS, Known, getDataLayout(), 6265 0, &AC, nullptr, &DT); 6266 6267 APInt EffectiveMask = 6268 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6269 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6270 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6271 const SCEV *LHS = getSCEV(BO->LHS); 6272 const SCEV *ShiftedLHS = nullptr; 6273 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6274 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6275 // For an expression like (x * 8) & 8, simplify the multiply. 6276 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6277 unsigned GCD = std::min(MulZeros, TZ); 6278 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6279 SmallVector<const SCEV*, 4> MulOps; 6280 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6281 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6282 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6283 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6284 } 6285 } 6286 if (!ShiftedLHS) 6287 ShiftedLHS = getUDivExpr(LHS, MulCount); 6288 return getMulExpr( 6289 getZeroExtendExpr( 6290 getTruncateExpr(ShiftedLHS, 6291 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6292 BO->LHS->getType()), 6293 MulCount); 6294 } 6295 } 6296 break; 6297 6298 case Instruction::Or: 6299 // If the RHS of the Or is a constant, we may have something like: 6300 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6301 // optimizations will transparently handle this case. 6302 // 6303 // In order for this transformation to be safe, the LHS must be of the 6304 // form X*(2^n) and the Or constant must be less than 2^n. 6305 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6306 const SCEV *LHS = getSCEV(BO->LHS); 6307 const APInt &CIVal = CI->getValue(); 6308 if (GetMinTrailingZeros(LHS) >= 6309 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6310 // Build a plain add SCEV. 6311 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6312 // If the LHS of the add was an addrec and it has no-wrap flags, 6313 // transfer the no-wrap flags, since an or won't introduce a wrap. 6314 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6315 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6316 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6317 OldAR->getNoWrapFlags()); 6318 } 6319 return S; 6320 } 6321 } 6322 break; 6323 6324 case Instruction::Xor: 6325 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6326 // If the RHS of xor is -1, then this is a not operation. 6327 if (CI->isMinusOne()) 6328 return getNotSCEV(getSCEV(BO->LHS)); 6329 6330 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6331 // This is a variant of the check for xor with -1, and it handles 6332 // the case where instcombine has trimmed non-demanded bits out 6333 // of an xor with -1. 6334 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6335 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6336 if (LBO->getOpcode() == Instruction::And && 6337 LCI->getValue() == CI->getValue()) 6338 if (const SCEVZeroExtendExpr *Z = 6339 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6340 Type *UTy = BO->LHS->getType(); 6341 const SCEV *Z0 = Z->getOperand(); 6342 Type *Z0Ty = Z0->getType(); 6343 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6344 6345 // If C is a low-bits mask, the zero extend is serving to 6346 // mask off the high bits. Complement the operand and 6347 // re-apply the zext. 6348 if (CI->getValue().isMask(Z0TySize)) 6349 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6350 6351 // If C is a single bit, it may be in the sign-bit position 6352 // before the zero-extend. In this case, represent the xor 6353 // using an add, which is equivalent, and re-apply the zext. 6354 APInt Trunc = CI->getValue().trunc(Z0TySize); 6355 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6356 Trunc.isSignMask()) 6357 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6358 UTy); 6359 } 6360 } 6361 break; 6362 6363 case Instruction::Shl: 6364 // Turn shift left of a constant amount into a multiply. 6365 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6366 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6367 6368 // If the shift count is not less than the bitwidth, the result of 6369 // the shift is undefined. Don't try to analyze it, because the 6370 // resolution chosen here may differ from the resolution chosen in 6371 // other parts of the compiler. 6372 if (SA->getValue().uge(BitWidth)) 6373 break; 6374 6375 // It is currently not resolved how to interpret NSW for left 6376 // shift by BitWidth - 1, so we avoid applying flags in that 6377 // case. Remove this check (or this comment) once the situation 6378 // is resolved. See 6379 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6380 // and http://reviews.llvm.org/D8890 . 6381 auto Flags = SCEV::FlagAnyWrap; 6382 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6383 Flags = getNoWrapFlagsFromUB(BO->Op); 6384 6385 Constant *X = ConstantInt::get( 6386 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6387 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6388 } 6389 break; 6390 6391 case Instruction::AShr: { 6392 // AShr X, C, where C is a constant. 6393 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6394 if (!CI) 6395 break; 6396 6397 Type *OuterTy = BO->LHS->getType(); 6398 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6399 // If the shift count is not less than the bitwidth, the result of 6400 // the shift is undefined. Don't try to analyze it, because the 6401 // resolution chosen here may differ from the resolution chosen in 6402 // other parts of the compiler. 6403 if (CI->getValue().uge(BitWidth)) 6404 break; 6405 6406 if (CI->isZero()) 6407 return getSCEV(BO->LHS); // shift by zero --> noop 6408 6409 uint64_t AShrAmt = CI->getZExtValue(); 6410 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6411 6412 Operator *L = dyn_cast<Operator>(BO->LHS); 6413 if (L && L->getOpcode() == Instruction::Shl) { 6414 // X = Shl A, n 6415 // Y = AShr X, m 6416 // Both n and m are constant. 6417 6418 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6419 if (L->getOperand(1) == BO->RHS) 6420 // For a two-shift sext-inreg, i.e. n = m, 6421 // use sext(trunc(x)) as the SCEV expression. 6422 return getSignExtendExpr( 6423 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6424 6425 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6426 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6427 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6428 if (ShlAmt > AShrAmt) { 6429 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6430 // expression. We already checked that ShlAmt < BitWidth, so 6431 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6432 // ShlAmt - AShrAmt < Amt. 6433 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6434 ShlAmt - AShrAmt); 6435 return getSignExtendExpr( 6436 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6437 getConstant(Mul)), OuterTy); 6438 } 6439 } 6440 } 6441 break; 6442 } 6443 } 6444 } 6445 6446 switch (U->getOpcode()) { 6447 case Instruction::Trunc: 6448 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6449 6450 case Instruction::ZExt: 6451 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6452 6453 case Instruction::SExt: 6454 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6455 // The NSW flag of a subtract does not always survive the conversion to 6456 // A + (-1)*B. By pushing sign extension onto its operands we are much 6457 // more likely to preserve NSW and allow later AddRec optimisations. 6458 // 6459 // NOTE: This is effectively duplicating this logic from getSignExtend: 6460 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6461 // but by that point the NSW information has potentially been lost. 6462 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6463 Type *Ty = U->getType(); 6464 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6465 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6466 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6467 } 6468 } 6469 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6470 6471 case Instruction::BitCast: 6472 // BitCasts are no-op casts so we just eliminate the cast. 6473 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6474 return getSCEV(U->getOperand(0)); 6475 break; 6476 6477 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6478 // lead to pointer expressions which cannot safely be expanded to GEPs, 6479 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6480 // simplifying integer expressions. 6481 6482 case Instruction::GetElementPtr: 6483 return createNodeForGEP(cast<GEPOperator>(U)); 6484 6485 case Instruction::PHI: 6486 return createNodeForPHI(cast<PHINode>(U)); 6487 6488 case Instruction::Select: 6489 // U can also be a select constant expr, which let fall through. Since 6490 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6491 // constant expressions cannot have instructions as operands, we'd have 6492 // returned getUnknown for a select constant expressions anyway. 6493 if (isa<Instruction>(U)) 6494 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6495 U->getOperand(1), U->getOperand(2)); 6496 break; 6497 6498 case Instruction::Call: 6499 case Instruction::Invoke: 6500 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6501 return getSCEV(RV); 6502 break; 6503 } 6504 6505 return getUnknown(V); 6506 } 6507 6508 //===----------------------------------------------------------------------===// 6509 // Iteration Count Computation Code 6510 // 6511 6512 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6513 if (!ExitCount) 6514 return 0; 6515 6516 ConstantInt *ExitConst = ExitCount->getValue(); 6517 6518 // Guard against huge trip counts. 6519 if (ExitConst->getValue().getActiveBits() > 32) 6520 return 0; 6521 6522 // In case of integer overflow, this returns 0, which is correct. 6523 return ((unsigned)ExitConst->getZExtValue()) + 1; 6524 } 6525 6526 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6527 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6528 return getSmallConstantTripCount(L, ExitingBB); 6529 6530 // No trip count information for multiple exits. 6531 return 0; 6532 } 6533 6534 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6535 BasicBlock *ExitingBlock) { 6536 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6537 assert(L->isLoopExiting(ExitingBlock) && 6538 "Exiting block must actually branch out of the loop!"); 6539 const SCEVConstant *ExitCount = 6540 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6541 return getConstantTripCount(ExitCount); 6542 } 6543 6544 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6545 const auto *MaxExitCount = 6546 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6547 return getConstantTripCount(MaxExitCount); 6548 } 6549 6550 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6551 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6552 return getSmallConstantTripMultiple(L, ExitingBB); 6553 6554 // No trip multiple information for multiple exits. 6555 return 0; 6556 } 6557 6558 /// Returns the largest constant divisor of the trip count of this loop as a 6559 /// normal unsigned value, if possible. This means that the actual trip count is 6560 /// always a multiple of the returned value (don't forget the trip count could 6561 /// very well be zero as well!). 6562 /// 6563 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6564 /// multiple of a constant (which is also the case if the trip count is simply 6565 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6566 /// if the trip count is very large (>= 2^32). 6567 /// 6568 /// As explained in the comments for getSmallConstantTripCount, this assumes 6569 /// that control exits the loop via ExitingBlock. 6570 unsigned 6571 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6572 BasicBlock *ExitingBlock) { 6573 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6574 assert(L->isLoopExiting(ExitingBlock) && 6575 "Exiting block must actually branch out of the loop!"); 6576 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6577 if (ExitCount == getCouldNotCompute()) 6578 return 1; 6579 6580 // Get the trip count from the BE count by adding 1. 6581 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6582 6583 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6584 if (!TC) 6585 // Attempt to factor more general cases. Returns the greatest power of 6586 // two divisor. If overflow happens, the trip count expression is still 6587 // divisible by the greatest power of 2 divisor returned. 6588 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6589 6590 ConstantInt *Result = TC->getValue(); 6591 6592 // Guard against huge trip counts (this requires checking 6593 // for zero to handle the case where the trip count == -1 and the 6594 // addition wraps). 6595 if (!Result || Result->getValue().getActiveBits() > 32 || 6596 Result->getValue().getActiveBits() == 0) 6597 return 1; 6598 6599 return (unsigned)Result->getZExtValue(); 6600 } 6601 6602 /// Get the expression for the number of loop iterations for which this loop is 6603 /// guaranteed not to exit via ExitingBlock. Otherwise return 6604 /// SCEVCouldNotCompute. 6605 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6606 BasicBlock *ExitingBlock) { 6607 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6608 } 6609 6610 const SCEV * 6611 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6612 SCEVUnionPredicate &Preds) { 6613 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6614 } 6615 6616 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6617 return getBackedgeTakenInfo(L).getExact(L, this); 6618 } 6619 6620 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6621 /// known never to be less than the actual backedge taken count. 6622 const SCEV *ScalarEvolution::getConstantMaxBackedgeTakenCount(const Loop *L) { 6623 return getBackedgeTakenInfo(L).getMax(this); 6624 } 6625 6626 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6627 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6628 } 6629 6630 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6631 static void 6632 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6633 BasicBlock *Header = L->getHeader(); 6634 6635 // Push all Loop-header PHIs onto the Worklist stack. 6636 for (PHINode &PN : Header->phis()) 6637 Worklist.push_back(&PN); 6638 } 6639 6640 const ScalarEvolution::BackedgeTakenInfo & 6641 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6642 auto &BTI = getBackedgeTakenInfo(L); 6643 if (BTI.hasFullInfo()) 6644 return BTI; 6645 6646 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6647 6648 if (!Pair.second) 6649 return Pair.first->second; 6650 6651 BackedgeTakenInfo Result = 6652 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6653 6654 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6655 } 6656 6657 const ScalarEvolution::BackedgeTakenInfo & 6658 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6659 // Initially insert an invalid entry for this loop. If the insertion 6660 // succeeds, proceed to actually compute a backedge-taken count and 6661 // update the value. The temporary CouldNotCompute value tells SCEV 6662 // code elsewhere that it shouldn't attempt to request a new 6663 // backedge-taken count, which could result in infinite recursion. 6664 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6665 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6666 if (!Pair.second) 6667 return Pair.first->second; 6668 6669 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6670 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6671 // must be cleared in this scope. 6672 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6673 6674 // In product build, there are no usage of statistic. 6675 (void)NumTripCountsComputed; 6676 (void)NumTripCountsNotComputed; 6677 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6678 const SCEV *BEExact = Result.getExact(L, this); 6679 if (BEExact != getCouldNotCompute()) { 6680 assert(isLoopInvariant(BEExact, L) && 6681 isLoopInvariant(Result.getMax(this), L) && 6682 "Computed backedge-taken count isn't loop invariant for loop!"); 6683 ++NumTripCountsComputed; 6684 } 6685 else if (Result.getMax(this) == getCouldNotCompute() && 6686 isa<PHINode>(L->getHeader()->begin())) { 6687 // Only count loops that have phi nodes as not being computable. 6688 ++NumTripCountsNotComputed; 6689 } 6690 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6691 6692 // Now that we know more about the trip count for this loop, forget any 6693 // existing SCEV values for PHI nodes in this loop since they are only 6694 // conservative estimates made without the benefit of trip count 6695 // information. This is similar to the code in forgetLoop, except that 6696 // it handles SCEVUnknown PHI nodes specially. 6697 if (Result.hasAnyInfo()) { 6698 SmallVector<Instruction *, 16> Worklist; 6699 PushLoopPHIs(L, Worklist); 6700 6701 SmallPtrSet<Instruction *, 8> Discovered; 6702 while (!Worklist.empty()) { 6703 Instruction *I = Worklist.pop_back_val(); 6704 6705 ValueExprMapType::iterator It = 6706 ValueExprMap.find_as(static_cast<Value *>(I)); 6707 if (It != ValueExprMap.end()) { 6708 const SCEV *Old = It->second; 6709 6710 // SCEVUnknown for a PHI either means that it has an unrecognized 6711 // structure, or it's a PHI that's in the progress of being computed 6712 // by createNodeForPHI. In the former case, additional loop trip 6713 // count information isn't going to change anything. In the later 6714 // case, createNodeForPHI will perform the necessary updates on its 6715 // own when it gets to that point. 6716 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6717 eraseValueFromMap(It->first); 6718 forgetMemoizedResults(Old); 6719 } 6720 if (PHINode *PN = dyn_cast<PHINode>(I)) 6721 ConstantEvolutionLoopExitValue.erase(PN); 6722 } 6723 6724 // Since we don't need to invalidate anything for correctness and we're 6725 // only invalidating to make SCEV's results more precise, we get to stop 6726 // early to avoid invalidating too much. This is especially important in 6727 // cases like: 6728 // 6729 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6730 // loop0: 6731 // %pn0 = phi 6732 // ... 6733 // loop1: 6734 // %pn1 = phi 6735 // ... 6736 // 6737 // where both loop0 and loop1's backedge taken count uses the SCEV 6738 // expression for %v. If we don't have the early stop below then in cases 6739 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6740 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6741 // count for loop1, effectively nullifying SCEV's trip count cache. 6742 for (auto *U : I->users()) 6743 if (auto *I = dyn_cast<Instruction>(U)) { 6744 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6745 if (LoopForUser && L->contains(LoopForUser) && 6746 Discovered.insert(I).second) 6747 Worklist.push_back(I); 6748 } 6749 } 6750 } 6751 6752 // Re-lookup the insert position, since the call to 6753 // computeBackedgeTakenCount above could result in a 6754 // recusive call to getBackedgeTakenInfo (on a different 6755 // loop), which would invalidate the iterator computed 6756 // earlier. 6757 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6758 } 6759 6760 void ScalarEvolution::forgetAllLoops() { 6761 // This method is intended to forget all info about loops. It should 6762 // invalidate caches as if the following happened: 6763 // - The trip counts of all loops have changed arbitrarily 6764 // - Every llvm::Value has been updated in place to produce a different 6765 // result. 6766 BackedgeTakenCounts.clear(); 6767 PredicatedBackedgeTakenCounts.clear(); 6768 LoopPropertiesCache.clear(); 6769 ConstantEvolutionLoopExitValue.clear(); 6770 ValueExprMap.clear(); 6771 ValuesAtScopes.clear(); 6772 LoopDispositions.clear(); 6773 BlockDispositions.clear(); 6774 UnsignedRanges.clear(); 6775 SignedRanges.clear(); 6776 ExprValueMap.clear(); 6777 HasRecMap.clear(); 6778 MinTrailingZerosCache.clear(); 6779 PredicatedSCEVRewrites.clear(); 6780 } 6781 6782 void ScalarEvolution::forgetLoop(const Loop *L) { 6783 // Drop any stored trip count value. 6784 auto RemoveLoopFromBackedgeMap = 6785 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6786 auto BTCPos = Map.find(L); 6787 if (BTCPos != Map.end()) { 6788 BTCPos->second.clear(); 6789 Map.erase(BTCPos); 6790 } 6791 }; 6792 6793 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6794 SmallVector<Instruction *, 32> Worklist; 6795 SmallPtrSet<Instruction *, 16> Visited; 6796 6797 // Iterate over all the loops and sub-loops to drop SCEV information. 6798 while (!LoopWorklist.empty()) { 6799 auto *CurrL = LoopWorklist.pop_back_val(); 6800 6801 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6802 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6803 6804 // Drop information about predicated SCEV rewrites for this loop. 6805 for (auto I = PredicatedSCEVRewrites.begin(); 6806 I != PredicatedSCEVRewrites.end();) { 6807 std::pair<const SCEV *, const Loop *> Entry = I->first; 6808 if (Entry.second == CurrL) 6809 PredicatedSCEVRewrites.erase(I++); 6810 else 6811 ++I; 6812 } 6813 6814 auto LoopUsersItr = LoopUsers.find(CurrL); 6815 if (LoopUsersItr != LoopUsers.end()) { 6816 for (auto *S : LoopUsersItr->second) 6817 forgetMemoizedResults(S); 6818 LoopUsers.erase(LoopUsersItr); 6819 } 6820 6821 // Drop information about expressions based on loop-header PHIs. 6822 PushLoopPHIs(CurrL, Worklist); 6823 6824 while (!Worklist.empty()) { 6825 Instruction *I = Worklist.pop_back_val(); 6826 if (!Visited.insert(I).second) 6827 continue; 6828 6829 ValueExprMapType::iterator It = 6830 ValueExprMap.find_as(static_cast<Value *>(I)); 6831 if (It != ValueExprMap.end()) { 6832 eraseValueFromMap(It->first); 6833 forgetMemoizedResults(It->second); 6834 if (PHINode *PN = dyn_cast<PHINode>(I)) 6835 ConstantEvolutionLoopExitValue.erase(PN); 6836 } 6837 6838 PushDefUseChildren(I, Worklist); 6839 } 6840 6841 LoopPropertiesCache.erase(CurrL); 6842 // Forget all contained loops too, to avoid dangling entries in the 6843 // ValuesAtScopes map. 6844 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6845 } 6846 } 6847 6848 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6849 while (Loop *Parent = L->getParentLoop()) 6850 L = Parent; 6851 forgetLoop(L); 6852 } 6853 6854 void ScalarEvolution::forgetValue(Value *V) { 6855 Instruction *I = dyn_cast<Instruction>(V); 6856 if (!I) return; 6857 6858 // Drop information about expressions based on loop-header PHIs. 6859 SmallVector<Instruction *, 16> Worklist; 6860 Worklist.push_back(I); 6861 6862 SmallPtrSet<Instruction *, 8> Visited; 6863 while (!Worklist.empty()) { 6864 I = Worklist.pop_back_val(); 6865 if (!Visited.insert(I).second) 6866 continue; 6867 6868 ValueExprMapType::iterator It = 6869 ValueExprMap.find_as(static_cast<Value *>(I)); 6870 if (It != ValueExprMap.end()) { 6871 eraseValueFromMap(It->first); 6872 forgetMemoizedResults(It->second); 6873 if (PHINode *PN = dyn_cast<PHINode>(I)) 6874 ConstantEvolutionLoopExitValue.erase(PN); 6875 } 6876 6877 PushDefUseChildren(I, Worklist); 6878 } 6879 } 6880 6881 /// Get the exact loop backedge taken count considering all loop exits. A 6882 /// computable result can only be returned for loops with all exiting blocks 6883 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6884 /// is never skipped. This is a valid assumption as long as the loop exits via 6885 /// that test. For precise results, it is the caller's responsibility to specify 6886 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6887 const SCEV * 6888 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6889 SCEVUnionPredicate *Preds) const { 6890 // If any exits were not computable, the loop is not computable. 6891 if (!isComplete() || ExitNotTaken.empty()) 6892 return SE->getCouldNotCompute(); 6893 6894 const BasicBlock *Latch = L->getLoopLatch(); 6895 // All exiting blocks we have collected must dominate the only backedge. 6896 if (!Latch) 6897 return SE->getCouldNotCompute(); 6898 6899 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6900 // count is simply a minimum out of all these calculated exit counts. 6901 SmallVector<const SCEV *, 2> Ops; 6902 for (auto &ENT : ExitNotTaken) { 6903 const SCEV *BECount = ENT.ExactNotTaken; 6904 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6905 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6906 "We should only have known counts for exiting blocks that dominate " 6907 "latch!"); 6908 6909 Ops.push_back(BECount); 6910 6911 if (Preds && !ENT.hasAlwaysTruePredicate()) 6912 Preds->add(ENT.Predicate.get()); 6913 6914 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6915 "Predicate should be always true!"); 6916 } 6917 6918 return SE->getUMinFromMismatchedTypes(Ops); 6919 } 6920 6921 /// Get the exact not taken count for this loop exit. 6922 const SCEV * 6923 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6924 ScalarEvolution *SE) const { 6925 for (auto &ENT : ExitNotTaken) 6926 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6927 return ENT.ExactNotTaken; 6928 6929 return SE->getCouldNotCompute(); 6930 } 6931 6932 /// getMax - Get the max backedge taken count for the loop. 6933 const SCEV * 6934 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6935 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6936 return !ENT.hasAlwaysTruePredicate(); 6937 }; 6938 6939 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6940 return SE->getCouldNotCompute(); 6941 6942 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6943 "No point in having a non-constant max backedge taken count!"); 6944 return getMax(); 6945 } 6946 6947 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6948 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6949 return !ENT.hasAlwaysTruePredicate(); 6950 }; 6951 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6952 } 6953 6954 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6955 ScalarEvolution *SE) const { 6956 if (getMax() && getMax() != SE->getCouldNotCompute() && 6957 SE->hasOperand(getMax(), S)) 6958 return true; 6959 6960 for (auto &ENT : ExitNotTaken) 6961 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6962 SE->hasOperand(ENT.ExactNotTaken, S)) 6963 return true; 6964 6965 return false; 6966 } 6967 6968 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6969 : ExactNotTaken(E), MaxNotTaken(E) { 6970 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6971 isa<SCEVConstant>(MaxNotTaken)) && 6972 "No point in having a non-constant max backedge taken count!"); 6973 } 6974 6975 ScalarEvolution::ExitLimit::ExitLimit( 6976 const SCEV *E, const SCEV *M, bool MaxOrZero, 6977 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6978 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6979 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6980 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6981 "Exact is not allowed to be less precise than Max"); 6982 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6983 isa<SCEVConstant>(MaxNotTaken)) && 6984 "No point in having a non-constant max backedge taken count!"); 6985 for (auto *PredSet : PredSetList) 6986 for (auto *P : *PredSet) 6987 addPredicate(P); 6988 } 6989 6990 ScalarEvolution::ExitLimit::ExitLimit( 6991 const SCEV *E, const SCEV *M, bool MaxOrZero, 6992 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6993 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6994 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6995 isa<SCEVConstant>(MaxNotTaken)) && 6996 "No point in having a non-constant max backedge taken count!"); 6997 } 6998 6999 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7000 bool MaxOrZero) 7001 : ExitLimit(E, M, MaxOrZero, None) { 7002 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7003 isa<SCEVConstant>(MaxNotTaken)) && 7004 "No point in having a non-constant max backedge taken count!"); 7005 } 7006 7007 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7008 /// computable exit into a persistent ExitNotTakenInfo array. 7009 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7010 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7011 ExitCounts, 7012 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7013 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7014 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7015 7016 ExitNotTaken.reserve(ExitCounts.size()); 7017 std::transform( 7018 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7019 [&](const EdgeExitInfo &EEI) { 7020 BasicBlock *ExitBB = EEI.first; 7021 const ExitLimit &EL = EEI.second; 7022 if (EL.Predicates.empty()) 7023 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7024 7025 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7026 for (auto *Pred : EL.Predicates) 7027 Predicate->add(Pred); 7028 7029 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7030 }); 7031 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7032 "No point in having a non-constant max backedge taken count!"); 7033 } 7034 7035 /// Invalidate this result and free the ExitNotTakenInfo array. 7036 void ScalarEvolution::BackedgeTakenInfo::clear() { 7037 ExitNotTaken.clear(); 7038 } 7039 7040 /// Compute the number of times the backedge of the specified loop will execute. 7041 ScalarEvolution::BackedgeTakenInfo 7042 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7043 bool AllowPredicates) { 7044 SmallVector<BasicBlock *, 8> ExitingBlocks; 7045 L->getExitingBlocks(ExitingBlocks); 7046 7047 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7048 7049 SmallVector<EdgeExitInfo, 4> ExitCounts; 7050 bool CouldComputeBECount = true; 7051 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7052 const SCEV *MustExitMaxBECount = nullptr; 7053 const SCEV *MayExitMaxBECount = nullptr; 7054 bool MustExitMaxOrZero = false; 7055 7056 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7057 // and compute maxBECount. 7058 // Do a union of all the predicates here. 7059 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7060 BasicBlock *ExitBB = ExitingBlocks[i]; 7061 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7062 7063 assert((AllowPredicates || EL.Predicates.empty()) && 7064 "Predicated exit limit when predicates are not allowed!"); 7065 7066 // 1. For each exit that can be computed, add an entry to ExitCounts. 7067 // CouldComputeBECount is true only if all exits can be computed. 7068 if (EL.ExactNotTaken == getCouldNotCompute()) 7069 // We couldn't compute an exact value for this exit, so 7070 // we won't be able to compute an exact value for the loop. 7071 CouldComputeBECount = false; 7072 else 7073 ExitCounts.emplace_back(ExitBB, EL); 7074 7075 // 2. Derive the loop's MaxBECount from each exit's max number of 7076 // non-exiting iterations. Partition the loop exits into two kinds: 7077 // LoopMustExits and LoopMayExits. 7078 // 7079 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7080 // is a LoopMayExit. If any computable LoopMustExit is found, then 7081 // MaxBECount is the minimum EL.MaxNotTaken of computable 7082 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7083 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7084 // computable EL.MaxNotTaken. 7085 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7086 DT.dominates(ExitBB, Latch)) { 7087 if (!MustExitMaxBECount) { 7088 MustExitMaxBECount = EL.MaxNotTaken; 7089 MustExitMaxOrZero = EL.MaxOrZero; 7090 } else { 7091 MustExitMaxBECount = 7092 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7093 } 7094 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7095 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7096 MayExitMaxBECount = EL.MaxNotTaken; 7097 else { 7098 MayExitMaxBECount = 7099 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7100 } 7101 } 7102 } 7103 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7104 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7105 // The loop backedge will be taken the maximum or zero times if there's 7106 // a single exit that must be taken the maximum or zero times. 7107 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7108 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7109 MaxBECount, MaxOrZero); 7110 } 7111 7112 ScalarEvolution::ExitLimit 7113 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7114 bool AllowPredicates) { 7115 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7116 // If our exiting block does not dominate the latch, then its connection with 7117 // loop's exit limit may be far from trivial. 7118 const BasicBlock *Latch = L->getLoopLatch(); 7119 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7120 return getCouldNotCompute(); 7121 7122 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7123 Instruction *Term = ExitingBlock->getTerminator(); 7124 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7125 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7126 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7127 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7128 "It should have one successor in loop and one exit block!"); 7129 // Proceed to the next level to examine the exit condition expression. 7130 return computeExitLimitFromCond( 7131 L, BI->getCondition(), ExitIfTrue, 7132 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7133 } 7134 7135 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7136 // For switch, make sure that there is a single exit from the loop. 7137 BasicBlock *Exit = nullptr; 7138 for (auto *SBB : successors(ExitingBlock)) 7139 if (!L->contains(SBB)) { 7140 if (Exit) // Multiple exit successors. 7141 return getCouldNotCompute(); 7142 Exit = SBB; 7143 } 7144 assert(Exit && "Exiting block must have at least one exit"); 7145 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7146 /*ControlsExit=*/IsOnlyExit); 7147 } 7148 7149 return getCouldNotCompute(); 7150 } 7151 7152 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7153 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7154 bool ControlsExit, bool AllowPredicates) { 7155 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7156 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7157 ControlsExit, AllowPredicates); 7158 } 7159 7160 Optional<ScalarEvolution::ExitLimit> 7161 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7162 bool ExitIfTrue, bool ControlsExit, 7163 bool AllowPredicates) { 7164 (void)this->L; 7165 (void)this->ExitIfTrue; 7166 (void)this->AllowPredicates; 7167 7168 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7169 this->AllowPredicates == AllowPredicates && 7170 "Variance in assumed invariant key components!"); 7171 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7172 if (Itr == TripCountMap.end()) 7173 return None; 7174 return Itr->second; 7175 } 7176 7177 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7178 bool ExitIfTrue, 7179 bool ControlsExit, 7180 bool AllowPredicates, 7181 const ExitLimit &EL) { 7182 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7183 this->AllowPredicates == AllowPredicates && 7184 "Variance in assumed invariant key components!"); 7185 7186 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7187 assert(InsertResult.second && "Expected successful insertion!"); 7188 (void)InsertResult; 7189 (void)ExitIfTrue; 7190 } 7191 7192 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7193 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7194 bool ControlsExit, bool AllowPredicates) { 7195 7196 if (auto MaybeEL = 7197 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7198 return *MaybeEL; 7199 7200 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7201 ControlsExit, AllowPredicates); 7202 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7203 return EL; 7204 } 7205 7206 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7207 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7208 bool ControlsExit, bool AllowPredicates) { 7209 // Check if the controlling expression for this loop is an And or Or. 7210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7211 if (BO->getOpcode() == Instruction::And) { 7212 // Recurse on the operands of the and. 7213 bool EitherMayExit = !ExitIfTrue; 7214 ExitLimit EL0 = computeExitLimitFromCondCached( 7215 Cache, L, BO->getOperand(0), ExitIfTrue, 7216 ControlsExit && !EitherMayExit, AllowPredicates); 7217 ExitLimit EL1 = computeExitLimitFromCondCached( 7218 Cache, L, BO->getOperand(1), ExitIfTrue, 7219 ControlsExit && !EitherMayExit, AllowPredicates); 7220 const SCEV *BECount = getCouldNotCompute(); 7221 const SCEV *MaxBECount = getCouldNotCompute(); 7222 if (EitherMayExit) { 7223 // Both conditions must be true for the loop to continue executing. 7224 // Choose the less conservative count. 7225 if (EL0.ExactNotTaken == getCouldNotCompute() || 7226 EL1.ExactNotTaken == getCouldNotCompute()) 7227 BECount = getCouldNotCompute(); 7228 else 7229 BECount = 7230 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7231 if (EL0.MaxNotTaken == getCouldNotCompute()) 7232 MaxBECount = EL1.MaxNotTaken; 7233 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7234 MaxBECount = EL0.MaxNotTaken; 7235 else 7236 MaxBECount = 7237 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7238 } else { 7239 // Both conditions must be true at the same time for the loop to exit. 7240 // For now, be conservative. 7241 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7242 MaxBECount = EL0.MaxNotTaken; 7243 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7244 BECount = EL0.ExactNotTaken; 7245 } 7246 7247 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7248 // to be more aggressive when computing BECount than when computing 7249 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7250 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7251 // to not. 7252 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7253 !isa<SCEVCouldNotCompute>(BECount)) 7254 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7255 7256 return ExitLimit(BECount, MaxBECount, false, 7257 {&EL0.Predicates, &EL1.Predicates}); 7258 } 7259 if (BO->getOpcode() == Instruction::Or) { 7260 // Recurse on the operands of the or. 7261 bool EitherMayExit = ExitIfTrue; 7262 ExitLimit EL0 = computeExitLimitFromCondCached( 7263 Cache, L, BO->getOperand(0), ExitIfTrue, 7264 ControlsExit && !EitherMayExit, AllowPredicates); 7265 ExitLimit EL1 = computeExitLimitFromCondCached( 7266 Cache, L, BO->getOperand(1), ExitIfTrue, 7267 ControlsExit && !EitherMayExit, AllowPredicates); 7268 const SCEV *BECount = getCouldNotCompute(); 7269 const SCEV *MaxBECount = getCouldNotCompute(); 7270 if (EitherMayExit) { 7271 // Both conditions must be false for the loop to continue executing. 7272 // Choose the less conservative count. 7273 if (EL0.ExactNotTaken == getCouldNotCompute() || 7274 EL1.ExactNotTaken == getCouldNotCompute()) 7275 BECount = getCouldNotCompute(); 7276 else 7277 BECount = 7278 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7279 if (EL0.MaxNotTaken == getCouldNotCompute()) 7280 MaxBECount = EL1.MaxNotTaken; 7281 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7282 MaxBECount = EL0.MaxNotTaken; 7283 else 7284 MaxBECount = 7285 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7286 } else { 7287 // Both conditions must be false at the same time for the loop to exit. 7288 // For now, be conservative. 7289 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7290 MaxBECount = EL0.MaxNotTaken; 7291 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7292 BECount = EL0.ExactNotTaken; 7293 } 7294 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7295 // to be more aggressive when computing BECount than when computing 7296 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7297 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7298 // to not. 7299 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7300 !isa<SCEVCouldNotCompute>(BECount)) 7301 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7302 7303 return ExitLimit(BECount, MaxBECount, false, 7304 {&EL0.Predicates, &EL1.Predicates}); 7305 } 7306 } 7307 7308 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7309 // Proceed to the next level to examine the icmp. 7310 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7311 ExitLimit EL = 7312 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7313 if (EL.hasFullInfo() || !AllowPredicates) 7314 return EL; 7315 7316 // Try again, but use SCEV predicates this time. 7317 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7318 /*AllowPredicates=*/true); 7319 } 7320 7321 // Check for a constant condition. These are normally stripped out by 7322 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7323 // preserve the CFG and is temporarily leaving constant conditions 7324 // in place. 7325 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7326 if (ExitIfTrue == !CI->getZExtValue()) 7327 // The backedge is always taken. 7328 return getCouldNotCompute(); 7329 else 7330 // The backedge is never taken. 7331 return getZero(CI->getType()); 7332 } 7333 7334 // If it's not an integer or pointer comparison then compute it the hard way. 7335 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7336 } 7337 7338 ScalarEvolution::ExitLimit 7339 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7340 ICmpInst *ExitCond, 7341 bool ExitIfTrue, 7342 bool ControlsExit, 7343 bool AllowPredicates) { 7344 // If the condition was exit on true, convert the condition to exit on false 7345 ICmpInst::Predicate Pred; 7346 if (!ExitIfTrue) 7347 Pred = ExitCond->getPredicate(); 7348 else 7349 Pred = ExitCond->getInversePredicate(); 7350 const ICmpInst::Predicate OriginalPred = Pred; 7351 7352 // Handle common loops like: for (X = "string"; *X; ++X) 7353 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7354 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7355 ExitLimit ItCnt = 7356 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7357 if (ItCnt.hasAnyInfo()) 7358 return ItCnt; 7359 } 7360 7361 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7362 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7363 7364 // Try to evaluate any dependencies out of the loop. 7365 LHS = getSCEVAtScope(LHS, L); 7366 RHS = getSCEVAtScope(RHS, L); 7367 7368 // At this point, we would like to compute how many iterations of the 7369 // loop the predicate will return true for these inputs. 7370 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7371 // If there is a loop-invariant, force it into the RHS. 7372 std::swap(LHS, RHS); 7373 Pred = ICmpInst::getSwappedPredicate(Pred); 7374 } 7375 7376 // Simplify the operands before analyzing them. 7377 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7378 7379 // If we have a comparison of a chrec against a constant, try to use value 7380 // ranges to answer this query. 7381 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7382 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7383 if (AddRec->getLoop() == L) { 7384 // Form the constant range. 7385 ConstantRange CompRange = 7386 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7387 7388 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7389 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7390 } 7391 7392 switch (Pred) { 7393 case ICmpInst::ICMP_NE: { // while (X != Y) 7394 // Convert to: while (X-Y != 0) 7395 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7396 AllowPredicates); 7397 if (EL.hasAnyInfo()) return EL; 7398 break; 7399 } 7400 case ICmpInst::ICMP_EQ: { // while (X == Y) 7401 // Convert to: while (X-Y == 0) 7402 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7403 if (EL.hasAnyInfo()) return EL; 7404 break; 7405 } 7406 case ICmpInst::ICMP_SLT: 7407 case ICmpInst::ICMP_ULT: { // while (X < Y) 7408 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7409 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7410 AllowPredicates); 7411 if (EL.hasAnyInfo()) return EL; 7412 break; 7413 } 7414 case ICmpInst::ICMP_SGT: 7415 case ICmpInst::ICMP_UGT: { // while (X > Y) 7416 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7417 ExitLimit EL = 7418 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7419 AllowPredicates); 7420 if (EL.hasAnyInfo()) return EL; 7421 break; 7422 } 7423 default: 7424 break; 7425 } 7426 7427 auto *ExhaustiveCount = 7428 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7429 7430 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7431 return ExhaustiveCount; 7432 7433 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7434 ExitCond->getOperand(1), L, OriginalPred); 7435 } 7436 7437 ScalarEvolution::ExitLimit 7438 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7439 SwitchInst *Switch, 7440 BasicBlock *ExitingBlock, 7441 bool ControlsExit) { 7442 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7443 7444 // Give up if the exit is the default dest of a switch. 7445 if (Switch->getDefaultDest() == ExitingBlock) 7446 return getCouldNotCompute(); 7447 7448 assert(L->contains(Switch->getDefaultDest()) && 7449 "Default case must not exit the loop!"); 7450 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7451 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7452 7453 // while (X != Y) --> while (X-Y != 0) 7454 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7455 if (EL.hasAnyInfo()) 7456 return EL; 7457 7458 return getCouldNotCompute(); 7459 } 7460 7461 static ConstantInt * 7462 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7463 ScalarEvolution &SE) { 7464 const SCEV *InVal = SE.getConstant(C); 7465 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7466 assert(isa<SCEVConstant>(Val) && 7467 "Evaluation of SCEV at constant didn't fold correctly?"); 7468 return cast<SCEVConstant>(Val)->getValue(); 7469 } 7470 7471 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7472 /// compute the backedge execution count. 7473 ScalarEvolution::ExitLimit 7474 ScalarEvolution::computeLoadConstantCompareExitLimit( 7475 LoadInst *LI, 7476 Constant *RHS, 7477 const Loop *L, 7478 ICmpInst::Predicate predicate) { 7479 if (LI->isVolatile()) return getCouldNotCompute(); 7480 7481 // Check to see if the loaded pointer is a getelementptr of a global. 7482 // TODO: Use SCEV instead of manually grubbing with GEPs. 7483 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7484 if (!GEP) return getCouldNotCompute(); 7485 7486 // Make sure that it is really a constant global we are gepping, with an 7487 // initializer, and make sure the first IDX is really 0. 7488 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7489 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7490 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7491 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7492 return getCouldNotCompute(); 7493 7494 // Okay, we allow one non-constant index into the GEP instruction. 7495 Value *VarIdx = nullptr; 7496 std::vector<Constant*> Indexes; 7497 unsigned VarIdxNum = 0; 7498 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7499 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7500 Indexes.push_back(CI); 7501 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7502 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7503 VarIdx = GEP->getOperand(i); 7504 VarIdxNum = i-2; 7505 Indexes.push_back(nullptr); 7506 } 7507 7508 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7509 if (!VarIdx) 7510 return getCouldNotCompute(); 7511 7512 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7513 // Check to see if X is a loop variant variable value now. 7514 const SCEV *Idx = getSCEV(VarIdx); 7515 Idx = getSCEVAtScope(Idx, L); 7516 7517 // We can only recognize very limited forms of loop index expressions, in 7518 // particular, only affine AddRec's like {C1,+,C2}. 7519 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7520 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7521 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7522 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7523 return getCouldNotCompute(); 7524 7525 unsigned MaxSteps = MaxBruteForceIterations; 7526 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7527 ConstantInt *ItCst = ConstantInt::get( 7528 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7529 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7530 7531 // Form the GEP offset. 7532 Indexes[VarIdxNum] = Val; 7533 7534 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7535 Indexes); 7536 if (!Result) break; // Cannot compute! 7537 7538 // Evaluate the condition for this iteration. 7539 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7540 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7541 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7542 ++NumArrayLenItCounts; 7543 return getConstant(ItCst); // Found terminating iteration! 7544 } 7545 } 7546 return getCouldNotCompute(); 7547 } 7548 7549 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7550 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7551 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7552 if (!RHS) 7553 return getCouldNotCompute(); 7554 7555 const BasicBlock *Latch = L->getLoopLatch(); 7556 if (!Latch) 7557 return getCouldNotCompute(); 7558 7559 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7560 if (!Predecessor) 7561 return getCouldNotCompute(); 7562 7563 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7564 // Return LHS in OutLHS and shift_opt in OutOpCode. 7565 auto MatchPositiveShift = 7566 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7567 7568 using namespace PatternMatch; 7569 7570 ConstantInt *ShiftAmt; 7571 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7572 OutOpCode = Instruction::LShr; 7573 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7574 OutOpCode = Instruction::AShr; 7575 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7576 OutOpCode = Instruction::Shl; 7577 else 7578 return false; 7579 7580 return ShiftAmt->getValue().isStrictlyPositive(); 7581 }; 7582 7583 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7584 // 7585 // loop: 7586 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7587 // %iv.shifted = lshr i32 %iv, <positive constant> 7588 // 7589 // Return true on a successful match. Return the corresponding PHI node (%iv 7590 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7591 auto MatchShiftRecurrence = 7592 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7593 Optional<Instruction::BinaryOps> PostShiftOpCode; 7594 7595 { 7596 Instruction::BinaryOps OpC; 7597 Value *V; 7598 7599 // If we encounter a shift instruction, "peel off" the shift operation, 7600 // and remember that we did so. Later when we inspect %iv's backedge 7601 // value, we will make sure that the backedge value uses the same 7602 // operation. 7603 // 7604 // Note: the peeled shift operation does not have to be the same 7605 // instruction as the one feeding into the PHI's backedge value. We only 7606 // really care about it being the same *kind* of shift instruction -- 7607 // that's all that is required for our later inferences to hold. 7608 if (MatchPositiveShift(LHS, V, OpC)) { 7609 PostShiftOpCode = OpC; 7610 LHS = V; 7611 } 7612 } 7613 7614 PNOut = dyn_cast<PHINode>(LHS); 7615 if (!PNOut || PNOut->getParent() != L->getHeader()) 7616 return false; 7617 7618 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7619 Value *OpLHS; 7620 7621 return 7622 // The backedge value for the PHI node must be a shift by a positive 7623 // amount 7624 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7625 7626 // of the PHI node itself 7627 OpLHS == PNOut && 7628 7629 // and the kind of shift should be match the kind of shift we peeled 7630 // off, if any. 7631 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7632 }; 7633 7634 PHINode *PN; 7635 Instruction::BinaryOps OpCode; 7636 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7637 return getCouldNotCompute(); 7638 7639 const DataLayout &DL = getDataLayout(); 7640 7641 // The key rationale for this optimization is that for some kinds of shift 7642 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7643 // within a finite number of iterations. If the condition guarding the 7644 // backedge (in the sense that the backedge is taken if the condition is true) 7645 // is false for the value the shift recurrence stabilizes to, then we know 7646 // that the backedge is taken only a finite number of times. 7647 7648 ConstantInt *StableValue = nullptr; 7649 switch (OpCode) { 7650 default: 7651 llvm_unreachable("Impossible case!"); 7652 7653 case Instruction::AShr: { 7654 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7655 // bitwidth(K) iterations. 7656 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7657 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7658 Predecessor->getTerminator(), &DT); 7659 auto *Ty = cast<IntegerType>(RHS->getType()); 7660 if (Known.isNonNegative()) 7661 StableValue = ConstantInt::get(Ty, 0); 7662 else if (Known.isNegative()) 7663 StableValue = ConstantInt::get(Ty, -1, true); 7664 else 7665 return getCouldNotCompute(); 7666 7667 break; 7668 } 7669 case Instruction::LShr: 7670 case Instruction::Shl: 7671 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7672 // stabilize to 0 in at most bitwidth(K) iterations. 7673 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7674 break; 7675 } 7676 7677 auto *Result = 7678 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7679 assert(Result->getType()->isIntegerTy(1) && 7680 "Otherwise cannot be an operand to a branch instruction"); 7681 7682 if (Result->isZeroValue()) { 7683 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7684 const SCEV *UpperBound = 7685 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7686 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7687 } 7688 7689 return getCouldNotCompute(); 7690 } 7691 7692 /// Return true if we can constant fold an instruction of the specified type, 7693 /// assuming that all operands were constants. 7694 static bool CanConstantFold(const Instruction *I) { 7695 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7696 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7697 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7698 return true; 7699 7700 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7701 if (const Function *F = CI->getCalledFunction()) 7702 return canConstantFoldCallTo(CI, F); 7703 return false; 7704 } 7705 7706 /// Determine whether this instruction can constant evolve within this loop 7707 /// assuming its operands can all constant evolve. 7708 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7709 // An instruction outside of the loop can't be derived from a loop PHI. 7710 if (!L->contains(I)) return false; 7711 7712 if (isa<PHINode>(I)) { 7713 // We don't currently keep track of the control flow needed to evaluate 7714 // PHIs, so we cannot handle PHIs inside of loops. 7715 return L->getHeader() == I->getParent(); 7716 } 7717 7718 // If we won't be able to constant fold this expression even if the operands 7719 // are constants, bail early. 7720 return CanConstantFold(I); 7721 } 7722 7723 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7724 /// recursing through each instruction operand until reaching a loop header phi. 7725 static PHINode * 7726 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7727 DenseMap<Instruction *, PHINode *> &PHIMap, 7728 unsigned Depth) { 7729 if (Depth > MaxConstantEvolvingDepth) 7730 return nullptr; 7731 7732 // Otherwise, we can evaluate this instruction if all of its operands are 7733 // constant or derived from a PHI node themselves. 7734 PHINode *PHI = nullptr; 7735 for (Value *Op : UseInst->operands()) { 7736 if (isa<Constant>(Op)) continue; 7737 7738 Instruction *OpInst = dyn_cast<Instruction>(Op); 7739 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7740 7741 PHINode *P = dyn_cast<PHINode>(OpInst); 7742 if (!P) 7743 // If this operand is already visited, reuse the prior result. 7744 // We may have P != PHI if this is the deepest point at which the 7745 // inconsistent paths meet. 7746 P = PHIMap.lookup(OpInst); 7747 if (!P) { 7748 // Recurse and memoize the results, whether a phi is found or not. 7749 // This recursive call invalidates pointers into PHIMap. 7750 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7751 PHIMap[OpInst] = P; 7752 } 7753 if (!P) 7754 return nullptr; // Not evolving from PHI 7755 if (PHI && PHI != P) 7756 return nullptr; // Evolving from multiple different PHIs. 7757 PHI = P; 7758 } 7759 // This is a expression evolving from a constant PHI! 7760 return PHI; 7761 } 7762 7763 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7764 /// in the loop that V is derived from. We allow arbitrary operations along the 7765 /// way, but the operands of an operation must either be constants or a value 7766 /// derived from a constant PHI. If this expression does not fit with these 7767 /// constraints, return null. 7768 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7769 Instruction *I = dyn_cast<Instruction>(V); 7770 if (!I || !canConstantEvolve(I, L)) return nullptr; 7771 7772 if (PHINode *PN = dyn_cast<PHINode>(I)) 7773 return PN; 7774 7775 // Record non-constant instructions contained by the loop. 7776 DenseMap<Instruction *, PHINode *> PHIMap; 7777 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7778 } 7779 7780 /// EvaluateExpression - Given an expression that passes the 7781 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7782 /// in the loop has the value PHIVal. If we can't fold this expression for some 7783 /// reason, return null. 7784 static Constant *EvaluateExpression(Value *V, const Loop *L, 7785 DenseMap<Instruction *, Constant *> &Vals, 7786 const DataLayout &DL, 7787 const TargetLibraryInfo *TLI) { 7788 // Convenient constant check, but redundant for recursive calls. 7789 if (Constant *C = dyn_cast<Constant>(V)) return C; 7790 Instruction *I = dyn_cast<Instruction>(V); 7791 if (!I) return nullptr; 7792 7793 if (Constant *C = Vals.lookup(I)) return C; 7794 7795 // An instruction inside the loop depends on a value outside the loop that we 7796 // weren't given a mapping for, or a value such as a call inside the loop. 7797 if (!canConstantEvolve(I, L)) return nullptr; 7798 7799 // An unmapped PHI can be due to a branch or another loop inside this loop, 7800 // or due to this not being the initial iteration through a loop where we 7801 // couldn't compute the evolution of this particular PHI last time. 7802 if (isa<PHINode>(I)) return nullptr; 7803 7804 std::vector<Constant*> Operands(I->getNumOperands()); 7805 7806 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7807 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7808 if (!Operand) { 7809 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7810 if (!Operands[i]) return nullptr; 7811 continue; 7812 } 7813 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7814 Vals[Operand] = C; 7815 if (!C) return nullptr; 7816 Operands[i] = C; 7817 } 7818 7819 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7820 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7821 Operands[1], DL, TLI); 7822 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7823 if (!LI->isVolatile()) 7824 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7825 } 7826 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7827 } 7828 7829 7830 // If every incoming value to PN except the one for BB is a specific Constant, 7831 // return that, else return nullptr. 7832 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7833 Constant *IncomingVal = nullptr; 7834 7835 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7836 if (PN->getIncomingBlock(i) == BB) 7837 continue; 7838 7839 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7840 if (!CurrentVal) 7841 return nullptr; 7842 7843 if (IncomingVal != CurrentVal) { 7844 if (IncomingVal) 7845 return nullptr; 7846 IncomingVal = CurrentVal; 7847 } 7848 } 7849 7850 return IncomingVal; 7851 } 7852 7853 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7854 /// in the header of its containing loop, we know the loop executes a 7855 /// constant number of times, and the PHI node is just a recurrence 7856 /// involving constants, fold it. 7857 Constant * 7858 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7859 const APInt &BEs, 7860 const Loop *L) { 7861 auto I = ConstantEvolutionLoopExitValue.find(PN); 7862 if (I != ConstantEvolutionLoopExitValue.end()) 7863 return I->second; 7864 7865 if (BEs.ugt(MaxBruteForceIterations)) 7866 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7867 7868 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7869 7870 DenseMap<Instruction *, Constant *> CurrentIterVals; 7871 BasicBlock *Header = L->getHeader(); 7872 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7873 7874 BasicBlock *Latch = L->getLoopLatch(); 7875 if (!Latch) 7876 return nullptr; 7877 7878 for (PHINode &PHI : Header->phis()) { 7879 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7880 CurrentIterVals[&PHI] = StartCST; 7881 } 7882 if (!CurrentIterVals.count(PN)) 7883 return RetVal = nullptr; 7884 7885 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7886 7887 // Execute the loop symbolically to determine the exit value. 7888 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7889 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7890 7891 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7892 unsigned IterationNum = 0; 7893 const DataLayout &DL = getDataLayout(); 7894 for (; ; ++IterationNum) { 7895 if (IterationNum == NumIterations) 7896 return RetVal = CurrentIterVals[PN]; // Got exit value! 7897 7898 // Compute the value of the PHIs for the next iteration. 7899 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7900 DenseMap<Instruction *, Constant *> NextIterVals; 7901 Constant *NextPHI = 7902 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7903 if (!NextPHI) 7904 return nullptr; // Couldn't evaluate! 7905 NextIterVals[PN] = NextPHI; 7906 7907 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7908 7909 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7910 // cease to be able to evaluate one of them or if they stop evolving, 7911 // because that doesn't necessarily prevent us from computing PN. 7912 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7913 for (const auto &I : CurrentIterVals) { 7914 PHINode *PHI = dyn_cast<PHINode>(I.first); 7915 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7916 PHIsToCompute.emplace_back(PHI, I.second); 7917 } 7918 // We use two distinct loops because EvaluateExpression may invalidate any 7919 // iterators into CurrentIterVals. 7920 for (const auto &I : PHIsToCompute) { 7921 PHINode *PHI = I.first; 7922 Constant *&NextPHI = NextIterVals[PHI]; 7923 if (!NextPHI) { // Not already computed. 7924 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7925 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7926 } 7927 if (NextPHI != I.second) 7928 StoppedEvolving = false; 7929 } 7930 7931 // If all entries in CurrentIterVals == NextIterVals then we can stop 7932 // iterating, the loop can't continue to change. 7933 if (StoppedEvolving) 7934 return RetVal = CurrentIterVals[PN]; 7935 7936 CurrentIterVals.swap(NextIterVals); 7937 } 7938 } 7939 7940 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7941 Value *Cond, 7942 bool ExitWhen) { 7943 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7944 if (!PN) return getCouldNotCompute(); 7945 7946 // If the loop is canonicalized, the PHI will have exactly two entries. 7947 // That's the only form we support here. 7948 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7949 7950 DenseMap<Instruction *, Constant *> CurrentIterVals; 7951 BasicBlock *Header = L->getHeader(); 7952 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7953 7954 BasicBlock *Latch = L->getLoopLatch(); 7955 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7956 7957 for (PHINode &PHI : Header->phis()) { 7958 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7959 CurrentIterVals[&PHI] = StartCST; 7960 } 7961 if (!CurrentIterVals.count(PN)) 7962 return getCouldNotCompute(); 7963 7964 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7965 // the loop symbolically to determine when the condition gets a value of 7966 // "ExitWhen". 7967 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7968 const DataLayout &DL = getDataLayout(); 7969 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7970 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7971 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7972 7973 // Couldn't symbolically evaluate. 7974 if (!CondVal) return getCouldNotCompute(); 7975 7976 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7977 ++NumBruteForceTripCountsComputed; 7978 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7979 } 7980 7981 // Update all the PHI nodes for the next iteration. 7982 DenseMap<Instruction *, Constant *> NextIterVals; 7983 7984 // Create a list of which PHIs we need to compute. We want to do this before 7985 // calling EvaluateExpression on them because that may invalidate iterators 7986 // into CurrentIterVals. 7987 SmallVector<PHINode *, 8> PHIsToCompute; 7988 for (const auto &I : CurrentIterVals) { 7989 PHINode *PHI = dyn_cast<PHINode>(I.first); 7990 if (!PHI || PHI->getParent() != Header) continue; 7991 PHIsToCompute.push_back(PHI); 7992 } 7993 for (PHINode *PHI : PHIsToCompute) { 7994 Constant *&NextPHI = NextIterVals[PHI]; 7995 if (NextPHI) continue; // Already computed! 7996 7997 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7998 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7999 } 8000 CurrentIterVals.swap(NextIterVals); 8001 } 8002 8003 // Too many iterations were needed to evaluate. 8004 return getCouldNotCompute(); 8005 } 8006 8007 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8008 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8009 ValuesAtScopes[V]; 8010 // Check to see if we've folded this expression at this loop before. 8011 for (auto &LS : Values) 8012 if (LS.first == L) 8013 return LS.second ? LS.second : V; 8014 8015 Values.emplace_back(L, nullptr); 8016 8017 // Otherwise compute it. 8018 const SCEV *C = computeSCEVAtScope(V, L); 8019 for (auto &LS : reverse(ValuesAtScopes[V])) 8020 if (LS.first == L) { 8021 LS.second = C; 8022 break; 8023 } 8024 return C; 8025 } 8026 8027 /// This builds up a Constant using the ConstantExpr interface. That way, we 8028 /// will return Constants for objects which aren't represented by a 8029 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8030 /// Returns NULL if the SCEV isn't representable as a Constant. 8031 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8032 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8033 case scCouldNotCompute: 8034 case scAddRecExpr: 8035 break; 8036 case scConstant: 8037 return cast<SCEVConstant>(V)->getValue(); 8038 case scUnknown: 8039 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8040 case scSignExtend: { 8041 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8042 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8043 return ConstantExpr::getSExt(CastOp, SS->getType()); 8044 break; 8045 } 8046 case scZeroExtend: { 8047 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8048 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8049 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8050 break; 8051 } 8052 case scTruncate: { 8053 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8054 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8055 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8056 break; 8057 } 8058 case scAddExpr: { 8059 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8060 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8061 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8062 unsigned AS = PTy->getAddressSpace(); 8063 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8064 C = ConstantExpr::getBitCast(C, DestPtrTy); 8065 } 8066 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8067 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8068 if (!C2) return nullptr; 8069 8070 // First pointer! 8071 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8072 unsigned AS = C2->getType()->getPointerAddressSpace(); 8073 std::swap(C, C2); 8074 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8075 // The offsets have been converted to bytes. We can add bytes to an 8076 // i8* by GEP with the byte count in the first index. 8077 C = ConstantExpr::getBitCast(C, DestPtrTy); 8078 } 8079 8080 // Don't bother trying to sum two pointers. We probably can't 8081 // statically compute a load that results from it anyway. 8082 if (C2->getType()->isPointerTy()) 8083 return nullptr; 8084 8085 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8086 if (PTy->getElementType()->isStructTy()) 8087 C2 = ConstantExpr::getIntegerCast( 8088 C2, Type::getInt32Ty(C->getContext()), true); 8089 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8090 } else 8091 C = ConstantExpr::getAdd(C, C2); 8092 } 8093 return C; 8094 } 8095 break; 8096 } 8097 case scMulExpr: { 8098 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8099 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8100 // Don't bother with pointers at all. 8101 if (C->getType()->isPointerTy()) return nullptr; 8102 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8103 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8104 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8105 C = ConstantExpr::getMul(C, C2); 8106 } 8107 return C; 8108 } 8109 break; 8110 } 8111 case scUDivExpr: { 8112 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8113 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8114 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8115 if (LHS->getType() == RHS->getType()) 8116 return ConstantExpr::getUDiv(LHS, RHS); 8117 break; 8118 } 8119 case scSMaxExpr: 8120 case scUMaxExpr: 8121 case scSMinExpr: 8122 case scUMinExpr: 8123 break; // TODO: smax, umax, smin, umax. 8124 } 8125 return nullptr; 8126 } 8127 8128 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8129 if (isa<SCEVConstant>(V)) return V; 8130 8131 // If this instruction is evolved from a constant-evolving PHI, compute the 8132 // exit value from the loop without using SCEVs. 8133 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8134 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8135 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8136 const Loop *LI = this->LI[I->getParent()]; 8137 // Looking for loop exit value. 8138 if (LI && LI->getParentLoop() == L && 8139 PN->getParent() == LI->getHeader()) { 8140 // Okay, there is no closed form solution for the PHI node. Check 8141 // to see if the loop that contains it has a known backedge-taken 8142 // count. If so, we may be able to force computation of the exit 8143 // value. 8144 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8145 // This trivial case can show up in some degenerate cases where 8146 // the incoming IR has not yet been fully simplified. 8147 if (BackedgeTakenCount->isZero()) { 8148 Value *InitValue = nullptr; 8149 bool MultipleInitValues = false; 8150 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8151 if (!LI->contains(PN->getIncomingBlock(i))) { 8152 if (!InitValue) 8153 InitValue = PN->getIncomingValue(i); 8154 else if (InitValue != PN->getIncomingValue(i)) { 8155 MultipleInitValues = true; 8156 break; 8157 } 8158 } 8159 } 8160 if (!MultipleInitValues && InitValue) 8161 return getSCEV(InitValue); 8162 } 8163 // Do we have a loop invariant value flowing around the backedge 8164 // for a loop which must execute the backedge? 8165 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8166 isKnownPositive(BackedgeTakenCount) && 8167 PN->getNumIncomingValues() == 2) { 8168 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8169 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8170 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8171 return OnBackedge; 8172 } 8173 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8174 // Okay, we know how many times the containing loop executes. If 8175 // this is a constant evolving PHI node, get the final value at 8176 // the specified iteration number. 8177 Constant *RV = 8178 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8179 if (RV) return getSCEV(RV); 8180 } 8181 } 8182 8183 // If there is a single-input Phi, evaluate it at our scope. If we can 8184 // prove that this replacement does not break LCSSA form, use new value. 8185 if (PN->getNumOperands() == 1) { 8186 const SCEV *Input = getSCEV(PN->getOperand(0)); 8187 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8188 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8189 // for the simplest case just support constants. 8190 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8191 } 8192 } 8193 8194 // Okay, this is an expression that we cannot symbolically evaluate 8195 // into a SCEV. Check to see if it's possible to symbolically evaluate 8196 // the arguments into constants, and if so, try to constant propagate the 8197 // result. This is particularly useful for computing loop exit values. 8198 if (CanConstantFold(I)) { 8199 SmallVector<Constant *, 4> Operands; 8200 bool MadeImprovement = false; 8201 for (Value *Op : I->operands()) { 8202 if (Constant *C = dyn_cast<Constant>(Op)) { 8203 Operands.push_back(C); 8204 continue; 8205 } 8206 8207 // If any of the operands is non-constant and if they are 8208 // non-integer and non-pointer, don't even try to analyze them 8209 // with scev techniques. 8210 if (!isSCEVable(Op->getType())) 8211 return V; 8212 8213 const SCEV *OrigV = getSCEV(Op); 8214 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8215 MadeImprovement |= OrigV != OpV; 8216 8217 Constant *C = BuildConstantFromSCEV(OpV); 8218 if (!C) return V; 8219 if (C->getType() != Op->getType()) 8220 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8221 Op->getType(), 8222 false), 8223 C, Op->getType()); 8224 Operands.push_back(C); 8225 } 8226 8227 // Check to see if getSCEVAtScope actually made an improvement. 8228 if (MadeImprovement) { 8229 Constant *C = nullptr; 8230 const DataLayout &DL = getDataLayout(); 8231 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8232 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8233 Operands[1], DL, &TLI); 8234 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8235 if (!LI->isVolatile()) 8236 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8237 } else 8238 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8239 if (!C) return V; 8240 return getSCEV(C); 8241 } 8242 } 8243 } 8244 8245 // This is some other type of SCEVUnknown, just return it. 8246 return V; 8247 } 8248 8249 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8250 // Avoid performing the look-up in the common case where the specified 8251 // expression has no loop-variant portions. 8252 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8253 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8254 if (OpAtScope != Comm->getOperand(i)) { 8255 // Okay, at least one of these operands is loop variant but might be 8256 // foldable. Build a new instance of the folded commutative expression. 8257 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8258 Comm->op_begin()+i); 8259 NewOps.push_back(OpAtScope); 8260 8261 for (++i; i != e; ++i) { 8262 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8263 NewOps.push_back(OpAtScope); 8264 } 8265 if (isa<SCEVAddExpr>(Comm)) 8266 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8267 if (isa<SCEVMulExpr>(Comm)) 8268 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8269 if (isa<SCEVMinMaxExpr>(Comm)) 8270 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8271 llvm_unreachable("Unknown commutative SCEV type!"); 8272 } 8273 } 8274 // If we got here, all operands are loop invariant. 8275 return Comm; 8276 } 8277 8278 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8279 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8280 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8281 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8282 return Div; // must be loop invariant 8283 return getUDivExpr(LHS, RHS); 8284 } 8285 8286 // If this is a loop recurrence for a loop that does not contain L, then we 8287 // are dealing with the final value computed by the loop. 8288 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8289 // First, attempt to evaluate each operand. 8290 // Avoid performing the look-up in the common case where the specified 8291 // expression has no loop-variant portions. 8292 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8293 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8294 if (OpAtScope == AddRec->getOperand(i)) 8295 continue; 8296 8297 // Okay, at least one of these operands is loop variant but might be 8298 // foldable. Build a new instance of the folded commutative expression. 8299 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8300 AddRec->op_begin()+i); 8301 NewOps.push_back(OpAtScope); 8302 for (++i; i != e; ++i) 8303 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8304 8305 const SCEV *FoldedRec = 8306 getAddRecExpr(NewOps, AddRec->getLoop(), 8307 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8308 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8309 // The addrec may be folded to a nonrecurrence, for example, if the 8310 // induction variable is multiplied by zero after constant folding. Go 8311 // ahead and return the folded value. 8312 if (!AddRec) 8313 return FoldedRec; 8314 break; 8315 } 8316 8317 // If the scope is outside the addrec's loop, evaluate it by using the 8318 // loop exit value of the addrec. 8319 if (!AddRec->getLoop()->contains(L)) { 8320 // To evaluate this recurrence, we need to know how many times the AddRec 8321 // loop iterates. Compute this now. 8322 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8323 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8324 8325 // Then, evaluate the AddRec. 8326 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8327 } 8328 8329 return AddRec; 8330 } 8331 8332 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8333 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8334 if (Op == Cast->getOperand()) 8335 return Cast; // must be loop invariant 8336 return getZeroExtendExpr(Op, Cast->getType()); 8337 } 8338 8339 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8340 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8341 if (Op == Cast->getOperand()) 8342 return Cast; // must be loop invariant 8343 return getSignExtendExpr(Op, Cast->getType()); 8344 } 8345 8346 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8347 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8348 if (Op == Cast->getOperand()) 8349 return Cast; // must be loop invariant 8350 return getTruncateExpr(Op, Cast->getType()); 8351 } 8352 8353 llvm_unreachable("Unknown SCEV type!"); 8354 } 8355 8356 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8357 return getSCEVAtScope(getSCEV(V), L); 8358 } 8359 8360 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8361 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8362 return stripInjectiveFunctions(ZExt->getOperand()); 8363 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8364 return stripInjectiveFunctions(SExt->getOperand()); 8365 return S; 8366 } 8367 8368 /// Finds the minimum unsigned root of the following equation: 8369 /// 8370 /// A * X = B (mod N) 8371 /// 8372 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8373 /// A and B isn't important. 8374 /// 8375 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8376 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8377 ScalarEvolution &SE) { 8378 uint32_t BW = A.getBitWidth(); 8379 assert(BW == SE.getTypeSizeInBits(B->getType())); 8380 assert(A != 0 && "A must be non-zero."); 8381 8382 // 1. D = gcd(A, N) 8383 // 8384 // The gcd of A and N may have only one prime factor: 2. The number of 8385 // trailing zeros in A is its multiplicity 8386 uint32_t Mult2 = A.countTrailingZeros(); 8387 // D = 2^Mult2 8388 8389 // 2. Check if B is divisible by D. 8390 // 8391 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8392 // is not less than multiplicity of this prime factor for D. 8393 if (SE.GetMinTrailingZeros(B) < Mult2) 8394 return SE.getCouldNotCompute(); 8395 8396 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8397 // modulo (N / D). 8398 // 8399 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8400 // (N / D) in general. The inverse itself always fits into BW bits, though, 8401 // so we immediately truncate it. 8402 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8403 APInt Mod(BW + 1, 0); 8404 Mod.setBit(BW - Mult2); // Mod = N / D 8405 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8406 8407 // 4. Compute the minimum unsigned root of the equation: 8408 // I * (B / D) mod (N / D) 8409 // To simplify the computation, we factor out the divide by D: 8410 // (I * B mod N) / D 8411 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8412 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8413 } 8414 8415 /// For a given quadratic addrec, generate coefficients of the corresponding 8416 /// quadratic equation, multiplied by a common value to ensure that they are 8417 /// integers. 8418 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8419 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8420 /// were multiplied by, and BitWidth is the bit width of the original addrec 8421 /// coefficients. 8422 /// This function returns None if the addrec coefficients are not compile- 8423 /// time constants. 8424 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8425 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8426 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8427 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8428 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8429 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8430 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8431 << *AddRec << '\n'); 8432 8433 // We currently can only solve this if the coefficients are constants. 8434 if (!LC || !MC || !NC) { 8435 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8436 return None; 8437 } 8438 8439 APInt L = LC->getAPInt(); 8440 APInt M = MC->getAPInt(); 8441 APInt N = NC->getAPInt(); 8442 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8443 8444 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8445 unsigned NewWidth = BitWidth + 1; 8446 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8447 << BitWidth << '\n'); 8448 // The sign-extension (as opposed to a zero-extension) here matches the 8449 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8450 N = N.sext(NewWidth); 8451 M = M.sext(NewWidth); 8452 L = L.sext(NewWidth); 8453 8454 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8455 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8456 // L+M, L+2M+N, L+3M+3N, ... 8457 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8458 // 8459 // The equation Acc = 0 is then 8460 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8461 // In a quadratic form it becomes: 8462 // N n^2 + (2M-N) n + 2L = 0. 8463 8464 APInt A = N; 8465 APInt B = 2 * M - A; 8466 APInt C = 2 * L; 8467 APInt T = APInt(NewWidth, 2); 8468 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8469 << "x + " << C << ", coeff bw: " << NewWidth 8470 << ", multiplied by " << T << '\n'); 8471 return std::make_tuple(A, B, C, T, BitWidth); 8472 } 8473 8474 /// Helper function to compare optional APInts: 8475 /// (a) if X and Y both exist, return min(X, Y), 8476 /// (b) if neither X nor Y exist, return None, 8477 /// (c) if exactly one of X and Y exists, return that value. 8478 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8479 if (X.hasValue() && Y.hasValue()) { 8480 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8481 APInt XW = X->sextOrSelf(W); 8482 APInt YW = Y->sextOrSelf(W); 8483 return XW.slt(YW) ? *X : *Y; 8484 } 8485 if (!X.hasValue() && !Y.hasValue()) 8486 return None; 8487 return X.hasValue() ? *X : *Y; 8488 } 8489 8490 /// Helper function to truncate an optional APInt to a given BitWidth. 8491 /// When solving addrec-related equations, it is preferable to return a value 8492 /// that has the same bit width as the original addrec's coefficients. If the 8493 /// solution fits in the original bit width, truncate it (except for i1). 8494 /// Returning a value of a different bit width may inhibit some optimizations. 8495 /// 8496 /// In general, a solution to a quadratic equation generated from an addrec 8497 /// may require BW+1 bits, where BW is the bit width of the addrec's 8498 /// coefficients. The reason is that the coefficients of the quadratic 8499 /// equation are BW+1 bits wide (to avoid truncation when converting from 8500 /// the addrec to the equation). 8501 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8502 if (!X.hasValue()) 8503 return None; 8504 unsigned W = X->getBitWidth(); 8505 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8506 return X->trunc(BitWidth); 8507 return X; 8508 } 8509 8510 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8511 /// iterations. The values L, M, N are assumed to be signed, and they 8512 /// should all have the same bit widths. 8513 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8514 /// where BW is the bit width of the addrec's coefficients. 8515 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8516 /// returned as such, otherwise the bit width of the returned value may 8517 /// be greater than BW. 8518 /// 8519 /// This function returns None if 8520 /// (a) the addrec coefficients are not constant, or 8521 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8522 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8523 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8524 static Optional<APInt> 8525 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8526 APInt A, B, C, M; 8527 unsigned BitWidth; 8528 auto T = GetQuadraticEquation(AddRec); 8529 if (!T.hasValue()) 8530 return None; 8531 8532 std::tie(A, B, C, M, BitWidth) = *T; 8533 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8534 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8535 if (!X.hasValue()) 8536 return None; 8537 8538 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8539 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8540 if (!V->isZero()) 8541 return None; 8542 8543 return TruncIfPossible(X, BitWidth); 8544 } 8545 8546 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8547 /// iterations. The values M, N are assumed to be signed, and they 8548 /// should all have the same bit widths. 8549 /// Find the least n such that c(n) does not belong to the given range, 8550 /// while c(n-1) does. 8551 /// 8552 /// This function returns None if 8553 /// (a) the addrec coefficients are not constant, or 8554 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8555 /// bounds of the range. 8556 static Optional<APInt> 8557 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8558 const ConstantRange &Range, ScalarEvolution &SE) { 8559 assert(AddRec->getOperand(0)->isZero() && 8560 "Starting value of addrec should be 0"); 8561 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8562 << Range << ", addrec " << *AddRec << '\n'); 8563 // This case is handled in getNumIterationsInRange. Here we can assume that 8564 // we start in the range. 8565 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8566 "Addrec's initial value should be in range"); 8567 8568 APInt A, B, C, M; 8569 unsigned BitWidth; 8570 auto T = GetQuadraticEquation(AddRec); 8571 if (!T.hasValue()) 8572 return None; 8573 8574 // Be careful about the return value: there can be two reasons for not 8575 // returning an actual number. First, if no solutions to the equations 8576 // were found, and second, if the solutions don't leave the given range. 8577 // The first case means that the actual solution is "unknown", the second 8578 // means that it's known, but not valid. If the solution is unknown, we 8579 // cannot make any conclusions. 8580 // Return a pair: the optional solution and a flag indicating if the 8581 // solution was found. 8582 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8583 // Solve for signed overflow and unsigned overflow, pick the lower 8584 // solution. 8585 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8586 << Bound << " (before multiplying by " << M << ")\n"); 8587 Bound *= M; // The quadratic equation multiplier. 8588 8589 Optional<APInt> SO = None; 8590 if (BitWidth > 1) { 8591 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8592 "signed overflow\n"); 8593 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8594 } 8595 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8596 "unsigned overflow\n"); 8597 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8598 BitWidth+1); 8599 8600 auto LeavesRange = [&] (const APInt &X) { 8601 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8602 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8603 if (Range.contains(V0->getValue())) 8604 return false; 8605 // X should be at least 1, so X-1 is non-negative. 8606 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8607 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8608 if (Range.contains(V1->getValue())) 8609 return true; 8610 return false; 8611 }; 8612 8613 // If SolveQuadraticEquationWrap returns None, it means that there can 8614 // be a solution, but the function failed to find it. We cannot treat it 8615 // as "no solution". 8616 if (!SO.hasValue() || !UO.hasValue()) 8617 return { None, false }; 8618 8619 // Check the smaller value first to see if it leaves the range. 8620 // At this point, both SO and UO must have values. 8621 Optional<APInt> Min = MinOptional(SO, UO); 8622 if (LeavesRange(*Min)) 8623 return { Min, true }; 8624 Optional<APInt> Max = Min == SO ? UO : SO; 8625 if (LeavesRange(*Max)) 8626 return { Max, true }; 8627 8628 // Solutions were found, but were eliminated, hence the "true". 8629 return { None, true }; 8630 }; 8631 8632 std::tie(A, B, C, M, BitWidth) = *T; 8633 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8634 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8635 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8636 auto SL = SolveForBoundary(Lower); 8637 auto SU = SolveForBoundary(Upper); 8638 // If any of the solutions was unknown, no meaninigful conclusions can 8639 // be made. 8640 if (!SL.second || !SU.second) 8641 return None; 8642 8643 // Claim: The correct solution is not some value between Min and Max. 8644 // 8645 // Justification: Assuming that Min and Max are different values, one of 8646 // them is when the first signed overflow happens, the other is when the 8647 // first unsigned overflow happens. Crossing the range boundary is only 8648 // possible via an overflow (treating 0 as a special case of it, modeling 8649 // an overflow as crossing k*2^W for some k). 8650 // 8651 // The interesting case here is when Min was eliminated as an invalid 8652 // solution, but Max was not. The argument is that if there was another 8653 // overflow between Min and Max, it would also have been eliminated if 8654 // it was considered. 8655 // 8656 // For a given boundary, it is possible to have two overflows of the same 8657 // type (signed/unsigned) without having the other type in between: this 8658 // can happen when the vertex of the parabola is between the iterations 8659 // corresponding to the overflows. This is only possible when the two 8660 // overflows cross k*2^W for the same k. In such case, if the second one 8661 // left the range (and was the first one to do so), the first overflow 8662 // would have to enter the range, which would mean that either we had left 8663 // the range before or that we started outside of it. Both of these cases 8664 // are contradictions. 8665 // 8666 // Claim: In the case where SolveForBoundary returns None, the correct 8667 // solution is not some value between the Max for this boundary and the 8668 // Min of the other boundary. 8669 // 8670 // Justification: Assume that we had such Max_A and Min_B corresponding 8671 // to range boundaries A and B and such that Max_A < Min_B. If there was 8672 // a solution between Max_A and Min_B, it would have to be caused by an 8673 // overflow corresponding to either A or B. It cannot correspond to B, 8674 // since Min_B is the first occurrence of such an overflow. If it 8675 // corresponded to A, it would have to be either a signed or an unsigned 8676 // overflow that is larger than both eliminated overflows for A. But 8677 // between the eliminated overflows and this overflow, the values would 8678 // cover the entire value space, thus crossing the other boundary, which 8679 // is a contradiction. 8680 8681 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8682 } 8683 8684 ScalarEvolution::ExitLimit 8685 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8686 bool AllowPredicates) { 8687 8688 // This is only used for loops with a "x != y" exit test. The exit condition 8689 // is now expressed as a single expression, V = x-y. So the exit test is 8690 // effectively V != 0. We know and take advantage of the fact that this 8691 // expression only being used in a comparison by zero context. 8692 8693 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8694 // If the value is a constant 8695 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8696 // If the value is already zero, the branch will execute zero times. 8697 if (C->getValue()->isZero()) return C; 8698 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8699 } 8700 8701 const SCEVAddRecExpr *AddRec = 8702 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8703 8704 if (!AddRec && AllowPredicates) 8705 // Try to make this an AddRec using runtime tests, in the first X 8706 // iterations of this loop, where X is the SCEV expression found by the 8707 // algorithm below. 8708 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8709 8710 if (!AddRec || AddRec->getLoop() != L) 8711 return getCouldNotCompute(); 8712 8713 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8714 // the quadratic equation to solve it. 8715 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8716 // We can only use this value if the chrec ends up with an exact zero 8717 // value at this index. When solving for "X*X != 5", for example, we 8718 // should not accept a root of 2. 8719 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8720 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8721 return ExitLimit(R, R, false, Predicates); 8722 } 8723 return getCouldNotCompute(); 8724 } 8725 8726 // Otherwise we can only handle this if it is affine. 8727 if (!AddRec->isAffine()) 8728 return getCouldNotCompute(); 8729 8730 // If this is an affine expression, the execution count of this branch is 8731 // the minimum unsigned root of the following equation: 8732 // 8733 // Start + Step*N = 0 (mod 2^BW) 8734 // 8735 // equivalent to: 8736 // 8737 // Step*N = -Start (mod 2^BW) 8738 // 8739 // where BW is the common bit width of Start and Step. 8740 8741 // Get the initial value for the loop. 8742 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8743 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8744 8745 // For now we handle only constant steps. 8746 // 8747 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8748 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8749 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8750 // We have not yet seen any such cases. 8751 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8752 if (!StepC || StepC->getValue()->isZero()) 8753 return getCouldNotCompute(); 8754 8755 // For positive steps (counting up until unsigned overflow): 8756 // N = -Start/Step (as unsigned) 8757 // For negative steps (counting down to zero): 8758 // N = Start/-Step 8759 // First compute the unsigned distance from zero in the direction of Step. 8760 bool CountDown = StepC->getAPInt().isNegative(); 8761 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8762 8763 // Handle unitary steps, which cannot wraparound. 8764 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8765 // N = Distance (as unsigned) 8766 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8767 APInt MaxBECount = getUnsignedRangeMax(Distance); 8768 8769 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8770 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8771 // case, and see if we can improve the bound. 8772 // 8773 // Explicitly handling this here is necessary because getUnsignedRange 8774 // isn't context-sensitive; it doesn't know that we only care about the 8775 // range inside the loop. 8776 const SCEV *Zero = getZero(Distance->getType()); 8777 const SCEV *One = getOne(Distance->getType()); 8778 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8779 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8780 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8781 // as "unsigned_max(Distance + 1) - 1". 8782 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8783 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8784 } 8785 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8786 } 8787 8788 // If the condition controls loop exit (the loop exits only if the expression 8789 // is true) and the addition is no-wrap we can use unsigned divide to 8790 // compute the backedge count. In this case, the step may not divide the 8791 // distance, but we don't care because if the condition is "missed" the loop 8792 // will have undefined behavior due to wrapping. 8793 if (ControlsExit && AddRec->hasNoSelfWrap() && 8794 loopHasNoAbnormalExits(AddRec->getLoop())) { 8795 const SCEV *Exact = 8796 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8797 const SCEV *Max = 8798 Exact == getCouldNotCompute() 8799 ? Exact 8800 : getConstant(getUnsignedRangeMax(Exact)); 8801 return ExitLimit(Exact, Max, false, Predicates); 8802 } 8803 8804 // Solve the general equation. 8805 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8806 getNegativeSCEV(Start), *this); 8807 const SCEV *M = E == getCouldNotCompute() 8808 ? E 8809 : getConstant(getUnsignedRangeMax(E)); 8810 return ExitLimit(E, M, false, Predicates); 8811 } 8812 8813 ScalarEvolution::ExitLimit 8814 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8815 // Loops that look like: while (X == 0) are very strange indeed. We don't 8816 // handle them yet except for the trivial case. This could be expanded in the 8817 // future as needed. 8818 8819 // If the value is a constant, check to see if it is known to be non-zero 8820 // already. If so, the backedge will execute zero times. 8821 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8822 if (!C->getValue()->isZero()) 8823 return getZero(C->getType()); 8824 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8825 } 8826 8827 // We could implement others, but I really doubt anyone writes loops like 8828 // this, and if they did, they would already be constant folded. 8829 return getCouldNotCompute(); 8830 } 8831 8832 std::pair<BasicBlock *, BasicBlock *> 8833 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8834 // If the block has a unique predecessor, then there is no path from the 8835 // predecessor to the block that does not go through the direct edge 8836 // from the predecessor to the block. 8837 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8838 return {Pred, BB}; 8839 8840 // A loop's header is defined to be a block that dominates the loop. 8841 // If the header has a unique predecessor outside the loop, it must be 8842 // a block that has exactly one successor that can reach the loop. 8843 if (Loop *L = LI.getLoopFor(BB)) 8844 return {L->getLoopPredecessor(), L->getHeader()}; 8845 8846 return {nullptr, nullptr}; 8847 } 8848 8849 /// SCEV structural equivalence is usually sufficient for testing whether two 8850 /// expressions are equal, however for the purposes of looking for a condition 8851 /// guarding a loop, it can be useful to be a little more general, since a 8852 /// front-end may have replicated the controlling expression. 8853 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8854 // Quick check to see if they are the same SCEV. 8855 if (A == B) return true; 8856 8857 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8858 // Not all instructions that are "identical" compute the same value. For 8859 // instance, two distinct alloca instructions allocating the same type are 8860 // identical and do not read memory; but compute distinct values. 8861 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8862 }; 8863 8864 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8865 // two different instructions with the same value. Check for this case. 8866 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8867 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8868 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8869 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8870 if (ComputesEqualValues(AI, BI)) 8871 return true; 8872 8873 // Otherwise assume they may have a different value. 8874 return false; 8875 } 8876 8877 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8878 const SCEV *&LHS, const SCEV *&RHS, 8879 unsigned Depth) { 8880 bool Changed = false; 8881 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8882 // '0 != 0'. 8883 auto TrivialCase = [&](bool TriviallyTrue) { 8884 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8885 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8886 return true; 8887 }; 8888 // If we hit the max recursion limit bail out. 8889 if (Depth >= 3) 8890 return false; 8891 8892 // Canonicalize a constant to the right side. 8893 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8894 // Check for both operands constant. 8895 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8896 if (ConstantExpr::getICmp(Pred, 8897 LHSC->getValue(), 8898 RHSC->getValue())->isNullValue()) 8899 return TrivialCase(false); 8900 else 8901 return TrivialCase(true); 8902 } 8903 // Otherwise swap the operands to put the constant on the right. 8904 std::swap(LHS, RHS); 8905 Pred = ICmpInst::getSwappedPredicate(Pred); 8906 Changed = true; 8907 } 8908 8909 // If we're comparing an addrec with a value which is loop-invariant in the 8910 // addrec's loop, put the addrec on the left. Also make a dominance check, 8911 // as both operands could be addrecs loop-invariant in each other's loop. 8912 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8913 const Loop *L = AR->getLoop(); 8914 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8915 std::swap(LHS, RHS); 8916 Pred = ICmpInst::getSwappedPredicate(Pred); 8917 Changed = true; 8918 } 8919 } 8920 8921 // If there's a constant operand, canonicalize comparisons with boundary 8922 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8923 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8924 const APInt &RA = RC->getAPInt(); 8925 8926 bool SimplifiedByConstantRange = false; 8927 8928 if (!ICmpInst::isEquality(Pred)) { 8929 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8930 if (ExactCR.isFullSet()) 8931 return TrivialCase(true); 8932 else if (ExactCR.isEmptySet()) 8933 return TrivialCase(false); 8934 8935 APInt NewRHS; 8936 CmpInst::Predicate NewPred; 8937 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8938 ICmpInst::isEquality(NewPred)) { 8939 // We were able to convert an inequality to an equality. 8940 Pred = NewPred; 8941 RHS = getConstant(NewRHS); 8942 Changed = SimplifiedByConstantRange = true; 8943 } 8944 } 8945 8946 if (!SimplifiedByConstantRange) { 8947 switch (Pred) { 8948 default: 8949 break; 8950 case ICmpInst::ICMP_EQ: 8951 case ICmpInst::ICMP_NE: 8952 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8953 if (!RA) 8954 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8955 if (const SCEVMulExpr *ME = 8956 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8957 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8958 ME->getOperand(0)->isAllOnesValue()) { 8959 RHS = AE->getOperand(1); 8960 LHS = ME->getOperand(1); 8961 Changed = true; 8962 } 8963 break; 8964 8965 8966 // The "Should have been caught earlier!" messages refer to the fact 8967 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8968 // should have fired on the corresponding cases, and canonicalized the 8969 // check to trivial case. 8970 8971 case ICmpInst::ICMP_UGE: 8972 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8973 Pred = ICmpInst::ICMP_UGT; 8974 RHS = getConstant(RA - 1); 8975 Changed = true; 8976 break; 8977 case ICmpInst::ICMP_ULE: 8978 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8979 Pred = ICmpInst::ICMP_ULT; 8980 RHS = getConstant(RA + 1); 8981 Changed = true; 8982 break; 8983 case ICmpInst::ICMP_SGE: 8984 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8985 Pred = ICmpInst::ICMP_SGT; 8986 RHS = getConstant(RA - 1); 8987 Changed = true; 8988 break; 8989 case ICmpInst::ICMP_SLE: 8990 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8991 Pred = ICmpInst::ICMP_SLT; 8992 RHS = getConstant(RA + 1); 8993 Changed = true; 8994 break; 8995 } 8996 } 8997 } 8998 8999 // Check for obvious equality. 9000 if (HasSameValue(LHS, RHS)) { 9001 if (ICmpInst::isTrueWhenEqual(Pred)) 9002 return TrivialCase(true); 9003 if (ICmpInst::isFalseWhenEqual(Pred)) 9004 return TrivialCase(false); 9005 } 9006 9007 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9008 // adding or subtracting 1 from one of the operands. 9009 switch (Pred) { 9010 case ICmpInst::ICMP_SLE: 9011 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9012 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9013 SCEV::FlagNSW); 9014 Pred = ICmpInst::ICMP_SLT; 9015 Changed = true; 9016 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9017 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9018 SCEV::FlagNSW); 9019 Pred = ICmpInst::ICMP_SLT; 9020 Changed = true; 9021 } 9022 break; 9023 case ICmpInst::ICMP_SGE: 9024 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9025 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9026 SCEV::FlagNSW); 9027 Pred = ICmpInst::ICMP_SGT; 9028 Changed = true; 9029 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9030 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9031 SCEV::FlagNSW); 9032 Pred = ICmpInst::ICMP_SGT; 9033 Changed = true; 9034 } 9035 break; 9036 case ICmpInst::ICMP_ULE: 9037 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9038 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9039 SCEV::FlagNUW); 9040 Pred = ICmpInst::ICMP_ULT; 9041 Changed = true; 9042 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9043 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9044 Pred = ICmpInst::ICMP_ULT; 9045 Changed = true; 9046 } 9047 break; 9048 case ICmpInst::ICMP_UGE: 9049 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9050 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9051 Pred = ICmpInst::ICMP_UGT; 9052 Changed = true; 9053 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9054 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9055 SCEV::FlagNUW); 9056 Pred = ICmpInst::ICMP_UGT; 9057 Changed = true; 9058 } 9059 break; 9060 default: 9061 break; 9062 } 9063 9064 // TODO: More simplifications are possible here. 9065 9066 // Recursively simplify until we either hit a recursion limit or nothing 9067 // changes. 9068 if (Changed) 9069 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9070 9071 return Changed; 9072 } 9073 9074 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9075 return getSignedRangeMax(S).isNegative(); 9076 } 9077 9078 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9079 return getSignedRangeMin(S).isStrictlyPositive(); 9080 } 9081 9082 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9083 return !getSignedRangeMin(S).isNegative(); 9084 } 9085 9086 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9087 return !getSignedRangeMax(S).isStrictlyPositive(); 9088 } 9089 9090 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9091 return isKnownNegative(S) || isKnownPositive(S); 9092 } 9093 9094 std::pair<const SCEV *, const SCEV *> 9095 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9096 // Compute SCEV on entry of loop L. 9097 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9098 if (Start == getCouldNotCompute()) 9099 return { Start, Start }; 9100 // Compute post increment SCEV for loop L. 9101 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9102 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9103 return { Start, PostInc }; 9104 } 9105 9106 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9107 const SCEV *LHS, const SCEV *RHS) { 9108 // First collect all loops. 9109 SmallPtrSet<const Loop *, 8> LoopsUsed; 9110 getUsedLoops(LHS, LoopsUsed); 9111 getUsedLoops(RHS, LoopsUsed); 9112 9113 if (LoopsUsed.empty()) 9114 return false; 9115 9116 // Domination relationship must be a linear order on collected loops. 9117 #ifndef NDEBUG 9118 for (auto *L1 : LoopsUsed) 9119 for (auto *L2 : LoopsUsed) 9120 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9121 DT.dominates(L2->getHeader(), L1->getHeader())) && 9122 "Domination relationship is not a linear order"); 9123 #endif 9124 9125 const Loop *MDL = 9126 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9127 [&](const Loop *L1, const Loop *L2) { 9128 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9129 }); 9130 9131 // Get init and post increment value for LHS. 9132 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9133 // if LHS contains unknown non-invariant SCEV then bail out. 9134 if (SplitLHS.first == getCouldNotCompute()) 9135 return false; 9136 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9137 // Get init and post increment value for RHS. 9138 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9139 // if RHS contains unknown non-invariant SCEV then bail out. 9140 if (SplitRHS.first == getCouldNotCompute()) 9141 return false; 9142 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9143 // It is possible that init SCEV contains an invariant load but it does 9144 // not dominate MDL and is not available at MDL loop entry, so we should 9145 // check it here. 9146 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9147 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9148 return false; 9149 9150 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9151 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9152 SplitRHS.second); 9153 } 9154 9155 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9156 const SCEV *LHS, const SCEV *RHS) { 9157 // Canonicalize the inputs first. 9158 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9159 9160 if (isKnownViaInduction(Pred, LHS, RHS)) 9161 return true; 9162 9163 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9164 return true; 9165 9166 // Otherwise see what can be done with some simple reasoning. 9167 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9168 } 9169 9170 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9171 const SCEVAddRecExpr *LHS, 9172 const SCEV *RHS) { 9173 const Loop *L = LHS->getLoop(); 9174 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9175 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9176 } 9177 9178 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9179 ICmpInst::Predicate Pred, 9180 bool &Increasing) { 9181 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9182 9183 #ifndef NDEBUG 9184 // Verify an invariant: inverting the predicate should turn a monotonically 9185 // increasing change to a monotonically decreasing one, and vice versa. 9186 bool IncreasingSwapped; 9187 bool ResultSwapped = isMonotonicPredicateImpl( 9188 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9189 9190 assert(Result == ResultSwapped && "should be able to analyze both!"); 9191 if (ResultSwapped) 9192 assert(Increasing == !IncreasingSwapped && 9193 "monotonicity should flip as we flip the predicate"); 9194 #endif 9195 9196 return Result; 9197 } 9198 9199 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9200 ICmpInst::Predicate Pred, 9201 bool &Increasing) { 9202 9203 // A zero step value for LHS means the induction variable is essentially a 9204 // loop invariant value. We don't really depend on the predicate actually 9205 // flipping from false to true (for increasing predicates, and the other way 9206 // around for decreasing predicates), all we care about is that *if* the 9207 // predicate changes then it only changes from false to true. 9208 // 9209 // A zero step value in itself is not very useful, but there may be places 9210 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9211 // as general as possible. 9212 9213 switch (Pred) { 9214 default: 9215 return false; // Conservative answer 9216 9217 case ICmpInst::ICMP_UGT: 9218 case ICmpInst::ICMP_UGE: 9219 case ICmpInst::ICMP_ULT: 9220 case ICmpInst::ICMP_ULE: 9221 if (!LHS->hasNoUnsignedWrap()) 9222 return false; 9223 9224 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9225 return true; 9226 9227 case ICmpInst::ICMP_SGT: 9228 case ICmpInst::ICMP_SGE: 9229 case ICmpInst::ICMP_SLT: 9230 case ICmpInst::ICMP_SLE: { 9231 if (!LHS->hasNoSignedWrap()) 9232 return false; 9233 9234 const SCEV *Step = LHS->getStepRecurrence(*this); 9235 9236 if (isKnownNonNegative(Step)) { 9237 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9238 return true; 9239 } 9240 9241 if (isKnownNonPositive(Step)) { 9242 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9243 return true; 9244 } 9245 9246 return false; 9247 } 9248 9249 } 9250 9251 llvm_unreachable("switch has default clause!"); 9252 } 9253 9254 bool ScalarEvolution::isLoopInvariantPredicate( 9255 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9256 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9257 const SCEV *&InvariantRHS) { 9258 9259 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9260 if (!isLoopInvariant(RHS, L)) { 9261 if (!isLoopInvariant(LHS, L)) 9262 return false; 9263 9264 std::swap(LHS, RHS); 9265 Pred = ICmpInst::getSwappedPredicate(Pred); 9266 } 9267 9268 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9269 if (!ArLHS || ArLHS->getLoop() != L) 9270 return false; 9271 9272 bool Increasing; 9273 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9274 return false; 9275 9276 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9277 // true as the loop iterates, and the backedge is control dependent on 9278 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9279 // 9280 // * if the predicate was false in the first iteration then the predicate 9281 // is never evaluated again, since the loop exits without taking the 9282 // backedge. 9283 // * if the predicate was true in the first iteration then it will 9284 // continue to be true for all future iterations since it is 9285 // monotonically increasing. 9286 // 9287 // For both the above possibilities, we can replace the loop varying 9288 // predicate with its value on the first iteration of the loop (which is 9289 // loop invariant). 9290 // 9291 // A similar reasoning applies for a monotonically decreasing predicate, by 9292 // replacing true with false and false with true in the above two bullets. 9293 9294 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9295 9296 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9297 return false; 9298 9299 InvariantPred = Pred; 9300 InvariantLHS = ArLHS->getStart(); 9301 InvariantRHS = RHS; 9302 return true; 9303 } 9304 9305 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9306 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9307 if (HasSameValue(LHS, RHS)) 9308 return ICmpInst::isTrueWhenEqual(Pred); 9309 9310 // This code is split out from isKnownPredicate because it is called from 9311 // within isLoopEntryGuardedByCond. 9312 9313 auto CheckRanges = 9314 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9315 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9316 .contains(RangeLHS); 9317 }; 9318 9319 // The check at the top of the function catches the case where the values are 9320 // known to be equal. 9321 if (Pred == CmpInst::ICMP_EQ) 9322 return false; 9323 9324 if (Pred == CmpInst::ICMP_NE) 9325 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9326 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9327 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9328 9329 if (CmpInst::isSigned(Pred)) 9330 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9331 9332 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9333 } 9334 9335 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9336 const SCEV *LHS, 9337 const SCEV *RHS) { 9338 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9339 // Return Y via OutY. 9340 auto MatchBinaryAddToConst = 9341 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9342 SCEV::NoWrapFlags ExpectedFlags) { 9343 const SCEV *NonConstOp, *ConstOp; 9344 SCEV::NoWrapFlags FlagsPresent; 9345 9346 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9347 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9348 return false; 9349 9350 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9351 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9352 }; 9353 9354 APInt C; 9355 9356 switch (Pred) { 9357 default: 9358 break; 9359 9360 case ICmpInst::ICMP_SGE: 9361 std::swap(LHS, RHS); 9362 LLVM_FALLTHROUGH; 9363 case ICmpInst::ICMP_SLE: 9364 // X s<= (X + C)<nsw> if C >= 0 9365 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9366 return true; 9367 9368 // (X + C)<nsw> s<= X if C <= 0 9369 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9370 !C.isStrictlyPositive()) 9371 return true; 9372 break; 9373 9374 case ICmpInst::ICMP_SGT: 9375 std::swap(LHS, RHS); 9376 LLVM_FALLTHROUGH; 9377 case ICmpInst::ICMP_SLT: 9378 // X s< (X + C)<nsw> if C > 0 9379 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9380 C.isStrictlyPositive()) 9381 return true; 9382 9383 // (X + C)<nsw> s< X if C < 0 9384 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9385 return true; 9386 break; 9387 } 9388 9389 return false; 9390 } 9391 9392 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9393 const SCEV *LHS, 9394 const SCEV *RHS) { 9395 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9396 return false; 9397 9398 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9399 // the stack can result in exponential time complexity. 9400 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9401 9402 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9403 // 9404 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9405 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9406 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9407 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9408 // use isKnownPredicate later if needed. 9409 return isKnownNonNegative(RHS) && 9410 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9411 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9412 } 9413 9414 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9415 ICmpInst::Predicate Pred, 9416 const SCEV *LHS, const SCEV *RHS) { 9417 // No need to even try if we know the module has no guards. 9418 if (!HasGuards) 9419 return false; 9420 9421 return any_of(*BB, [&](Instruction &I) { 9422 using namespace llvm::PatternMatch; 9423 9424 Value *Condition; 9425 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9426 m_Value(Condition))) && 9427 isImpliedCond(Pred, LHS, RHS, Condition, false); 9428 }); 9429 } 9430 9431 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9432 /// protected by a conditional between LHS and RHS. This is used to 9433 /// to eliminate casts. 9434 bool 9435 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9436 ICmpInst::Predicate Pred, 9437 const SCEV *LHS, const SCEV *RHS) { 9438 // Interpret a null as meaning no loop, where there is obviously no guard 9439 // (interprocedural conditions notwithstanding). 9440 if (!L) return true; 9441 9442 if (VerifyIR) 9443 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9444 "This cannot be done on broken IR!"); 9445 9446 9447 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9448 return true; 9449 9450 BasicBlock *Latch = L->getLoopLatch(); 9451 if (!Latch) 9452 return false; 9453 9454 BranchInst *LoopContinuePredicate = 9455 dyn_cast<BranchInst>(Latch->getTerminator()); 9456 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9457 isImpliedCond(Pred, LHS, RHS, 9458 LoopContinuePredicate->getCondition(), 9459 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9460 return true; 9461 9462 // We don't want more than one activation of the following loops on the stack 9463 // -- that can lead to O(n!) time complexity. 9464 if (WalkingBEDominatingConds) 9465 return false; 9466 9467 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9468 9469 // See if we can exploit a trip count to prove the predicate. 9470 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9471 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9472 if (LatchBECount != getCouldNotCompute()) { 9473 // We know that Latch branches back to the loop header exactly 9474 // LatchBECount times. This means the backdege condition at Latch is 9475 // equivalent to "{0,+,1} u< LatchBECount". 9476 Type *Ty = LatchBECount->getType(); 9477 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9478 const SCEV *LoopCounter = 9479 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9480 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9481 LatchBECount)) 9482 return true; 9483 } 9484 9485 // Check conditions due to any @llvm.assume intrinsics. 9486 for (auto &AssumeVH : AC.assumptions()) { 9487 if (!AssumeVH) 9488 continue; 9489 auto *CI = cast<CallInst>(AssumeVH); 9490 if (!DT.dominates(CI, Latch->getTerminator())) 9491 continue; 9492 9493 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9494 return true; 9495 } 9496 9497 // If the loop is not reachable from the entry block, we risk running into an 9498 // infinite loop as we walk up into the dom tree. These loops do not matter 9499 // anyway, so we just return a conservative answer when we see them. 9500 if (!DT.isReachableFromEntry(L->getHeader())) 9501 return false; 9502 9503 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9504 return true; 9505 9506 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9507 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9508 assert(DTN && "should reach the loop header before reaching the root!"); 9509 9510 BasicBlock *BB = DTN->getBlock(); 9511 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9512 return true; 9513 9514 BasicBlock *PBB = BB->getSinglePredecessor(); 9515 if (!PBB) 9516 continue; 9517 9518 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9519 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9520 continue; 9521 9522 Value *Condition = ContinuePredicate->getCondition(); 9523 9524 // If we have an edge `E` within the loop body that dominates the only 9525 // latch, the condition guarding `E` also guards the backedge. This 9526 // reasoning works only for loops with a single latch. 9527 9528 BasicBlockEdge DominatingEdge(PBB, BB); 9529 if (DominatingEdge.isSingleEdge()) { 9530 // We're constructively (and conservatively) enumerating edges within the 9531 // loop body that dominate the latch. The dominator tree better agree 9532 // with us on this: 9533 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9534 9535 if (isImpliedCond(Pred, LHS, RHS, Condition, 9536 BB != ContinuePredicate->getSuccessor(0))) 9537 return true; 9538 } 9539 } 9540 9541 return false; 9542 } 9543 9544 bool 9545 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9546 ICmpInst::Predicate Pred, 9547 const SCEV *LHS, const SCEV *RHS) { 9548 // Interpret a null as meaning no loop, where there is obviously no guard 9549 // (interprocedural conditions notwithstanding). 9550 if (!L) return false; 9551 9552 if (VerifyIR) 9553 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9554 "This cannot be done on broken IR!"); 9555 9556 // Both LHS and RHS must be available at loop entry. 9557 assert(isAvailableAtLoopEntry(LHS, L) && 9558 "LHS is not available at Loop Entry"); 9559 assert(isAvailableAtLoopEntry(RHS, L) && 9560 "RHS is not available at Loop Entry"); 9561 9562 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9563 return true; 9564 9565 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9566 // the facts (a >= b && a != b) separately. A typical situation is when the 9567 // non-strict comparison is known from ranges and non-equality is known from 9568 // dominating predicates. If we are proving strict comparison, we always try 9569 // to prove non-equality and non-strict comparison separately. 9570 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9571 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9572 bool ProvedNonStrictComparison = false; 9573 bool ProvedNonEquality = false; 9574 9575 if (ProvingStrictComparison) { 9576 ProvedNonStrictComparison = 9577 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9578 ProvedNonEquality = 9579 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9580 if (ProvedNonStrictComparison && ProvedNonEquality) 9581 return true; 9582 } 9583 9584 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9585 auto ProveViaGuard = [&](BasicBlock *Block) { 9586 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9587 return true; 9588 if (ProvingStrictComparison) { 9589 if (!ProvedNonStrictComparison) 9590 ProvedNonStrictComparison = 9591 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9592 if (!ProvedNonEquality) 9593 ProvedNonEquality = 9594 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9595 if (ProvedNonStrictComparison && ProvedNonEquality) 9596 return true; 9597 } 9598 return false; 9599 }; 9600 9601 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9602 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9603 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9604 return true; 9605 if (ProvingStrictComparison) { 9606 if (!ProvedNonStrictComparison) 9607 ProvedNonStrictComparison = 9608 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9609 if (!ProvedNonEquality) 9610 ProvedNonEquality = 9611 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9612 if (ProvedNonStrictComparison && ProvedNonEquality) 9613 return true; 9614 } 9615 return false; 9616 }; 9617 9618 // Starting at the loop predecessor, climb up the predecessor chain, as long 9619 // as there are predecessors that can be found that have unique successors 9620 // leading to the original header. 9621 for (std::pair<BasicBlock *, BasicBlock *> 9622 Pair(L->getLoopPredecessor(), L->getHeader()); 9623 Pair.first; 9624 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9625 9626 if (ProveViaGuard(Pair.first)) 9627 return true; 9628 9629 BranchInst *LoopEntryPredicate = 9630 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9631 if (!LoopEntryPredicate || 9632 LoopEntryPredicate->isUnconditional()) 9633 continue; 9634 9635 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9636 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9637 return true; 9638 } 9639 9640 // Check conditions due to any @llvm.assume intrinsics. 9641 for (auto &AssumeVH : AC.assumptions()) { 9642 if (!AssumeVH) 9643 continue; 9644 auto *CI = cast<CallInst>(AssumeVH); 9645 if (!DT.dominates(CI, L->getHeader())) 9646 continue; 9647 9648 if (ProveViaCond(CI->getArgOperand(0), false)) 9649 return true; 9650 } 9651 9652 return false; 9653 } 9654 9655 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9656 const SCEV *LHS, const SCEV *RHS, 9657 Value *FoundCondValue, 9658 bool Inverse) { 9659 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9660 return false; 9661 9662 auto ClearOnExit = 9663 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9664 9665 // Recursively handle And and Or conditions. 9666 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9667 if (BO->getOpcode() == Instruction::And) { 9668 if (!Inverse) 9669 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9670 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9671 } else if (BO->getOpcode() == Instruction::Or) { 9672 if (Inverse) 9673 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9674 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9675 } 9676 } 9677 9678 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9679 if (!ICI) return false; 9680 9681 // Now that we found a conditional branch that dominates the loop or controls 9682 // the loop latch. Check to see if it is the comparison we are looking for. 9683 ICmpInst::Predicate FoundPred; 9684 if (Inverse) 9685 FoundPred = ICI->getInversePredicate(); 9686 else 9687 FoundPred = ICI->getPredicate(); 9688 9689 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9690 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9691 9692 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9693 } 9694 9695 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9696 const SCEV *RHS, 9697 ICmpInst::Predicate FoundPred, 9698 const SCEV *FoundLHS, 9699 const SCEV *FoundRHS) { 9700 // Balance the types. 9701 if (getTypeSizeInBits(LHS->getType()) < 9702 getTypeSizeInBits(FoundLHS->getType())) { 9703 if (CmpInst::isSigned(Pred)) { 9704 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9705 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9706 } else { 9707 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9708 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9709 } 9710 } else if (getTypeSizeInBits(LHS->getType()) > 9711 getTypeSizeInBits(FoundLHS->getType())) { 9712 if (CmpInst::isSigned(FoundPred)) { 9713 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9714 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9715 } else { 9716 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9717 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9718 } 9719 } 9720 9721 // Canonicalize the query to match the way instcombine will have 9722 // canonicalized the comparison. 9723 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9724 if (LHS == RHS) 9725 return CmpInst::isTrueWhenEqual(Pred); 9726 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9727 if (FoundLHS == FoundRHS) 9728 return CmpInst::isFalseWhenEqual(FoundPred); 9729 9730 // Check to see if we can make the LHS or RHS match. 9731 if (LHS == FoundRHS || RHS == FoundLHS) { 9732 if (isa<SCEVConstant>(RHS)) { 9733 std::swap(FoundLHS, FoundRHS); 9734 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9735 } else { 9736 std::swap(LHS, RHS); 9737 Pred = ICmpInst::getSwappedPredicate(Pred); 9738 } 9739 } 9740 9741 // Check whether the found predicate is the same as the desired predicate. 9742 if (FoundPred == Pred) 9743 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9744 9745 // Check whether swapping the found predicate makes it the same as the 9746 // desired predicate. 9747 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9748 if (isa<SCEVConstant>(RHS)) 9749 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9750 else 9751 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9752 RHS, LHS, FoundLHS, FoundRHS); 9753 } 9754 9755 // Unsigned comparison is the same as signed comparison when both the operands 9756 // are non-negative. 9757 if (CmpInst::isUnsigned(FoundPred) && 9758 CmpInst::getSignedPredicate(FoundPred) == Pred && 9759 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9760 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9761 9762 // Check if we can make progress by sharpening ranges. 9763 if (FoundPred == ICmpInst::ICMP_NE && 9764 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9765 9766 const SCEVConstant *C = nullptr; 9767 const SCEV *V = nullptr; 9768 9769 if (isa<SCEVConstant>(FoundLHS)) { 9770 C = cast<SCEVConstant>(FoundLHS); 9771 V = FoundRHS; 9772 } else { 9773 C = cast<SCEVConstant>(FoundRHS); 9774 V = FoundLHS; 9775 } 9776 9777 // The guarding predicate tells us that C != V. If the known range 9778 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9779 // range we consider has to correspond to same signedness as the 9780 // predicate we're interested in folding. 9781 9782 APInt Min = ICmpInst::isSigned(Pred) ? 9783 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9784 9785 if (Min == C->getAPInt()) { 9786 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9787 // This is true even if (Min + 1) wraps around -- in case of 9788 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9789 9790 APInt SharperMin = Min + 1; 9791 9792 switch (Pred) { 9793 case ICmpInst::ICMP_SGE: 9794 case ICmpInst::ICMP_UGE: 9795 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9796 // RHS, we're done. 9797 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9798 getConstant(SharperMin))) 9799 return true; 9800 LLVM_FALLTHROUGH; 9801 9802 case ICmpInst::ICMP_SGT: 9803 case ICmpInst::ICMP_UGT: 9804 // We know from the range information that (V `Pred` Min || 9805 // V == Min). We know from the guarding condition that !(V 9806 // == Min). This gives us 9807 // 9808 // V `Pred` Min || V == Min && !(V == Min) 9809 // => V `Pred` Min 9810 // 9811 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9812 9813 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9814 return true; 9815 LLVM_FALLTHROUGH; 9816 9817 default: 9818 // No change 9819 break; 9820 } 9821 } 9822 } 9823 9824 // Check whether the actual condition is beyond sufficient. 9825 if (FoundPred == ICmpInst::ICMP_EQ) 9826 if (ICmpInst::isTrueWhenEqual(Pred)) 9827 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9828 return true; 9829 if (Pred == ICmpInst::ICMP_NE) 9830 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9831 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9832 return true; 9833 9834 // Otherwise assume the worst. 9835 return false; 9836 } 9837 9838 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9839 const SCEV *&L, const SCEV *&R, 9840 SCEV::NoWrapFlags &Flags) { 9841 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9842 if (!AE || AE->getNumOperands() != 2) 9843 return false; 9844 9845 L = AE->getOperand(0); 9846 R = AE->getOperand(1); 9847 Flags = AE->getNoWrapFlags(); 9848 return true; 9849 } 9850 9851 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9852 const SCEV *Less) { 9853 // We avoid subtracting expressions here because this function is usually 9854 // fairly deep in the call stack (i.e. is called many times). 9855 9856 // X - X = 0. 9857 if (More == Less) 9858 return APInt(getTypeSizeInBits(More->getType()), 0); 9859 9860 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9861 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9862 const auto *MAR = cast<SCEVAddRecExpr>(More); 9863 9864 if (LAR->getLoop() != MAR->getLoop()) 9865 return None; 9866 9867 // We look at affine expressions only; not for correctness but to keep 9868 // getStepRecurrence cheap. 9869 if (!LAR->isAffine() || !MAR->isAffine()) 9870 return None; 9871 9872 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9873 return None; 9874 9875 Less = LAR->getStart(); 9876 More = MAR->getStart(); 9877 9878 // fall through 9879 } 9880 9881 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9882 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9883 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9884 return M - L; 9885 } 9886 9887 SCEV::NoWrapFlags Flags; 9888 const SCEV *LLess = nullptr, *RLess = nullptr; 9889 const SCEV *LMore = nullptr, *RMore = nullptr; 9890 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9891 // Compare (X + C1) vs X. 9892 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9893 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9894 if (RLess == More) 9895 return -(C1->getAPInt()); 9896 9897 // Compare X vs (X + C2). 9898 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9899 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9900 if (RMore == Less) 9901 return C2->getAPInt(); 9902 9903 // Compare (X + C1) vs (X + C2). 9904 if (C1 && C2 && RLess == RMore) 9905 return C2->getAPInt() - C1->getAPInt(); 9906 9907 return None; 9908 } 9909 9910 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9911 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9912 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9913 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9914 return false; 9915 9916 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9917 if (!AddRecLHS) 9918 return false; 9919 9920 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9921 if (!AddRecFoundLHS) 9922 return false; 9923 9924 // We'd like to let SCEV reason about control dependencies, so we constrain 9925 // both the inequalities to be about add recurrences on the same loop. This 9926 // way we can use isLoopEntryGuardedByCond later. 9927 9928 const Loop *L = AddRecFoundLHS->getLoop(); 9929 if (L != AddRecLHS->getLoop()) 9930 return false; 9931 9932 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9933 // 9934 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9935 // ... (2) 9936 // 9937 // Informal proof for (2), assuming (1) [*]: 9938 // 9939 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9940 // 9941 // Then 9942 // 9943 // FoundLHS s< FoundRHS s< INT_MIN - C 9944 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9945 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9946 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9947 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9948 // <=> FoundLHS + C s< FoundRHS + C 9949 // 9950 // [*]: (1) can be proved by ruling out overflow. 9951 // 9952 // [**]: This can be proved by analyzing all the four possibilities: 9953 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9954 // (A s>= 0, B s>= 0). 9955 // 9956 // Note: 9957 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9958 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9959 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9960 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9961 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9962 // C)". 9963 9964 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9965 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9966 if (!LDiff || !RDiff || *LDiff != *RDiff) 9967 return false; 9968 9969 if (LDiff->isMinValue()) 9970 return true; 9971 9972 APInt FoundRHSLimit; 9973 9974 if (Pred == CmpInst::ICMP_ULT) { 9975 FoundRHSLimit = -(*RDiff); 9976 } else { 9977 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9978 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9979 } 9980 9981 // Try to prove (1) or (2), as needed. 9982 return isAvailableAtLoopEntry(FoundRHS, L) && 9983 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9984 getConstant(FoundRHSLimit)); 9985 } 9986 9987 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9988 const SCEV *LHS, const SCEV *RHS, 9989 const SCEV *FoundLHS, 9990 const SCEV *FoundRHS, unsigned Depth) { 9991 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9992 9993 auto ClearOnExit = make_scope_exit([&]() { 9994 if (LPhi) { 9995 bool Erased = PendingMerges.erase(LPhi); 9996 assert(Erased && "Failed to erase LPhi!"); 9997 (void)Erased; 9998 } 9999 if (RPhi) { 10000 bool Erased = PendingMerges.erase(RPhi); 10001 assert(Erased && "Failed to erase RPhi!"); 10002 (void)Erased; 10003 } 10004 }); 10005 10006 // Find respective Phis and check that they are not being pending. 10007 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10008 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10009 if (!PendingMerges.insert(Phi).second) 10010 return false; 10011 LPhi = Phi; 10012 } 10013 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10014 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10015 // If we detect a loop of Phi nodes being processed by this method, for 10016 // example: 10017 // 10018 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10019 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10020 // 10021 // we don't want to deal with a case that complex, so return conservative 10022 // answer false. 10023 if (!PendingMerges.insert(Phi).second) 10024 return false; 10025 RPhi = Phi; 10026 } 10027 10028 // If none of LHS, RHS is a Phi, nothing to do here. 10029 if (!LPhi && !RPhi) 10030 return false; 10031 10032 // If there is a SCEVUnknown Phi we are interested in, make it left. 10033 if (!LPhi) { 10034 std::swap(LHS, RHS); 10035 std::swap(FoundLHS, FoundRHS); 10036 std::swap(LPhi, RPhi); 10037 Pred = ICmpInst::getSwappedPredicate(Pred); 10038 } 10039 10040 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10041 const BasicBlock *LBB = LPhi->getParent(); 10042 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10043 10044 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10045 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10046 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10047 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10048 }; 10049 10050 if (RPhi && RPhi->getParent() == LBB) { 10051 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10052 // If we compare two Phis from the same block, and for each entry block 10053 // the predicate is true for incoming values from this block, then the 10054 // predicate is also true for the Phis. 10055 for (const BasicBlock *IncBB : predecessors(LBB)) { 10056 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10057 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10058 if (!ProvedEasily(L, R)) 10059 return false; 10060 } 10061 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10062 // Case two: RHS is also a Phi from the same basic block, and it is an 10063 // AddRec. It means that there is a loop which has both AddRec and Unknown 10064 // PHIs, for it we can compare incoming values of AddRec from above the loop 10065 // and latch with their respective incoming values of LPhi. 10066 // TODO: Generalize to handle loops with many inputs in a header. 10067 if (LPhi->getNumIncomingValues() != 2) return false; 10068 10069 auto *RLoop = RAR->getLoop(); 10070 auto *Predecessor = RLoop->getLoopPredecessor(); 10071 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10072 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10073 if (!ProvedEasily(L1, RAR->getStart())) 10074 return false; 10075 auto *Latch = RLoop->getLoopLatch(); 10076 assert(Latch && "Loop with AddRec with no latch?"); 10077 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10078 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10079 return false; 10080 } else { 10081 // In all other cases go over inputs of LHS and compare each of them to RHS, 10082 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10083 // At this point RHS is either a non-Phi, or it is a Phi from some block 10084 // different from LBB. 10085 for (const BasicBlock *IncBB : predecessors(LBB)) { 10086 // Check that RHS is available in this block. 10087 if (!dominates(RHS, IncBB)) 10088 return false; 10089 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10090 if (!ProvedEasily(L, RHS)) 10091 return false; 10092 } 10093 } 10094 return true; 10095 } 10096 10097 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10098 const SCEV *LHS, const SCEV *RHS, 10099 const SCEV *FoundLHS, 10100 const SCEV *FoundRHS) { 10101 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10102 return true; 10103 10104 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10105 return true; 10106 10107 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10108 FoundLHS, FoundRHS) || 10109 // ~x < ~y --> x > y 10110 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10111 getNotSCEV(FoundRHS), 10112 getNotSCEV(FoundLHS)); 10113 } 10114 10115 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10116 template <typename MinMaxExprType> 10117 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10118 const SCEV *Candidate) { 10119 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10120 if (!MinMaxExpr) 10121 return false; 10122 10123 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10124 } 10125 10126 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10127 ICmpInst::Predicate Pred, 10128 const SCEV *LHS, const SCEV *RHS) { 10129 // If both sides are affine addrecs for the same loop, with equal 10130 // steps, and we know the recurrences don't wrap, then we only 10131 // need to check the predicate on the starting values. 10132 10133 if (!ICmpInst::isRelational(Pred)) 10134 return false; 10135 10136 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10137 if (!LAR) 10138 return false; 10139 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10140 if (!RAR) 10141 return false; 10142 if (LAR->getLoop() != RAR->getLoop()) 10143 return false; 10144 if (!LAR->isAffine() || !RAR->isAffine()) 10145 return false; 10146 10147 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10148 return false; 10149 10150 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10151 SCEV::FlagNSW : SCEV::FlagNUW; 10152 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10153 return false; 10154 10155 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10156 } 10157 10158 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10159 /// expression? 10160 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10161 ICmpInst::Predicate Pred, 10162 const SCEV *LHS, const SCEV *RHS) { 10163 switch (Pred) { 10164 default: 10165 return false; 10166 10167 case ICmpInst::ICMP_SGE: 10168 std::swap(LHS, RHS); 10169 LLVM_FALLTHROUGH; 10170 case ICmpInst::ICMP_SLE: 10171 return 10172 // min(A, ...) <= A 10173 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10174 // A <= max(A, ...) 10175 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10176 10177 case ICmpInst::ICMP_UGE: 10178 std::swap(LHS, RHS); 10179 LLVM_FALLTHROUGH; 10180 case ICmpInst::ICMP_ULE: 10181 return 10182 // min(A, ...) <= A 10183 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10184 // A <= max(A, ...) 10185 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10186 } 10187 10188 llvm_unreachable("covered switch fell through?!"); 10189 } 10190 10191 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10192 const SCEV *LHS, const SCEV *RHS, 10193 const SCEV *FoundLHS, 10194 const SCEV *FoundRHS, 10195 unsigned Depth) { 10196 assert(getTypeSizeInBits(LHS->getType()) == 10197 getTypeSizeInBits(RHS->getType()) && 10198 "LHS and RHS have different sizes?"); 10199 assert(getTypeSizeInBits(FoundLHS->getType()) == 10200 getTypeSizeInBits(FoundRHS->getType()) && 10201 "FoundLHS and FoundRHS have different sizes?"); 10202 // We want to avoid hurting the compile time with analysis of too big trees. 10203 if (Depth > MaxSCEVOperationsImplicationDepth) 10204 return false; 10205 // We only want to work with ICMP_SGT comparison so far. 10206 // TODO: Extend to ICMP_UGT? 10207 if (Pred == ICmpInst::ICMP_SLT) { 10208 Pred = ICmpInst::ICMP_SGT; 10209 std::swap(LHS, RHS); 10210 std::swap(FoundLHS, FoundRHS); 10211 } 10212 if (Pred != ICmpInst::ICMP_SGT) 10213 return false; 10214 10215 auto GetOpFromSExt = [&](const SCEV *S) { 10216 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10217 return Ext->getOperand(); 10218 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10219 // the constant in some cases. 10220 return S; 10221 }; 10222 10223 // Acquire values from extensions. 10224 auto *OrigLHS = LHS; 10225 auto *OrigFoundLHS = FoundLHS; 10226 LHS = GetOpFromSExt(LHS); 10227 FoundLHS = GetOpFromSExt(FoundLHS); 10228 10229 // Is the SGT predicate can be proved trivially or using the found context. 10230 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10231 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10232 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10233 FoundRHS, Depth + 1); 10234 }; 10235 10236 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10237 // We want to avoid creation of any new non-constant SCEV. Since we are 10238 // going to compare the operands to RHS, we should be certain that we don't 10239 // need any size extensions for this. So let's decline all cases when the 10240 // sizes of types of LHS and RHS do not match. 10241 // TODO: Maybe try to get RHS from sext to catch more cases? 10242 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10243 return false; 10244 10245 // Should not overflow. 10246 if (!LHSAddExpr->hasNoSignedWrap()) 10247 return false; 10248 10249 auto *LL = LHSAddExpr->getOperand(0); 10250 auto *LR = LHSAddExpr->getOperand(1); 10251 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10252 10253 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10254 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10255 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10256 }; 10257 // Try to prove the following rule: 10258 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10259 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10260 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10261 return true; 10262 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10263 Value *LL, *LR; 10264 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10265 10266 using namespace llvm::PatternMatch; 10267 10268 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10269 // Rules for division. 10270 // We are going to perform some comparisons with Denominator and its 10271 // derivative expressions. In general case, creating a SCEV for it may 10272 // lead to a complex analysis of the entire graph, and in particular it 10273 // can request trip count recalculation for the same loop. This would 10274 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10275 // this, we only want to create SCEVs that are constants in this section. 10276 // So we bail if Denominator is not a constant. 10277 if (!isa<ConstantInt>(LR)) 10278 return false; 10279 10280 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10281 10282 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10283 // then a SCEV for the numerator already exists and matches with FoundLHS. 10284 auto *Numerator = getExistingSCEV(LL); 10285 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10286 return false; 10287 10288 // Make sure that the numerator matches with FoundLHS and the denominator 10289 // is positive. 10290 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10291 return false; 10292 10293 auto *DTy = Denominator->getType(); 10294 auto *FRHSTy = FoundRHS->getType(); 10295 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10296 // One of types is a pointer and another one is not. We cannot extend 10297 // them properly to a wider type, so let us just reject this case. 10298 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10299 // to avoid this check. 10300 return false; 10301 10302 // Given that: 10303 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10304 auto *WTy = getWiderType(DTy, FRHSTy); 10305 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10306 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10307 10308 // Try to prove the following rule: 10309 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10310 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10311 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10312 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10313 if (isKnownNonPositive(RHS) && 10314 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10315 return true; 10316 10317 // Try to prove the following rule: 10318 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10319 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10320 // If we divide it by Denominator > 2, then: 10321 // 1. If FoundLHS is negative, then the result is 0. 10322 // 2. If FoundLHS is non-negative, then the result is non-negative. 10323 // Anyways, the result is non-negative. 10324 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10325 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10326 if (isKnownNegative(RHS) && 10327 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10328 return true; 10329 } 10330 } 10331 10332 // If our expression contained SCEVUnknown Phis, and we split it down and now 10333 // need to prove something for them, try to prove the predicate for every 10334 // possible incoming values of those Phis. 10335 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10336 return true; 10337 10338 return false; 10339 } 10340 10341 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10342 const SCEV *LHS, const SCEV *RHS) { 10343 // zext x u<= sext x, sext x s<= zext x 10344 switch (Pred) { 10345 case ICmpInst::ICMP_SGE: 10346 std::swap(LHS, RHS); 10347 LLVM_FALLTHROUGH; 10348 case ICmpInst::ICMP_SLE: { 10349 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10350 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10351 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10352 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10353 return true; 10354 break; 10355 } 10356 case ICmpInst::ICMP_UGE: 10357 std::swap(LHS, RHS); 10358 LLVM_FALLTHROUGH; 10359 case ICmpInst::ICMP_ULE: { 10360 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10361 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10362 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10363 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10364 return true; 10365 break; 10366 } 10367 default: 10368 break; 10369 }; 10370 return false; 10371 } 10372 10373 bool 10374 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10375 const SCEV *LHS, const SCEV *RHS) { 10376 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10377 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10378 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10379 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10380 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10381 } 10382 10383 bool 10384 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10385 const SCEV *LHS, const SCEV *RHS, 10386 const SCEV *FoundLHS, 10387 const SCEV *FoundRHS) { 10388 switch (Pred) { 10389 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10390 case ICmpInst::ICMP_EQ: 10391 case ICmpInst::ICMP_NE: 10392 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10393 return true; 10394 break; 10395 case ICmpInst::ICMP_SLT: 10396 case ICmpInst::ICMP_SLE: 10397 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10398 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10399 return true; 10400 break; 10401 case ICmpInst::ICMP_SGT: 10402 case ICmpInst::ICMP_SGE: 10403 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10404 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10405 return true; 10406 break; 10407 case ICmpInst::ICMP_ULT: 10408 case ICmpInst::ICMP_ULE: 10409 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10410 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10411 return true; 10412 break; 10413 case ICmpInst::ICMP_UGT: 10414 case ICmpInst::ICMP_UGE: 10415 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10416 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10417 return true; 10418 break; 10419 } 10420 10421 // Maybe it can be proved via operations? 10422 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10423 return true; 10424 10425 return false; 10426 } 10427 10428 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10429 const SCEV *LHS, 10430 const SCEV *RHS, 10431 const SCEV *FoundLHS, 10432 const SCEV *FoundRHS) { 10433 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10434 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10435 // reduce the compile time impact of this optimization. 10436 return false; 10437 10438 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10439 if (!Addend) 10440 return false; 10441 10442 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10443 10444 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10445 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10446 ConstantRange FoundLHSRange = 10447 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10448 10449 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10450 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10451 10452 // We can also compute the range of values for `LHS` that satisfy the 10453 // consequent, "`LHS` `Pred` `RHS`": 10454 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10455 ConstantRange SatisfyingLHSRange = 10456 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10457 10458 // The antecedent implies the consequent if every value of `LHS` that 10459 // satisfies the antecedent also satisfies the consequent. 10460 return SatisfyingLHSRange.contains(LHSRange); 10461 } 10462 10463 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10464 bool IsSigned, bool NoWrap) { 10465 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10466 10467 if (NoWrap) return false; 10468 10469 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10470 const SCEV *One = getOne(Stride->getType()); 10471 10472 if (IsSigned) { 10473 APInt MaxRHS = getSignedRangeMax(RHS); 10474 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10475 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10476 10477 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10478 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10479 } 10480 10481 APInt MaxRHS = getUnsignedRangeMax(RHS); 10482 APInt MaxValue = APInt::getMaxValue(BitWidth); 10483 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10484 10485 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10486 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10487 } 10488 10489 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10490 bool IsSigned, bool NoWrap) { 10491 if (NoWrap) return false; 10492 10493 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10494 const SCEV *One = getOne(Stride->getType()); 10495 10496 if (IsSigned) { 10497 APInt MinRHS = getSignedRangeMin(RHS); 10498 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10499 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10500 10501 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10502 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10503 } 10504 10505 APInt MinRHS = getUnsignedRangeMin(RHS); 10506 APInt MinValue = APInt::getMinValue(BitWidth); 10507 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10508 10509 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10510 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10511 } 10512 10513 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10514 bool Equality) { 10515 const SCEV *One = getOne(Step->getType()); 10516 Delta = Equality ? getAddExpr(Delta, Step) 10517 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10518 return getUDivExpr(Delta, Step); 10519 } 10520 10521 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10522 const SCEV *Stride, 10523 const SCEV *End, 10524 unsigned BitWidth, 10525 bool IsSigned) { 10526 10527 assert(!isKnownNonPositive(Stride) && 10528 "Stride is expected strictly positive!"); 10529 // Calculate the maximum backedge count based on the range of values 10530 // permitted by Start, End, and Stride. 10531 const SCEV *MaxBECount; 10532 APInt MinStart = 10533 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10534 10535 APInt StrideForMaxBECount = 10536 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10537 10538 // We already know that the stride is positive, so we paper over conservatism 10539 // in our range computation by forcing StrideForMaxBECount to be at least one. 10540 // In theory this is unnecessary, but we expect MaxBECount to be a 10541 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10542 // is nothing to constant fold it to). 10543 APInt One(BitWidth, 1, IsSigned); 10544 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10545 10546 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10547 : APInt::getMaxValue(BitWidth); 10548 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10549 10550 // Although End can be a MAX expression we estimate MaxEnd considering only 10551 // the case End = RHS of the loop termination condition. This is safe because 10552 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10553 // taken count. 10554 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10555 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10556 10557 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10558 getConstant(StrideForMaxBECount) /* Step */, 10559 false /* Equality */); 10560 10561 return MaxBECount; 10562 } 10563 10564 ScalarEvolution::ExitLimit 10565 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10566 const Loop *L, bool IsSigned, 10567 bool ControlsExit, bool AllowPredicates) { 10568 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10569 10570 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10571 bool PredicatedIV = false; 10572 10573 if (!IV && AllowPredicates) { 10574 // Try to make this an AddRec using runtime tests, in the first X 10575 // iterations of this loop, where X is the SCEV expression found by the 10576 // algorithm below. 10577 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10578 PredicatedIV = true; 10579 } 10580 10581 // Avoid weird loops 10582 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10583 return getCouldNotCompute(); 10584 10585 bool NoWrap = ControlsExit && 10586 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10587 10588 const SCEV *Stride = IV->getStepRecurrence(*this); 10589 10590 bool PositiveStride = isKnownPositive(Stride); 10591 10592 // Avoid negative or zero stride values. 10593 if (!PositiveStride) { 10594 // We can compute the correct backedge taken count for loops with unknown 10595 // strides if we can prove that the loop is not an infinite loop with side 10596 // effects. Here's the loop structure we are trying to handle - 10597 // 10598 // i = start 10599 // do { 10600 // A[i] = i; 10601 // i += s; 10602 // } while (i < end); 10603 // 10604 // The backedge taken count for such loops is evaluated as - 10605 // (max(end, start + stride) - start - 1) /u stride 10606 // 10607 // The additional preconditions that we need to check to prove correctness 10608 // of the above formula is as follows - 10609 // 10610 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10611 // NoWrap flag). 10612 // b) loop is single exit with no side effects. 10613 // 10614 // 10615 // Precondition a) implies that if the stride is negative, this is a single 10616 // trip loop. The backedge taken count formula reduces to zero in this case. 10617 // 10618 // Precondition b) implies that the unknown stride cannot be zero otherwise 10619 // we have UB. 10620 // 10621 // The positive stride case is the same as isKnownPositive(Stride) returning 10622 // true (original behavior of the function). 10623 // 10624 // We want to make sure that the stride is truly unknown as there are edge 10625 // cases where ScalarEvolution propagates no wrap flags to the 10626 // post-increment/decrement IV even though the increment/decrement operation 10627 // itself is wrapping. The computed backedge taken count may be wrong in 10628 // such cases. This is prevented by checking that the stride is not known to 10629 // be either positive or non-positive. For example, no wrap flags are 10630 // propagated to the post-increment IV of this loop with a trip count of 2 - 10631 // 10632 // unsigned char i; 10633 // for(i=127; i<128; i+=129) 10634 // A[i] = i; 10635 // 10636 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10637 !loopHasNoSideEffects(L)) 10638 return getCouldNotCompute(); 10639 } else if (!Stride->isOne() && 10640 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10641 // Avoid proven overflow cases: this will ensure that the backedge taken 10642 // count will not generate any unsigned overflow. Relaxed no-overflow 10643 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10644 // undefined behaviors like the case of C language. 10645 return getCouldNotCompute(); 10646 10647 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10648 : ICmpInst::ICMP_ULT; 10649 const SCEV *Start = IV->getStart(); 10650 const SCEV *End = RHS; 10651 // When the RHS is not invariant, we do not know the end bound of the loop and 10652 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10653 // calculate the MaxBECount, given the start, stride and max value for the end 10654 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10655 // checked above). 10656 if (!isLoopInvariant(RHS, L)) { 10657 const SCEV *MaxBECount = computeMaxBECountForLT( 10658 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10659 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10660 false /*MaxOrZero*/, Predicates); 10661 } 10662 // If the backedge is taken at least once, then it will be taken 10663 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10664 // is the LHS value of the less-than comparison the first time it is evaluated 10665 // and End is the RHS. 10666 const SCEV *BECountIfBackedgeTaken = 10667 computeBECount(getMinusSCEV(End, Start), Stride, false); 10668 // If the loop entry is guarded by the result of the backedge test of the 10669 // first loop iteration, then we know the backedge will be taken at least 10670 // once and so the backedge taken count is as above. If not then we use the 10671 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10672 // as if the backedge is taken at least once max(End,Start) is End and so the 10673 // result is as above, and if not max(End,Start) is Start so we get a backedge 10674 // count of zero. 10675 const SCEV *BECount; 10676 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10677 BECount = BECountIfBackedgeTaken; 10678 else { 10679 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10680 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10681 } 10682 10683 const SCEV *MaxBECount; 10684 bool MaxOrZero = false; 10685 if (isa<SCEVConstant>(BECount)) 10686 MaxBECount = BECount; 10687 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10688 // If we know exactly how many times the backedge will be taken if it's 10689 // taken at least once, then the backedge count will either be that or 10690 // zero. 10691 MaxBECount = BECountIfBackedgeTaken; 10692 MaxOrZero = true; 10693 } else { 10694 MaxBECount = computeMaxBECountForLT( 10695 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10696 } 10697 10698 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10699 !isa<SCEVCouldNotCompute>(BECount)) 10700 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10701 10702 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10703 } 10704 10705 ScalarEvolution::ExitLimit 10706 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10707 const Loop *L, bool IsSigned, 10708 bool ControlsExit, bool AllowPredicates) { 10709 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10710 // We handle only IV > Invariant 10711 if (!isLoopInvariant(RHS, L)) 10712 return getCouldNotCompute(); 10713 10714 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10715 if (!IV && AllowPredicates) 10716 // Try to make this an AddRec using runtime tests, in the first X 10717 // iterations of this loop, where X is the SCEV expression found by the 10718 // algorithm below. 10719 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10720 10721 // Avoid weird loops 10722 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10723 return getCouldNotCompute(); 10724 10725 bool NoWrap = ControlsExit && 10726 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10727 10728 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10729 10730 // Avoid negative or zero stride values 10731 if (!isKnownPositive(Stride)) 10732 return getCouldNotCompute(); 10733 10734 // Avoid proven overflow cases: this will ensure that the backedge taken count 10735 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10736 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10737 // behaviors like the case of C language. 10738 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10739 return getCouldNotCompute(); 10740 10741 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10742 : ICmpInst::ICMP_UGT; 10743 10744 const SCEV *Start = IV->getStart(); 10745 const SCEV *End = RHS; 10746 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10747 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10748 10749 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10750 10751 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10752 : getUnsignedRangeMax(Start); 10753 10754 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10755 : getUnsignedRangeMin(Stride); 10756 10757 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10758 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10759 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10760 10761 // Although End can be a MIN expression we estimate MinEnd considering only 10762 // the case End = RHS. This is safe because in the other case (Start - End) 10763 // is zero, leading to a zero maximum backedge taken count. 10764 APInt MinEnd = 10765 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10766 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10767 10768 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10769 ? BECount 10770 : computeBECount(getConstant(MaxStart - MinEnd), 10771 getConstant(MinStride), false); 10772 10773 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10774 MaxBECount = BECount; 10775 10776 return ExitLimit(BECount, MaxBECount, false, Predicates); 10777 } 10778 10779 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10780 ScalarEvolution &SE) const { 10781 if (Range.isFullSet()) // Infinite loop. 10782 return SE.getCouldNotCompute(); 10783 10784 // If the start is a non-zero constant, shift the range to simplify things. 10785 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10786 if (!SC->getValue()->isZero()) { 10787 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10788 Operands[0] = SE.getZero(SC->getType()); 10789 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10790 getNoWrapFlags(FlagNW)); 10791 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10792 return ShiftedAddRec->getNumIterationsInRange( 10793 Range.subtract(SC->getAPInt()), SE); 10794 // This is strange and shouldn't happen. 10795 return SE.getCouldNotCompute(); 10796 } 10797 10798 // The only time we can solve this is when we have all constant indices. 10799 // Otherwise, we cannot determine the overflow conditions. 10800 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10801 return SE.getCouldNotCompute(); 10802 10803 // Okay at this point we know that all elements of the chrec are constants and 10804 // that the start element is zero. 10805 10806 // First check to see if the range contains zero. If not, the first 10807 // iteration exits. 10808 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10809 if (!Range.contains(APInt(BitWidth, 0))) 10810 return SE.getZero(getType()); 10811 10812 if (isAffine()) { 10813 // If this is an affine expression then we have this situation: 10814 // Solve {0,+,A} in Range === Ax in Range 10815 10816 // We know that zero is in the range. If A is positive then we know that 10817 // the upper value of the range must be the first possible exit value. 10818 // If A is negative then the lower of the range is the last possible loop 10819 // value. Also note that we already checked for a full range. 10820 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10821 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10822 10823 // The exit value should be (End+A)/A. 10824 APInt ExitVal = (End + A).udiv(A); 10825 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10826 10827 // Evaluate at the exit value. If we really did fall out of the valid 10828 // range, then we computed our trip count, otherwise wrap around or other 10829 // things must have happened. 10830 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10831 if (Range.contains(Val->getValue())) 10832 return SE.getCouldNotCompute(); // Something strange happened 10833 10834 // Ensure that the previous value is in the range. This is a sanity check. 10835 assert(Range.contains( 10836 EvaluateConstantChrecAtConstant(this, 10837 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10838 "Linear scev computation is off in a bad way!"); 10839 return SE.getConstant(ExitValue); 10840 } 10841 10842 if (isQuadratic()) { 10843 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10844 return SE.getConstant(S.getValue()); 10845 } 10846 10847 return SE.getCouldNotCompute(); 10848 } 10849 10850 const SCEVAddRecExpr * 10851 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10852 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10853 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10854 // but in this case we cannot guarantee that the value returned will be an 10855 // AddRec because SCEV does not have a fixed point where it stops 10856 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10857 // may happen if we reach arithmetic depth limit while simplifying. So we 10858 // construct the returned value explicitly. 10859 SmallVector<const SCEV *, 3> Ops; 10860 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10861 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10862 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10863 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10864 // We know that the last operand is not a constant zero (otherwise it would 10865 // have been popped out earlier). This guarantees us that if the result has 10866 // the same last operand, then it will also not be popped out, meaning that 10867 // the returned value will be an AddRec. 10868 const SCEV *Last = getOperand(getNumOperands() - 1); 10869 assert(!Last->isZero() && "Recurrency with zero step?"); 10870 Ops.push_back(Last); 10871 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10872 SCEV::FlagAnyWrap)); 10873 } 10874 10875 // Return true when S contains at least an undef value. 10876 static inline bool containsUndefs(const SCEV *S) { 10877 return SCEVExprContains(S, [](const SCEV *S) { 10878 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10879 return isa<UndefValue>(SU->getValue()); 10880 return false; 10881 }); 10882 } 10883 10884 namespace { 10885 10886 // Collect all steps of SCEV expressions. 10887 struct SCEVCollectStrides { 10888 ScalarEvolution &SE; 10889 SmallVectorImpl<const SCEV *> &Strides; 10890 10891 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10892 : SE(SE), Strides(S) {} 10893 10894 bool follow(const SCEV *S) { 10895 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10896 Strides.push_back(AR->getStepRecurrence(SE)); 10897 return true; 10898 } 10899 10900 bool isDone() const { return false; } 10901 }; 10902 10903 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10904 struct SCEVCollectTerms { 10905 SmallVectorImpl<const SCEV *> &Terms; 10906 10907 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10908 10909 bool follow(const SCEV *S) { 10910 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10911 isa<SCEVSignExtendExpr>(S)) { 10912 if (!containsUndefs(S)) 10913 Terms.push_back(S); 10914 10915 // Stop recursion: once we collected a term, do not walk its operands. 10916 return false; 10917 } 10918 10919 // Keep looking. 10920 return true; 10921 } 10922 10923 bool isDone() const { return false; } 10924 }; 10925 10926 // Check if a SCEV contains an AddRecExpr. 10927 struct SCEVHasAddRec { 10928 bool &ContainsAddRec; 10929 10930 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10931 ContainsAddRec = false; 10932 } 10933 10934 bool follow(const SCEV *S) { 10935 if (isa<SCEVAddRecExpr>(S)) { 10936 ContainsAddRec = true; 10937 10938 // Stop recursion: once we collected a term, do not walk its operands. 10939 return false; 10940 } 10941 10942 // Keep looking. 10943 return true; 10944 } 10945 10946 bool isDone() const { return false; } 10947 }; 10948 10949 // Find factors that are multiplied with an expression that (possibly as a 10950 // subexpression) contains an AddRecExpr. In the expression: 10951 // 10952 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10953 // 10954 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10955 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10956 // parameters as they form a product with an induction variable. 10957 // 10958 // This collector expects all array size parameters to be in the same MulExpr. 10959 // It might be necessary to later add support for collecting parameters that are 10960 // spread over different nested MulExpr. 10961 struct SCEVCollectAddRecMultiplies { 10962 SmallVectorImpl<const SCEV *> &Terms; 10963 ScalarEvolution &SE; 10964 10965 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10966 : Terms(T), SE(SE) {} 10967 10968 bool follow(const SCEV *S) { 10969 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10970 bool HasAddRec = false; 10971 SmallVector<const SCEV *, 0> Operands; 10972 for (auto Op : Mul->operands()) { 10973 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10974 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10975 Operands.push_back(Op); 10976 } else if (Unknown) { 10977 HasAddRec = true; 10978 } else { 10979 bool ContainsAddRec; 10980 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10981 visitAll(Op, ContiansAddRec); 10982 HasAddRec |= ContainsAddRec; 10983 } 10984 } 10985 if (Operands.size() == 0) 10986 return true; 10987 10988 if (!HasAddRec) 10989 return false; 10990 10991 Terms.push_back(SE.getMulExpr(Operands)); 10992 // Stop recursion: once we collected a term, do not walk its operands. 10993 return false; 10994 } 10995 10996 // Keep looking. 10997 return true; 10998 } 10999 11000 bool isDone() const { return false; } 11001 }; 11002 11003 } // end anonymous namespace 11004 11005 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11006 /// two places: 11007 /// 1) The strides of AddRec expressions. 11008 /// 2) Unknowns that are multiplied with AddRec expressions. 11009 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11010 SmallVectorImpl<const SCEV *> &Terms) { 11011 SmallVector<const SCEV *, 4> Strides; 11012 SCEVCollectStrides StrideCollector(*this, Strides); 11013 visitAll(Expr, StrideCollector); 11014 11015 LLVM_DEBUG({ 11016 dbgs() << "Strides:\n"; 11017 for (const SCEV *S : Strides) 11018 dbgs() << *S << "\n"; 11019 }); 11020 11021 for (const SCEV *S : Strides) { 11022 SCEVCollectTerms TermCollector(Terms); 11023 visitAll(S, TermCollector); 11024 } 11025 11026 LLVM_DEBUG({ 11027 dbgs() << "Terms:\n"; 11028 for (const SCEV *T : Terms) 11029 dbgs() << *T << "\n"; 11030 }); 11031 11032 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11033 visitAll(Expr, MulCollector); 11034 } 11035 11036 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11037 SmallVectorImpl<const SCEV *> &Terms, 11038 SmallVectorImpl<const SCEV *> &Sizes) { 11039 int Last = Terms.size() - 1; 11040 const SCEV *Step = Terms[Last]; 11041 11042 // End of recursion. 11043 if (Last == 0) { 11044 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11045 SmallVector<const SCEV *, 2> Qs; 11046 for (const SCEV *Op : M->operands()) 11047 if (!isa<SCEVConstant>(Op)) 11048 Qs.push_back(Op); 11049 11050 Step = SE.getMulExpr(Qs); 11051 } 11052 11053 Sizes.push_back(Step); 11054 return true; 11055 } 11056 11057 for (const SCEV *&Term : Terms) { 11058 // Normalize the terms before the next call to findArrayDimensionsRec. 11059 const SCEV *Q, *R; 11060 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11061 11062 // Bail out when GCD does not evenly divide one of the terms. 11063 if (!R->isZero()) 11064 return false; 11065 11066 Term = Q; 11067 } 11068 11069 // Remove all SCEVConstants. 11070 Terms.erase( 11071 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11072 Terms.end()); 11073 11074 if (Terms.size() > 0) 11075 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11076 return false; 11077 11078 Sizes.push_back(Step); 11079 return true; 11080 } 11081 11082 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11083 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11084 for (const SCEV *T : Terms) 11085 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11086 return true; 11087 return false; 11088 } 11089 11090 // Return the number of product terms in S. 11091 static inline int numberOfTerms(const SCEV *S) { 11092 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11093 return Expr->getNumOperands(); 11094 return 1; 11095 } 11096 11097 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11098 if (isa<SCEVConstant>(T)) 11099 return nullptr; 11100 11101 if (isa<SCEVUnknown>(T)) 11102 return T; 11103 11104 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11105 SmallVector<const SCEV *, 2> Factors; 11106 for (const SCEV *Op : M->operands()) 11107 if (!isa<SCEVConstant>(Op)) 11108 Factors.push_back(Op); 11109 11110 return SE.getMulExpr(Factors); 11111 } 11112 11113 return T; 11114 } 11115 11116 /// Return the size of an element read or written by Inst. 11117 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11118 Type *Ty; 11119 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11120 Ty = Store->getValueOperand()->getType(); 11121 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11122 Ty = Load->getType(); 11123 else 11124 return nullptr; 11125 11126 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11127 return getSizeOfExpr(ETy, Ty); 11128 } 11129 11130 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11131 SmallVectorImpl<const SCEV *> &Sizes, 11132 const SCEV *ElementSize) { 11133 if (Terms.size() < 1 || !ElementSize) 11134 return; 11135 11136 // Early return when Terms do not contain parameters: we do not delinearize 11137 // non parametric SCEVs. 11138 if (!containsParameters(Terms)) 11139 return; 11140 11141 LLVM_DEBUG({ 11142 dbgs() << "Terms:\n"; 11143 for (const SCEV *T : Terms) 11144 dbgs() << *T << "\n"; 11145 }); 11146 11147 // Remove duplicates. 11148 array_pod_sort(Terms.begin(), Terms.end()); 11149 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11150 11151 // Put larger terms first. 11152 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11153 return numberOfTerms(LHS) > numberOfTerms(RHS); 11154 }); 11155 11156 // Try to divide all terms by the element size. If term is not divisible by 11157 // element size, proceed with the original term. 11158 for (const SCEV *&Term : Terms) { 11159 const SCEV *Q, *R; 11160 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11161 if (!Q->isZero()) 11162 Term = Q; 11163 } 11164 11165 SmallVector<const SCEV *, 4> NewTerms; 11166 11167 // Remove constant factors. 11168 for (const SCEV *T : Terms) 11169 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11170 NewTerms.push_back(NewT); 11171 11172 LLVM_DEBUG({ 11173 dbgs() << "Terms after sorting:\n"; 11174 for (const SCEV *T : NewTerms) 11175 dbgs() << *T << "\n"; 11176 }); 11177 11178 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11179 Sizes.clear(); 11180 return; 11181 } 11182 11183 // The last element to be pushed into Sizes is the size of an element. 11184 Sizes.push_back(ElementSize); 11185 11186 LLVM_DEBUG({ 11187 dbgs() << "Sizes:\n"; 11188 for (const SCEV *S : Sizes) 11189 dbgs() << *S << "\n"; 11190 }); 11191 } 11192 11193 void ScalarEvolution::computeAccessFunctions( 11194 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11195 SmallVectorImpl<const SCEV *> &Sizes) { 11196 // Early exit in case this SCEV is not an affine multivariate function. 11197 if (Sizes.empty()) 11198 return; 11199 11200 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11201 if (!AR->isAffine()) 11202 return; 11203 11204 const SCEV *Res = Expr; 11205 int Last = Sizes.size() - 1; 11206 for (int i = Last; i >= 0; i--) { 11207 const SCEV *Q, *R; 11208 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11209 11210 LLVM_DEBUG({ 11211 dbgs() << "Res: " << *Res << "\n"; 11212 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11213 dbgs() << "Res divided by Sizes[i]:\n"; 11214 dbgs() << "Quotient: " << *Q << "\n"; 11215 dbgs() << "Remainder: " << *R << "\n"; 11216 }); 11217 11218 Res = Q; 11219 11220 // Do not record the last subscript corresponding to the size of elements in 11221 // the array. 11222 if (i == Last) { 11223 11224 // Bail out if the remainder is too complex. 11225 if (isa<SCEVAddRecExpr>(R)) { 11226 Subscripts.clear(); 11227 Sizes.clear(); 11228 return; 11229 } 11230 11231 continue; 11232 } 11233 11234 // Record the access function for the current subscript. 11235 Subscripts.push_back(R); 11236 } 11237 11238 // Also push in last position the remainder of the last division: it will be 11239 // the access function of the innermost dimension. 11240 Subscripts.push_back(Res); 11241 11242 std::reverse(Subscripts.begin(), Subscripts.end()); 11243 11244 LLVM_DEBUG({ 11245 dbgs() << "Subscripts:\n"; 11246 for (const SCEV *S : Subscripts) 11247 dbgs() << *S << "\n"; 11248 }); 11249 } 11250 11251 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11252 /// sizes of an array access. Returns the remainder of the delinearization that 11253 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11254 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11255 /// expressions in the stride and base of a SCEV corresponding to the 11256 /// computation of a GCD (greatest common divisor) of base and stride. When 11257 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11258 /// 11259 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11260 /// 11261 /// void foo(long n, long m, long o, double A[n][m][o]) { 11262 /// 11263 /// for (long i = 0; i < n; i++) 11264 /// for (long j = 0; j < m; j++) 11265 /// for (long k = 0; k < o; k++) 11266 /// A[i][j][k] = 1.0; 11267 /// } 11268 /// 11269 /// the delinearization input is the following AddRec SCEV: 11270 /// 11271 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11272 /// 11273 /// From this SCEV, we are able to say that the base offset of the access is %A 11274 /// because it appears as an offset that does not divide any of the strides in 11275 /// the loops: 11276 /// 11277 /// CHECK: Base offset: %A 11278 /// 11279 /// and then SCEV->delinearize determines the size of some of the dimensions of 11280 /// the array as these are the multiples by which the strides are happening: 11281 /// 11282 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11283 /// 11284 /// Note that the outermost dimension remains of UnknownSize because there are 11285 /// no strides that would help identifying the size of the last dimension: when 11286 /// the array has been statically allocated, one could compute the size of that 11287 /// dimension by dividing the overall size of the array by the size of the known 11288 /// dimensions: %m * %o * 8. 11289 /// 11290 /// Finally delinearize provides the access functions for the array reference 11291 /// that does correspond to A[i][j][k] of the above C testcase: 11292 /// 11293 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11294 /// 11295 /// The testcases are checking the output of a function pass: 11296 /// DelinearizationPass that walks through all loads and stores of a function 11297 /// asking for the SCEV of the memory access with respect to all enclosing 11298 /// loops, calling SCEV->delinearize on that and printing the results. 11299 void ScalarEvolution::delinearize(const SCEV *Expr, 11300 SmallVectorImpl<const SCEV *> &Subscripts, 11301 SmallVectorImpl<const SCEV *> &Sizes, 11302 const SCEV *ElementSize) { 11303 // First step: collect parametric terms. 11304 SmallVector<const SCEV *, 4> Terms; 11305 collectParametricTerms(Expr, Terms); 11306 11307 if (Terms.empty()) 11308 return; 11309 11310 // Second step: find subscript sizes. 11311 findArrayDimensions(Terms, Sizes, ElementSize); 11312 11313 if (Sizes.empty()) 11314 return; 11315 11316 // Third step: compute the access functions for each subscript. 11317 computeAccessFunctions(Expr, Subscripts, Sizes); 11318 11319 if (Subscripts.empty()) 11320 return; 11321 11322 LLVM_DEBUG({ 11323 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11324 dbgs() << "ArrayDecl[UnknownSize]"; 11325 for (const SCEV *S : Sizes) 11326 dbgs() << "[" << *S << "]"; 11327 11328 dbgs() << "\nArrayRef"; 11329 for (const SCEV *S : Subscripts) 11330 dbgs() << "[" << *S << "]"; 11331 dbgs() << "\n"; 11332 }); 11333 } 11334 11335 //===----------------------------------------------------------------------===// 11336 // SCEVCallbackVH Class Implementation 11337 //===----------------------------------------------------------------------===// 11338 11339 void ScalarEvolution::SCEVCallbackVH::deleted() { 11340 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11341 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11342 SE->ConstantEvolutionLoopExitValue.erase(PN); 11343 SE->eraseValueFromMap(getValPtr()); 11344 // this now dangles! 11345 } 11346 11347 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11348 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11349 11350 // Forget all the expressions associated with users of the old value, 11351 // so that future queries will recompute the expressions using the new 11352 // value. 11353 Value *Old = getValPtr(); 11354 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11355 SmallPtrSet<User *, 8> Visited; 11356 while (!Worklist.empty()) { 11357 User *U = Worklist.pop_back_val(); 11358 // Deleting the Old value will cause this to dangle. Postpone 11359 // that until everything else is done. 11360 if (U == Old) 11361 continue; 11362 if (!Visited.insert(U).second) 11363 continue; 11364 if (PHINode *PN = dyn_cast<PHINode>(U)) 11365 SE->ConstantEvolutionLoopExitValue.erase(PN); 11366 SE->eraseValueFromMap(U); 11367 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11368 } 11369 // Delete the Old value. 11370 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11371 SE->ConstantEvolutionLoopExitValue.erase(PN); 11372 SE->eraseValueFromMap(Old); 11373 // this now dangles! 11374 } 11375 11376 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11377 : CallbackVH(V), SE(se) {} 11378 11379 //===----------------------------------------------------------------------===// 11380 // ScalarEvolution Class Implementation 11381 //===----------------------------------------------------------------------===// 11382 11383 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11384 AssumptionCache &AC, DominatorTree &DT, 11385 LoopInfo &LI) 11386 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11387 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11388 LoopDispositions(64), BlockDispositions(64) { 11389 // To use guards for proving predicates, we need to scan every instruction in 11390 // relevant basic blocks, and not just terminators. Doing this is a waste of 11391 // time if the IR does not actually contain any calls to 11392 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11393 // 11394 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11395 // to _add_ guards to the module when there weren't any before, and wants 11396 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11397 // efficient in lieu of being smart in that rather obscure case. 11398 11399 auto *GuardDecl = F.getParent()->getFunction( 11400 Intrinsic::getName(Intrinsic::experimental_guard)); 11401 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11402 } 11403 11404 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11405 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11406 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11407 ValueExprMap(std::move(Arg.ValueExprMap)), 11408 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11409 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11410 PendingMerges(std::move(Arg.PendingMerges)), 11411 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11412 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11413 PredicatedBackedgeTakenCounts( 11414 std::move(Arg.PredicatedBackedgeTakenCounts)), 11415 ConstantEvolutionLoopExitValue( 11416 std::move(Arg.ConstantEvolutionLoopExitValue)), 11417 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11418 LoopDispositions(std::move(Arg.LoopDispositions)), 11419 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11420 BlockDispositions(std::move(Arg.BlockDispositions)), 11421 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11422 SignedRanges(std::move(Arg.SignedRanges)), 11423 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11424 UniquePreds(std::move(Arg.UniquePreds)), 11425 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11426 LoopUsers(std::move(Arg.LoopUsers)), 11427 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11428 FirstUnknown(Arg.FirstUnknown) { 11429 Arg.FirstUnknown = nullptr; 11430 } 11431 11432 ScalarEvolution::~ScalarEvolution() { 11433 // Iterate through all the SCEVUnknown instances and call their 11434 // destructors, so that they release their references to their values. 11435 for (SCEVUnknown *U = FirstUnknown; U;) { 11436 SCEVUnknown *Tmp = U; 11437 U = U->Next; 11438 Tmp->~SCEVUnknown(); 11439 } 11440 FirstUnknown = nullptr; 11441 11442 ExprValueMap.clear(); 11443 ValueExprMap.clear(); 11444 HasRecMap.clear(); 11445 11446 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11447 // that a loop had multiple computable exits. 11448 for (auto &BTCI : BackedgeTakenCounts) 11449 BTCI.second.clear(); 11450 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11451 BTCI.second.clear(); 11452 11453 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11454 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11455 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11456 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11457 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11458 } 11459 11460 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11461 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11462 } 11463 11464 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11465 const Loop *L) { 11466 // Print all inner loops first 11467 for (Loop *I : *L) 11468 PrintLoopInfo(OS, SE, I); 11469 11470 OS << "Loop "; 11471 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11472 OS << ": "; 11473 11474 SmallVector<BasicBlock *, 8> ExitingBlocks; 11475 L->getExitingBlocks(ExitingBlocks); 11476 if (ExitingBlocks.size() != 1) 11477 OS << "<multiple exits> "; 11478 11479 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11480 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11481 else 11482 OS << "Unpredictable backedge-taken count.\n"; 11483 11484 if (ExitingBlocks.size() > 1) 11485 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11486 OS << " exit count for " << ExitingBlock->getName() << ": " 11487 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11488 } 11489 11490 OS << "Loop "; 11491 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11492 OS << ": "; 11493 11494 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11495 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11496 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11497 OS << ", actual taken count either this or zero."; 11498 } else { 11499 OS << "Unpredictable max backedge-taken count. "; 11500 } 11501 11502 OS << "\n" 11503 "Loop "; 11504 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11505 OS << ": "; 11506 11507 SCEVUnionPredicate Pred; 11508 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11509 if (!isa<SCEVCouldNotCompute>(PBT)) { 11510 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11511 OS << " Predicates:\n"; 11512 Pred.print(OS, 4); 11513 } else { 11514 OS << "Unpredictable predicated backedge-taken count. "; 11515 } 11516 OS << "\n"; 11517 11518 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11519 OS << "Loop "; 11520 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11521 OS << ": "; 11522 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11523 } 11524 } 11525 11526 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11527 switch (LD) { 11528 case ScalarEvolution::LoopVariant: 11529 return "Variant"; 11530 case ScalarEvolution::LoopInvariant: 11531 return "Invariant"; 11532 case ScalarEvolution::LoopComputable: 11533 return "Computable"; 11534 } 11535 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11536 } 11537 11538 void ScalarEvolution::print(raw_ostream &OS) const { 11539 // ScalarEvolution's implementation of the print method is to print 11540 // out SCEV values of all instructions that are interesting. Doing 11541 // this potentially causes it to create new SCEV objects though, 11542 // which technically conflicts with the const qualifier. This isn't 11543 // observable from outside the class though, so casting away the 11544 // const isn't dangerous. 11545 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11546 11547 OS << "Classifying expressions for: "; 11548 F.printAsOperand(OS, /*PrintType=*/false); 11549 OS << "\n"; 11550 for (Instruction &I : instructions(F)) 11551 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11552 OS << I << '\n'; 11553 OS << " --> "; 11554 const SCEV *SV = SE.getSCEV(&I); 11555 SV->print(OS); 11556 if (!isa<SCEVCouldNotCompute>(SV)) { 11557 OS << " U: "; 11558 SE.getUnsignedRange(SV).print(OS); 11559 OS << " S: "; 11560 SE.getSignedRange(SV).print(OS); 11561 } 11562 11563 const Loop *L = LI.getLoopFor(I.getParent()); 11564 11565 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11566 if (AtUse != SV) { 11567 OS << " --> "; 11568 AtUse->print(OS); 11569 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11570 OS << " U: "; 11571 SE.getUnsignedRange(AtUse).print(OS); 11572 OS << " S: "; 11573 SE.getSignedRange(AtUse).print(OS); 11574 } 11575 } 11576 11577 if (L) { 11578 OS << "\t\t" "Exits: "; 11579 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11580 if (!SE.isLoopInvariant(ExitValue, L)) { 11581 OS << "<<Unknown>>"; 11582 } else { 11583 OS << *ExitValue; 11584 } 11585 11586 bool First = true; 11587 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11588 if (First) { 11589 OS << "\t\t" "LoopDispositions: { "; 11590 First = false; 11591 } else { 11592 OS << ", "; 11593 } 11594 11595 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11596 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11597 } 11598 11599 for (auto *InnerL : depth_first(L)) { 11600 if (InnerL == L) 11601 continue; 11602 if (First) { 11603 OS << "\t\t" "LoopDispositions: { "; 11604 First = false; 11605 } else { 11606 OS << ", "; 11607 } 11608 11609 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11610 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11611 } 11612 11613 OS << " }"; 11614 } 11615 11616 OS << "\n"; 11617 } 11618 11619 OS << "Determining loop execution counts for: "; 11620 F.printAsOperand(OS, /*PrintType=*/false); 11621 OS << "\n"; 11622 for (Loop *I : LI) 11623 PrintLoopInfo(OS, &SE, I); 11624 } 11625 11626 ScalarEvolution::LoopDisposition 11627 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11628 auto &Values = LoopDispositions[S]; 11629 for (auto &V : Values) { 11630 if (V.getPointer() == L) 11631 return V.getInt(); 11632 } 11633 Values.emplace_back(L, LoopVariant); 11634 LoopDisposition D = computeLoopDisposition(S, L); 11635 auto &Values2 = LoopDispositions[S]; 11636 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11637 if (V.getPointer() == L) { 11638 V.setInt(D); 11639 break; 11640 } 11641 } 11642 return D; 11643 } 11644 11645 ScalarEvolution::LoopDisposition 11646 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11647 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11648 case scConstant: 11649 return LoopInvariant; 11650 case scTruncate: 11651 case scZeroExtend: 11652 case scSignExtend: 11653 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11654 case scAddRecExpr: { 11655 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11656 11657 // If L is the addrec's loop, it's computable. 11658 if (AR->getLoop() == L) 11659 return LoopComputable; 11660 11661 // Add recurrences are never invariant in the function-body (null loop). 11662 if (!L) 11663 return LoopVariant; 11664 11665 // Everything that is not defined at loop entry is variant. 11666 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11667 return LoopVariant; 11668 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11669 " dominate the contained loop's header?"); 11670 11671 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11672 if (AR->getLoop()->contains(L)) 11673 return LoopInvariant; 11674 11675 // This recurrence is variant w.r.t. L if any of its operands 11676 // are variant. 11677 for (auto *Op : AR->operands()) 11678 if (!isLoopInvariant(Op, L)) 11679 return LoopVariant; 11680 11681 // Otherwise it's loop-invariant. 11682 return LoopInvariant; 11683 } 11684 case scAddExpr: 11685 case scMulExpr: 11686 case scUMaxExpr: 11687 case scSMaxExpr: 11688 case scUMinExpr: 11689 case scSMinExpr: { 11690 bool HasVarying = false; 11691 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11692 LoopDisposition D = getLoopDisposition(Op, L); 11693 if (D == LoopVariant) 11694 return LoopVariant; 11695 if (D == LoopComputable) 11696 HasVarying = true; 11697 } 11698 return HasVarying ? LoopComputable : LoopInvariant; 11699 } 11700 case scUDivExpr: { 11701 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11702 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11703 if (LD == LoopVariant) 11704 return LoopVariant; 11705 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11706 if (RD == LoopVariant) 11707 return LoopVariant; 11708 return (LD == LoopInvariant && RD == LoopInvariant) ? 11709 LoopInvariant : LoopComputable; 11710 } 11711 case scUnknown: 11712 // All non-instruction values are loop invariant. All instructions are loop 11713 // invariant if they are not contained in the specified loop. 11714 // Instructions are never considered invariant in the function body 11715 // (null loop) because they are defined within the "loop". 11716 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11717 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11718 return LoopInvariant; 11719 case scCouldNotCompute: 11720 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11721 } 11722 llvm_unreachable("Unknown SCEV kind!"); 11723 } 11724 11725 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11726 return getLoopDisposition(S, L) == LoopInvariant; 11727 } 11728 11729 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11730 return getLoopDisposition(S, L) == LoopComputable; 11731 } 11732 11733 ScalarEvolution::BlockDisposition 11734 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11735 auto &Values = BlockDispositions[S]; 11736 for (auto &V : Values) { 11737 if (V.getPointer() == BB) 11738 return V.getInt(); 11739 } 11740 Values.emplace_back(BB, DoesNotDominateBlock); 11741 BlockDisposition D = computeBlockDisposition(S, BB); 11742 auto &Values2 = BlockDispositions[S]; 11743 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11744 if (V.getPointer() == BB) { 11745 V.setInt(D); 11746 break; 11747 } 11748 } 11749 return D; 11750 } 11751 11752 ScalarEvolution::BlockDisposition 11753 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11754 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11755 case scConstant: 11756 return ProperlyDominatesBlock; 11757 case scTruncate: 11758 case scZeroExtend: 11759 case scSignExtend: 11760 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11761 case scAddRecExpr: { 11762 // This uses a "dominates" query instead of "properly dominates" query 11763 // to test for proper dominance too, because the instruction which 11764 // produces the addrec's value is a PHI, and a PHI effectively properly 11765 // dominates its entire containing block. 11766 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11767 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11768 return DoesNotDominateBlock; 11769 11770 // Fall through into SCEVNAryExpr handling. 11771 LLVM_FALLTHROUGH; 11772 } 11773 case scAddExpr: 11774 case scMulExpr: 11775 case scUMaxExpr: 11776 case scSMaxExpr: 11777 case scUMinExpr: 11778 case scSMinExpr: { 11779 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11780 bool Proper = true; 11781 for (const SCEV *NAryOp : NAry->operands()) { 11782 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11783 if (D == DoesNotDominateBlock) 11784 return DoesNotDominateBlock; 11785 if (D == DominatesBlock) 11786 Proper = false; 11787 } 11788 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11789 } 11790 case scUDivExpr: { 11791 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11792 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11793 BlockDisposition LD = getBlockDisposition(LHS, BB); 11794 if (LD == DoesNotDominateBlock) 11795 return DoesNotDominateBlock; 11796 BlockDisposition RD = getBlockDisposition(RHS, BB); 11797 if (RD == DoesNotDominateBlock) 11798 return DoesNotDominateBlock; 11799 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11800 ProperlyDominatesBlock : DominatesBlock; 11801 } 11802 case scUnknown: 11803 if (Instruction *I = 11804 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11805 if (I->getParent() == BB) 11806 return DominatesBlock; 11807 if (DT.properlyDominates(I->getParent(), BB)) 11808 return ProperlyDominatesBlock; 11809 return DoesNotDominateBlock; 11810 } 11811 return ProperlyDominatesBlock; 11812 case scCouldNotCompute: 11813 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11814 } 11815 llvm_unreachable("Unknown SCEV kind!"); 11816 } 11817 11818 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11819 return getBlockDisposition(S, BB) >= DominatesBlock; 11820 } 11821 11822 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11823 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11824 } 11825 11826 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11827 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11828 } 11829 11830 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11831 auto IsS = [&](const SCEV *X) { return S == X; }; 11832 auto ContainsS = [&](const SCEV *X) { 11833 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11834 }; 11835 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11836 } 11837 11838 void 11839 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11840 ValuesAtScopes.erase(S); 11841 LoopDispositions.erase(S); 11842 BlockDispositions.erase(S); 11843 UnsignedRanges.erase(S); 11844 SignedRanges.erase(S); 11845 ExprValueMap.erase(S); 11846 HasRecMap.erase(S); 11847 MinTrailingZerosCache.erase(S); 11848 11849 for (auto I = PredicatedSCEVRewrites.begin(); 11850 I != PredicatedSCEVRewrites.end();) { 11851 std::pair<const SCEV *, const Loop *> Entry = I->first; 11852 if (Entry.first == S) 11853 PredicatedSCEVRewrites.erase(I++); 11854 else 11855 ++I; 11856 } 11857 11858 auto RemoveSCEVFromBackedgeMap = 11859 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11860 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11861 BackedgeTakenInfo &BEInfo = I->second; 11862 if (BEInfo.hasOperand(S, this)) { 11863 BEInfo.clear(); 11864 Map.erase(I++); 11865 } else 11866 ++I; 11867 } 11868 }; 11869 11870 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11871 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11872 } 11873 11874 void 11875 ScalarEvolution::getUsedLoops(const SCEV *S, 11876 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11877 struct FindUsedLoops { 11878 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11879 : LoopsUsed(LoopsUsed) {} 11880 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11881 bool follow(const SCEV *S) { 11882 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11883 LoopsUsed.insert(AR->getLoop()); 11884 return true; 11885 } 11886 11887 bool isDone() const { return false; } 11888 }; 11889 11890 FindUsedLoops F(LoopsUsed); 11891 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11892 } 11893 11894 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11895 SmallPtrSet<const Loop *, 8> LoopsUsed; 11896 getUsedLoops(S, LoopsUsed); 11897 for (auto *L : LoopsUsed) 11898 LoopUsers[L].push_back(S); 11899 } 11900 11901 void ScalarEvolution::verify() const { 11902 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11903 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11904 11905 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11906 11907 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11908 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11909 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11910 11911 const SCEV *visitConstant(const SCEVConstant *Constant) { 11912 return SE.getConstant(Constant->getAPInt()); 11913 } 11914 11915 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11916 return SE.getUnknown(Expr->getValue()); 11917 } 11918 11919 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11920 return SE.getCouldNotCompute(); 11921 } 11922 }; 11923 11924 SCEVMapper SCM(SE2); 11925 11926 while (!LoopStack.empty()) { 11927 auto *L = LoopStack.pop_back_val(); 11928 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11929 11930 auto *CurBECount = SCM.visit( 11931 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11932 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11933 11934 if (CurBECount == SE2.getCouldNotCompute() || 11935 NewBECount == SE2.getCouldNotCompute()) { 11936 // NB! This situation is legal, but is very suspicious -- whatever pass 11937 // change the loop to make a trip count go from could not compute to 11938 // computable or vice-versa *should have* invalidated SCEV. However, we 11939 // choose not to assert here (for now) since we don't want false 11940 // positives. 11941 continue; 11942 } 11943 11944 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11945 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11946 // not propagate undef aggressively). This means we can (and do) fail 11947 // verification in cases where a transform makes the trip count of a loop 11948 // go from "undef" to "undef+1" (say). The transform is fine, since in 11949 // both cases the loop iterates "undef" times, but SCEV thinks we 11950 // increased the trip count of the loop by 1 incorrectly. 11951 continue; 11952 } 11953 11954 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11955 SE.getTypeSizeInBits(NewBECount->getType())) 11956 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11957 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11958 SE.getTypeSizeInBits(NewBECount->getType())) 11959 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11960 11961 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 11962 11963 // Unless VerifySCEVStrict is set, we only compare constant deltas. 11964 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 11965 dbgs() << "Trip Count for " << *L << " Changed!\n"; 11966 dbgs() << "Old: " << *CurBECount << "\n"; 11967 dbgs() << "New: " << *NewBECount << "\n"; 11968 dbgs() << "Delta: " << *Delta << "\n"; 11969 std::abort(); 11970 } 11971 } 11972 } 11973 11974 bool ScalarEvolution::invalidate( 11975 Function &F, const PreservedAnalyses &PA, 11976 FunctionAnalysisManager::Invalidator &Inv) { 11977 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11978 // of its dependencies is invalidated. 11979 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11980 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11981 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11982 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11983 Inv.invalidate<LoopAnalysis>(F, PA); 11984 } 11985 11986 AnalysisKey ScalarEvolutionAnalysis::Key; 11987 11988 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11989 FunctionAnalysisManager &AM) { 11990 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11991 AM.getResult<AssumptionAnalysis>(F), 11992 AM.getResult<DominatorTreeAnalysis>(F), 11993 AM.getResult<LoopAnalysis>(F)); 11994 } 11995 11996 PreservedAnalyses 11997 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11998 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11999 return PreservedAnalyses::all(); 12000 } 12001 12002 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12003 "Scalar Evolution Analysis", false, true) 12004 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12005 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12006 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12007 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12008 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12009 "Scalar Evolution Analysis", false, true) 12010 12011 char ScalarEvolutionWrapperPass::ID = 0; 12012 12013 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12014 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12015 } 12016 12017 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12018 SE.reset(new ScalarEvolution( 12019 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12020 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12021 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12022 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12023 return false; 12024 } 12025 12026 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12027 12028 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12029 SE->print(OS); 12030 } 12031 12032 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12033 if (!VerifySCEV) 12034 return; 12035 12036 SE->verify(); 12037 } 12038 12039 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12040 AU.setPreservesAll(); 12041 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12042 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12043 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12044 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12045 } 12046 12047 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12048 const SCEV *RHS) { 12049 FoldingSetNodeID ID; 12050 assert(LHS->getType() == RHS->getType() && 12051 "Type mismatch between LHS and RHS"); 12052 // Unique this node based on the arguments 12053 ID.AddInteger(SCEVPredicate::P_Equal); 12054 ID.AddPointer(LHS); 12055 ID.AddPointer(RHS); 12056 void *IP = nullptr; 12057 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12058 return S; 12059 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12060 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12061 UniquePreds.InsertNode(Eq, IP); 12062 return Eq; 12063 } 12064 12065 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12066 const SCEVAddRecExpr *AR, 12067 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12068 FoldingSetNodeID ID; 12069 // Unique this node based on the arguments 12070 ID.AddInteger(SCEVPredicate::P_Wrap); 12071 ID.AddPointer(AR); 12072 ID.AddInteger(AddedFlags); 12073 void *IP = nullptr; 12074 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12075 return S; 12076 auto *OF = new (SCEVAllocator) 12077 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12078 UniquePreds.InsertNode(OF, IP); 12079 return OF; 12080 } 12081 12082 namespace { 12083 12084 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12085 public: 12086 12087 /// Rewrites \p S in the context of a loop L and the SCEV predication 12088 /// infrastructure. 12089 /// 12090 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12091 /// equivalences present in \p Pred. 12092 /// 12093 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12094 /// \p NewPreds such that the result will be an AddRecExpr. 12095 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12096 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12097 SCEVUnionPredicate *Pred) { 12098 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12099 return Rewriter.visit(S); 12100 } 12101 12102 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12103 if (Pred) { 12104 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12105 for (auto *Pred : ExprPreds) 12106 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12107 if (IPred->getLHS() == Expr) 12108 return IPred->getRHS(); 12109 } 12110 return convertToAddRecWithPreds(Expr); 12111 } 12112 12113 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12114 const SCEV *Operand = visit(Expr->getOperand()); 12115 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12116 if (AR && AR->getLoop() == L && AR->isAffine()) { 12117 // This couldn't be folded because the operand didn't have the nuw 12118 // flag. Add the nusw flag as an assumption that we could make. 12119 const SCEV *Step = AR->getStepRecurrence(SE); 12120 Type *Ty = Expr->getType(); 12121 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12122 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12123 SE.getSignExtendExpr(Step, Ty), L, 12124 AR->getNoWrapFlags()); 12125 } 12126 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12127 } 12128 12129 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12130 const SCEV *Operand = visit(Expr->getOperand()); 12131 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12132 if (AR && AR->getLoop() == L && AR->isAffine()) { 12133 // This couldn't be folded because the operand didn't have the nsw 12134 // flag. Add the nssw flag as an assumption that we could make. 12135 const SCEV *Step = AR->getStepRecurrence(SE); 12136 Type *Ty = Expr->getType(); 12137 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12138 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12139 SE.getSignExtendExpr(Step, Ty), L, 12140 AR->getNoWrapFlags()); 12141 } 12142 return SE.getSignExtendExpr(Operand, Expr->getType()); 12143 } 12144 12145 private: 12146 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12147 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12148 SCEVUnionPredicate *Pred) 12149 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12150 12151 bool addOverflowAssumption(const SCEVPredicate *P) { 12152 if (!NewPreds) { 12153 // Check if we've already made this assumption. 12154 return Pred && Pred->implies(P); 12155 } 12156 NewPreds->insert(P); 12157 return true; 12158 } 12159 12160 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12161 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12162 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12163 return addOverflowAssumption(A); 12164 } 12165 12166 // If \p Expr represents a PHINode, we try to see if it can be represented 12167 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12168 // to add this predicate as a runtime overflow check, we return the AddRec. 12169 // If \p Expr does not meet these conditions (is not a PHI node, or we 12170 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12171 // return \p Expr. 12172 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12173 if (!isa<PHINode>(Expr->getValue())) 12174 return Expr; 12175 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12176 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12177 if (!PredicatedRewrite) 12178 return Expr; 12179 for (auto *P : PredicatedRewrite->second){ 12180 // Wrap predicates from outer loops are not supported. 12181 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12182 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12183 if (L != AR->getLoop()) 12184 return Expr; 12185 } 12186 if (!addOverflowAssumption(P)) 12187 return Expr; 12188 } 12189 return PredicatedRewrite->first; 12190 } 12191 12192 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12193 SCEVUnionPredicate *Pred; 12194 const Loop *L; 12195 }; 12196 12197 } // end anonymous namespace 12198 12199 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12200 SCEVUnionPredicate &Preds) { 12201 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12202 } 12203 12204 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12205 const SCEV *S, const Loop *L, 12206 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12207 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12208 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12209 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12210 12211 if (!AddRec) 12212 return nullptr; 12213 12214 // Since the transformation was successful, we can now transfer the SCEV 12215 // predicates. 12216 for (auto *P : TransformPreds) 12217 Preds.insert(P); 12218 12219 return AddRec; 12220 } 12221 12222 /// SCEV predicates 12223 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12224 SCEVPredicateKind Kind) 12225 : FastID(ID), Kind(Kind) {} 12226 12227 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12228 const SCEV *LHS, const SCEV *RHS) 12229 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12230 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12231 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12232 } 12233 12234 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12235 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12236 12237 if (!Op) 12238 return false; 12239 12240 return Op->LHS == LHS && Op->RHS == RHS; 12241 } 12242 12243 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12244 12245 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12246 12247 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12248 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12249 } 12250 12251 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12252 const SCEVAddRecExpr *AR, 12253 IncrementWrapFlags Flags) 12254 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12255 12256 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12257 12258 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12259 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12260 12261 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12262 } 12263 12264 bool SCEVWrapPredicate::isAlwaysTrue() const { 12265 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12266 IncrementWrapFlags IFlags = Flags; 12267 12268 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12269 IFlags = clearFlags(IFlags, IncrementNSSW); 12270 12271 return IFlags == IncrementAnyWrap; 12272 } 12273 12274 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12275 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12276 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12277 OS << "<nusw>"; 12278 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12279 OS << "<nssw>"; 12280 OS << "\n"; 12281 } 12282 12283 SCEVWrapPredicate::IncrementWrapFlags 12284 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12285 ScalarEvolution &SE) { 12286 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12287 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12288 12289 // We can safely transfer the NSW flag as NSSW. 12290 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12291 ImpliedFlags = IncrementNSSW; 12292 12293 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12294 // If the increment is positive, the SCEV NUW flag will also imply the 12295 // WrapPredicate NUSW flag. 12296 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12297 if (Step->getValue()->getValue().isNonNegative()) 12298 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12299 } 12300 12301 return ImpliedFlags; 12302 } 12303 12304 /// Union predicates don't get cached so create a dummy set ID for it. 12305 SCEVUnionPredicate::SCEVUnionPredicate() 12306 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12307 12308 bool SCEVUnionPredicate::isAlwaysTrue() const { 12309 return all_of(Preds, 12310 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12311 } 12312 12313 ArrayRef<const SCEVPredicate *> 12314 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12315 auto I = SCEVToPreds.find(Expr); 12316 if (I == SCEVToPreds.end()) 12317 return ArrayRef<const SCEVPredicate *>(); 12318 return I->second; 12319 } 12320 12321 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12322 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12323 return all_of(Set->Preds, 12324 [this](const SCEVPredicate *I) { return this->implies(I); }); 12325 12326 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12327 if (ScevPredsIt == SCEVToPreds.end()) 12328 return false; 12329 auto &SCEVPreds = ScevPredsIt->second; 12330 12331 return any_of(SCEVPreds, 12332 [N](const SCEVPredicate *I) { return I->implies(N); }); 12333 } 12334 12335 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12336 12337 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12338 for (auto Pred : Preds) 12339 Pred->print(OS, Depth); 12340 } 12341 12342 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12343 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12344 for (auto Pred : Set->Preds) 12345 add(Pred); 12346 return; 12347 } 12348 12349 if (implies(N)) 12350 return; 12351 12352 const SCEV *Key = N->getExpr(); 12353 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12354 " associated expression!"); 12355 12356 SCEVToPreds[Key].push_back(N); 12357 Preds.push_back(N); 12358 } 12359 12360 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12361 Loop &L) 12362 : SE(SE), L(L) {} 12363 12364 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12365 const SCEV *Expr = SE.getSCEV(V); 12366 RewriteEntry &Entry = RewriteMap[Expr]; 12367 12368 // If we already have an entry and the version matches, return it. 12369 if (Entry.second && Generation == Entry.first) 12370 return Entry.second; 12371 12372 // We found an entry but it's stale. Rewrite the stale entry 12373 // according to the current predicate. 12374 if (Entry.second) 12375 Expr = Entry.second; 12376 12377 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12378 Entry = {Generation, NewSCEV}; 12379 12380 return NewSCEV; 12381 } 12382 12383 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12384 if (!BackedgeCount) { 12385 SCEVUnionPredicate BackedgePred; 12386 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12387 addPredicate(BackedgePred); 12388 } 12389 return BackedgeCount; 12390 } 12391 12392 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12393 if (Preds.implies(&Pred)) 12394 return; 12395 Preds.add(&Pred); 12396 updateGeneration(); 12397 } 12398 12399 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12400 return Preds; 12401 } 12402 12403 void PredicatedScalarEvolution::updateGeneration() { 12404 // If the generation number wrapped recompute everything. 12405 if (++Generation == 0) { 12406 for (auto &II : RewriteMap) { 12407 const SCEV *Rewritten = II.second.second; 12408 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12409 } 12410 } 12411 } 12412 12413 void PredicatedScalarEvolution::setNoOverflow( 12414 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12415 const SCEV *Expr = getSCEV(V); 12416 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12417 12418 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12419 12420 // Clear the statically implied flags. 12421 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12422 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12423 12424 auto II = FlagsMap.insert({V, Flags}); 12425 if (!II.second) 12426 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12427 } 12428 12429 bool PredicatedScalarEvolution::hasNoOverflow( 12430 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12431 const SCEV *Expr = getSCEV(V); 12432 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12433 12434 Flags = SCEVWrapPredicate::clearFlags( 12435 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12436 12437 auto II = FlagsMap.find(V); 12438 12439 if (II != FlagsMap.end()) 12440 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12441 12442 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12443 } 12444 12445 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12446 const SCEV *Expr = this->getSCEV(V); 12447 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12448 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12449 12450 if (!New) 12451 return nullptr; 12452 12453 for (auto *P : NewPreds) 12454 Preds.add(P); 12455 12456 updateGeneration(); 12457 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12458 return New; 12459 } 12460 12461 PredicatedScalarEvolution::PredicatedScalarEvolution( 12462 const PredicatedScalarEvolution &Init) 12463 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12464 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12465 for (const auto &I : Init.FlagsMap) 12466 FlagsMap.insert(I); 12467 } 12468 12469 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12470 // For each block. 12471 for (auto *BB : L.getBlocks()) 12472 for (auto &I : *BB) { 12473 if (!SE.isSCEVable(I.getType())) 12474 continue; 12475 12476 auto *Expr = SE.getSCEV(&I); 12477 auto II = RewriteMap.find(Expr); 12478 12479 if (II == RewriteMap.end()) 12480 continue; 12481 12482 // Don't print things that are not interesting. 12483 if (II->second.second == Expr) 12484 continue; 12485 12486 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12487 OS.indent(Depth + 2) << *Expr << "\n"; 12488 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12489 } 12490 } 12491 12492 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12493 // arbitrary expressions. 12494 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12495 // 4, A / B becomes X / 8). 12496 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12497 const SCEV *&RHS) { 12498 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12499 if (Add == nullptr || Add->getNumOperands() != 2) 12500 return false; 12501 12502 const SCEV *A = Add->getOperand(1); 12503 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12504 12505 if (Mul == nullptr) 12506 return false; 12507 12508 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12509 // (SomeExpr + (-(SomeExpr / B) * B)). 12510 if (Expr == getURemExpr(A, B)) { 12511 LHS = A; 12512 RHS = B; 12513 return true; 12514 } 12515 return false; 12516 }; 12517 12518 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12519 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12520 return MatchURemWithDivisor(Mul->getOperand(1)) || 12521 MatchURemWithDivisor(Mul->getOperand(2)); 12522 12523 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12524 if (Mul->getNumOperands() == 2) 12525 return MatchURemWithDivisor(Mul->getOperand(1)) || 12526 MatchURemWithDivisor(Mul->getOperand(0)) || 12527 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12528 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12529 return false; 12530 } 12531