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/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/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/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 230 //===----------------------------------------------------------------------===// 231 // SCEV class definitions 232 //===----------------------------------------------------------------------===// 233 234 //===----------------------------------------------------------------------===// 235 // Implementation of the SCEV class. 236 // 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 LLVM_DUMP_METHOD void SCEV::dump() const { 240 print(dbgs()); 241 dbgs() << '\n'; 242 } 243 #endif 244 245 void SCEV::print(raw_ostream &OS) const { 246 switch (getSCEVType()) { 247 case scConstant: 248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 249 return; 250 case scTruncate: { 251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 252 const SCEV *Op = Trunc->getOperand(); 253 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 254 << *Trunc->getType() << ")"; 255 return; 256 } 257 case scZeroExtend: { 258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 259 const SCEV *Op = ZExt->getOperand(); 260 OS << "(zext " << *Op->getType() << " " << *Op << " to " 261 << *ZExt->getType() << ")"; 262 return; 263 } 264 case scSignExtend: { 265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 266 const SCEV *Op = SExt->getOperand(); 267 OS << "(sext " << *Op->getType() << " " << *Op << " to " 268 << *SExt->getType() << ")"; 269 return; 270 } 271 case scAddRecExpr: { 272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 273 OS << "{" << *AR->getOperand(0); 274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 275 OS << ",+," << *AR->getOperand(i); 276 OS << "}<"; 277 if (AR->hasNoUnsignedWrap()) 278 OS << "nuw><"; 279 if (AR->hasNoSignedWrap()) 280 OS << "nsw><"; 281 if (AR->hasNoSelfWrap() && 282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 283 OS << "nw><"; 284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 285 OS << ">"; 286 return; 287 } 288 case scAddExpr: 289 case scMulExpr: 290 case scUMaxExpr: 291 case scSMaxExpr: 292 case scUMinExpr: 293 case scSMinExpr: { 294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 295 const char *OpStr = nullptr; 296 switch (NAry->getSCEVType()) { 297 case scAddExpr: OpStr = " + "; break; 298 case scMulExpr: OpStr = " * "; break; 299 case scUMaxExpr: OpStr = " umax "; break; 300 case scSMaxExpr: OpStr = " smax "; break; 301 case scUMinExpr: 302 OpStr = " umin "; 303 break; 304 case scSMinExpr: 305 OpStr = " smin "; 306 break; 307 default: 308 llvm_unreachable("There are no other nary expression types."); 309 } 310 OS << "("; 311 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 312 I != E; ++I) { 313 OS << **I; 314 if (std::next(I) != E) 315 OS << OpStr; 316 } 317 OS << ")"; 318 switch (NAry->getSCEVType()) { 319 case scAddExpr: 320 case scMulExpr: 321 if (NAry->hasNoUnsignedWrap()) 322 OS << "<nuw>"; 323 if (NAry->hasNoSignedWrap()) 324 OS << "<nsw>"; 325 break; 326 default: 327 // Nothing to print for other nary expressions. 328 break; 329 } 330 return; 331 } 332 case scUDivExpr: { 333 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 334 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 335 return; 336 } 337 case scUnknown: { 338 const SCEVUnknown *U = cast<SCEVUnknown>(this); 339 Type *AllocTy; 340 if (U->isSizeOf(AllocTy)) { 341 OS << "sizeof(" << *AllocTy << ")"; 342 return; 343 } 344 if (U->isAlignOf(AllocTy)) { 345 OS << "alignof(" << *AllocTy << ")"; 346 return; 347 } 348 349 Type *CTy; 350 Constant *FieldNo; 351 if (U->isOffsetOf(CTy, FieldNo)) { 352 OS << "offsetof(" << *CTy << ", "; 353 FieldNo->printAsOperand(OS, false); 354 OS << ")"; 355 return; 356 } 357 358 // Otherwise just print it normally. 359 U->getValue()->printAsOperand(OS, false); 360 return; 361 } 362 case scCouldNotCompute: 363 OS << "***COULDNOTCOMPUTE***"; 364 return; 365 } 366 llvm_unreachable("Unknown SCEV kind!"); 367 } 368 369 Type *SCEV::getType() const { 370 switch (getSCEVType()) { 371 case scConstant: 372 return cast<SCEVConstant>(this)->getType(); 373 case scTruncate: 374 case scZeroExtend: 375 case scSignExtend: 376 return cast<SCEVIntegralCastExpr>(this)->getType(); 377 case scAddRecExpr: 378 case scMulExpr: 379 case scUMaxExpr: 380 case scSMaxExpr: 381 case scUMinExpr: 382 case scSMinExpr: 383 return cast<SCEVNAryExpr>(this)->getType(); 384 case scAddExpr: 385 return cast<SCEVAddExpr>(this)->getType(); 386 case scUDivExpr: 387 return cast<SCEVUDivExpr>(this)->getType(); 388 case scUnknown: 389 return cast<SCEVUnknown>(this)->getType(); 390 case scCouldNotCompute: 391 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 392 } 393 llvm_unreachable("Unknown SCEV kind!"); 394 } 395 396 bool SCEV::isZero() const { 397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 398 return SC->getValue()->isZero(); 399 return false; 400 } 401 402 bool SCEV::isOne() const { 403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 404 return SC->getValue()->isOne(); 405 return false; 406 } 407 408 bool SCEV::isAllOnesValue() const { 409 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 410 return SC->getValue()->isMinusOne(); 411 return false; 412 } 413 414 bool SCEV::isNonConstantNegative() const { 415 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 416 if (!Mul) return false; 417 418 // If there is a constant factor, it will be first. 419 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 420 if (!SC) return false; 421 422 // Return true if the value is negative, this matches things like (-42 * V). 423 return SC->getAPInt().isNegative(); 424 } 425 426 SCEVCouldNotCompute::SCEVCouldNotCompute() : 427 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 428 429 bool SCEVCouldNotCompute::classof(const SCEV *S) { 430 return S->getSCEVType() == scCouldNotCompute; 431 } 432 433 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 434 FoldingSetNodeID ID; 435 ID.AddInteger(scConstant); 436 ID.AddPointer(V); 437 void *IP = nullptr; 438 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 439 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 440 UniqueSCEVs.InsertNode(S, IP); 441 return S; 442 } 443 444 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 445 return getConstant(ConstantInt::get(getContext(), Val)); 446 } 447 448 const SCEV * 449 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 450 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 451 return getConstant(ConstantInt::get(ITy, V, isSigned)); 452 } 453 454 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 455 SCEVTypes SCEVTy, const SCEV *op, 456 Type *ty) 457 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 458 Operands[0] = op; 459 } 460 461 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 462 Type *ty) 463 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 464 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 465 "Cannot truncate non-integer value!"); 466 } 467 468 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 469 const SCEV *op, Type *ty) 470 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 471 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 472 "Cannot zero extend non-integer value!"); 473 } 474 475 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 476 const SCEV *op, Type *ty) 477 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 478 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 479 "Cannot sign extend non-integer value!"); 480 } 481 482 void SCEVUnknown::deleted() { 483 // Clear this SCEVUnknown from various maps. 484 SE->forgetMemoizedResults(this); 485 486 // Remove this SCEVUnknown from the uniquing map. 487 SE->UniqueSCEVs.RemoveNode(this); 488 489 // Release the value. 490 setValPtr(nullptr); 491 } 492 493 void SCEVUnknown::allUsesReplacedWith(Value *New) { 494 // Remove this SCEVUnknown from the uniquing map. 495 SE->UniqueSCEVs.RemoveNode(this); 496 497 // Update this SCEVUnknown to point to the new value. This is needed 498 // because there may still be outstanding SCEVs which still point to 499 // this SCEVUnknown. 500 setValPtr(New); 501 } 502 503 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 504 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 505 if (VCE->getOpcode() == Instruction::PtrToInt) 506 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 507 if (CE->getOpcode() == Instruction::GetElementPtr && 508 CE->getOperand(0)->isNullValue() && 509 CE->getNumOperands() == 2) 510 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 511 if (CI->isOne()) { 512 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 513 ->getElementType(); 514 return true; 515 } 516 517 return false; 518 } 519 520 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 521 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 522 if (VCE->getOpcode() == Instruction::PtrToInt) 523 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 524 if (CE->getOpcode() == Instruction::GetElementPtr && 525 CE->getOperand(0)->isNullValue()) { 526 Type *Ty = 527 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 528 if (StructType *STy = dyn_cast<StructType>(Ty)) 529 if (!STy->isPacked() && 530 CE->getNumOperands() == 3 && 531 CE->getOperand(1)->isNullValue()) { 532 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 533 if (CI->isOne() && 534 STy->getNumElements() == 2 && 535 STy->getElementType(0)->isIntegerTy(1)) { 536 AllocTy = STy->getElementType(1); 537 return true; 538 } 539 } 540 } 541 542 return false; 543 } 544 545 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 546 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 547 if (VCE->getOpcode() == Instruction::PtrToInt) 548 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 549 if (CE->getOpcode() == Instruction::GetElementPtr && 550 CE->getNumOperands() == 3 && 551 CE->getOperand(0)->isNullValue() && 552 CE->getOperand(1)->isNullValue()) { 553 Type *Ty = 554 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 555 // Ignore vector types here so that ScalarEvolutionExpander doesn't 556 // emit getelementptrs that index into vectors. 557 if (Ty->isStructTy() || Ty->isArrayTy()) { 558 CTy = Ty; 559 FieldNo = CE->getOperand(2); 560 return true; 561 } 562 } 563 564 return false; 565 } 566 567 //===----------------------------------------------------------------------===// 568 // SCEV Utilities 569 //===----------------------------------------------------------------------===// 570 571 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 572 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 573 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 574 /// have been previously deemed to be "equally complex" by this routine. It is 575 /// intended to avoid exponential time complexity in cases like: 576 /// 577 /// %a = f(%x, %y) 578 /// %b = f(%a, %a) 579 /// %c = f(%b, %b) 580 /// 581 /// %d = f(%x, %y) 582 /// %e = f(%d, %d) 583 /// %f = f(%e, %e) 584 /// 585 /// CompareValueComplexity(%f, %c) 586 /// 587 /// Since we do not continue running this routine on expression trees once we 588 /// have seen unequal values, there is no need to track them in the cache. 589 static int 590 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 591 const LoopInfo *const LI, Value *LV, Value *RV, 592 unsigned Depth) { 593 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 594 return 0; 595 596 // Order pointer values after integer values. This helps SCEVExpander form 597 // GEPs. 598 bool LIsPointer = LV->getType()->isPointerTy(), 599 RIsPointer = RV->getType()->isPointerTy(); 600 if (LIsPointer != RIsPointer) 601 return (int)LIsPointer - (int)RIsPointer; 602 603 // Compare getValueID values. 604 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 605 if (LID != RID) 606 return (int)LID - (int)RID; 607 608 // Sort arguments by their position. 609 if (const auto *LA = dyn_cast<Argument>(LV)) { 610 const auto *RA = cast<Argument>(RV); 611 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 612 return (int)LArgNo - (int)RArgNo; 613 } 614 615 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 616 const auto *RGV = cast<GlobalValue>(RV); 617 618 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 619 auto LT = GV->getLinkage(); 620 return !(GlobalValue::isPrivateLinkage(LT) || 621 GlobalValue::isInternalLinkage(LT)); 622 }; 623 624 // Use the names to distinguish the two values, but only if the 625 // names are semantically important. 626 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 627 return LGV->getName().compare(RGV->getName()); 628 } 629 630 // For instructions, compare their loop depth, and their operand count. This 631 // is pretty loose. 632 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 633 const auto *RInst = cast<Instruction>(RV); 634 635 // Compare loop depths. 636 const BasicBlock *LParent = LInst->getParent(), 637 *RParent = RInst->getParent(); 638 if (LParent != RParent) { 639 unsigned LDepth = LI->getLoopDepth(LParent), 640 RDepth = LI->getLoopDepth(RParent); 641 if (LDepth != RDepth) 642 return (int)LDepth - (int)RDepth; 643 } 644 645 // Compare the number of operands. 646 unsigned LNumOps = LInst->getNumOperands(), 647 RNumOps = RInst->getNumOperands(); 648 if (LNumOps != RNumOps) 649 return (int)LNumOps - (int)RNumOps; 650 651 for (unsigned Idx : seq(0u, LNumOps)) { 652 int Result = 653 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 654 RInst->getOperand(Idx), Depth + 1); 655 if (Result != 0) 656 return Result; 657 } 658 } 659 660 EqCacheValue.unionSets(LV, RV); 661 return 0; 662 } 663 664 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 665 // than RHS, respectively. A three-way result allows recursive comparisons to be 666 // more efficient. 667 static int CompareSCEVComplexity( 668 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 669 EquivalenceClasses<const Value *> &EqCacheValue, 670 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 671 DominatorTree &DT, unsigned Depth = 0) { 672 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 673 if (LHS == RHS) 674 return 0; 675 676 // Primarily, sort the SCEVs by their getSCEVType(). 677 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 678 if (LType != RType) 679 return (int)LType - (int)RType; 680 681 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 682 return 0; 683 // Aside from the getSCEVType() ordering, the particular ordering 684 // isn't very important except that it's beneficial to be consistent, 685 // so that (a + b) and (b + a) don't end up as different expressions. 686 switch (LType) { 687 case scUnknown: { 688 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 689 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 690 691 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 692 RU->getValue(), Depth + 1); 693 if (X == 0) 694 EqCacheSCEV.unionSets(LHS, RHS); 695 return X; 696 } 697 698 case scConstant: { 699 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 700 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 701 702 // Compare constant values. 703 const APInt &LA = LC->getAPInt(); 704 const APInt &RA = RC->getAPInt(); 705 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 706 if (LBitWidth != RBitWidth) 707 return (int)LBitWidth - (int)RBitWidth; 708 return LA.ult(RA) ? -1 : 1; 709 } 710 711 case scAddRecExpr: { 712 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 713 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 714 715 // There is always a dominance between two recs that are used by one SCEV, 716 // so we can safely sort recs by loop header dominance. We require such 717 // order in getAddExpr. 718 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 719 if (LLoop != RLoop) { 720 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 721 assert(LHead != RHead && "Two loops share the same header?"); 722 if (DT.dominates(LHead, RHead)) 723 return 1; 724 else 725 assert(DT.dominates(RHead, LHead) && 726 "No dominance between recurrences used by one SCEV?"); 727 return -1; 728 } 729 730 // Addrec complexity grows with operand count. 731 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 732 if (LNumOps != RNumOps) 733 return (int)LNumOps - (int)RNumOps; 734 735 // Lexicographically compare. 736 for (unsigned i = 0; i != LNumOps; ++i) { 737 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 738 LA->getOperand(i), RA->getOperand(i), DT, 739 Depth + 1); 740 if (X != 0) 741 return X; 742 } 743 EqCacheSCEV.unionSets(LHS, RHS); 744 return 0; 745 } 746 747 case scAddExpr: 748 case scMulExpr: 749 case scSMaxExpr: 750 case scUMaxExpr: 751 case scSMinExpr: 752 case scUMinExpr: { 753 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 754 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 755 756 // Lexicographically compare n-ary expressions. 757 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 758 if (LNumOps != RNumOps) 759 return (int)LNumOps - (int)RNumOps; 760 761 for (unsigned i = 0; i != LNumOps; ++i) { 762 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 763 LC->getOperand(i), RC->getOperand(i), DT, 764 Depth + 1); 765 if (X != 0) 766 return X; 767 } 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return 0; 770 } 771 772 case scUDivExpr: { 773 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 774 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 775 776 // Lexicographically compare udiv expressions. 777 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 778 RC->getLHS(), DT, Depth + 1); 779 if (X != 0) 780 return X; 781 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 782 RC->getRHS(), DT, Depth + 1); 783 if (X == 0) 784 EqCacheSCEV.unionSets(LHS, RHS); 785 return X; 786 } 787 788 case scTruncate: 789 case scZeroExtend: 790 case scSignExtend: { 791 const SCEVIntegralCastExpr *LC = cast<SCEVIntegralCastExpr>(LHS); 792 const SCEVIntegralCastExpr *RC = cast<SCEVIntegralCastExpr>(RHS); 793 794 // Compare cast expressions by operand. 795 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 796 LC->getOperand(), RC->getOperand(), DT, 797 Depth + 1); 798 if (X == 0) 799 EqCacheSCEV.unionSets(LHS, RHS); 800 return X; 801 } 802 803 case scCouldNotCompute: 804 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 805 } 806 llvm_unreachable("Unknown SCEV kind!"); 807 } 808 809 /// Given a list of SCEV objects, order them by their complexity, and group 810 /// objects of the same complexity together by value. When this routine is 811 /// finished, we know that any duplicates in the vector are consecutive and that 812 /// complexity is monotonically increasing. 813 /// 814 /// Note that we go take special precautions to ensure that we get deterministic 815 /// results from this routine. In other words, we don't want the results of 816 /// this to depend on where the addresses of various SCEV objects happened to 817 /// land in memory. 818 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 819 LoopInfo *LI, DominatorTree &DT) { 820 if (Ops.size() < 2) return; // Noop 821 822 EquivalenceClasses<const SCEV *> EqCacheSCEV; 823 EquivalenceClasses<const Value *> EqCacheValue; 824 if (Ops.size() == 2) { 825 // This is the common case, which also happens to be trivially simple. 826 // Special case it. 827 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 828 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 829 std::swap(LHS, RHS); 830 return; 831 } 832 833 // Do the rough sort by complexity. 834 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 835 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 836 0; 837 }); 838 839 // Now that we are sorted by complexity, group elements of the same 840 // complexity. Note that this is, at worst, N^2, but the vector is likely to 841 // be extremely short in practice. Note that we take this approach because we 842 // do not want to depend on the addresses of the objects we are grouping. 843 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 844 const SCEV *S = Ops[i]; 845 unsigned Complexity = S->getSCEVType(); 846 847 // If there are any objects of the same complexity and same value as this 848 // one, group them. 849 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 850 if (Ops[j] == S) { // Found a duplicate. 851 // Move it to immediately after i'th element. 852 std::swap(Ops[i+1], Ops[j]); 853 ++i; // no need to rescan it. 854 if (i == e-2) return; // Done! 855 } 856 } 857 } 858 } 859 860 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 861 /// least HugeExprThreshold nodes). 862 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 863 return any_of(Ops, [](const SCEV *S) { 864 return S->getExpressionSize() >= HugeExprThreshold; 865 }); 866 } 867 868 //===----------------------------------------------------------------------===// 869 // Simple SCEV method implementations 870 //===----------------------------------------------------------------------===// 871 872 /// Compute BC(It, K). The result has width W. Assume, K > 0. 873 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 874 ScalarEvolution &SE, 875 Type *ResultTy) { 876 // Handle the simplest case efficiently. 877 if (K == 1) 878 return SE.getTruncateOrZeroExtend(It, ResultTy); 879 880 // We are using the following formula for BC(It, K): 881 // 882 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 883 // 884 // Suppose, W is the bitwidth of the return value. We must be prepared for 885 // overflow. Hence, we must assure that the result of our computation is 886 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 887 // safe in modular arithmetic. 888 // 889 // However, this code doesn't use exactly that formula; the formula it uses 890 // is something like the following, where T is the number of factors of 2 in 891 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 892 // exponentiation: 893 // 894 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 895 // 896 // This formula is trivially equivalent to the previous formula. However, 897 // this formula can be implemented much more efficiently. The trick is that 898 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 899 // arithmetic. To do exact division in modular arithmetic, all we have 900 // to do is multiply by the inverse. Therefore, this step can be done at 901 // width W. 902 // 903 // The next issue is how to safely do the division by 2^T. The way this 904 // is done is by doing the multiplication step at a width of at least W + T 905 // bits. This way, the bottom W+T bits of the product are accurate. Then, 906 // when we perform the division by 2^T (which is equivalent to a right shift 907 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 908 // truncated out after the division by 2^T. 909 // 910 // In comparison to just directly using the first formula, this technique 911 // is much more efficient; using the first formula requires W * K bits, 912 // but this formula less than W + K bits. Also, the first formula requires 913 // a division step, whereas this formula only requires multiplies and shifts. 914 // 915 // It doesn't matter whether the subtraction step is done in the calculation 916 // width or the input iteration count's width; if the subtraction overflows, 917 // the result must be zero anyway. We prefer here to do it in the width of 918 // the induction variable because it helps a lot for certain cases; CodeGen 919 // isn't smart enough to ignore the overflow, which leads to much less 920 // efficient code if the width of the subtraction is wider than the native 921 // register width. 922 // 923 // (It's possible to not widen at all by pulling out factors of 2 before 924 // the multiplication; for example, K=2 can be calculated as 925 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 926 // extra arithmetic, so it's not an obvious win, and it gets 927 // much more complicated for K > 3.) 928 929 // Protection from insane SCEVs; this bound is conservative, 930 // but it probably doesn't matter. 931 if (K > 1000) 932 return SE.getCouldNotCompute(); 933 934 unsigned W = SE.getTypeSizeInBits(ResultTy); 935 936 // Calculate K! / 2^T and T; we divide out the factors of two before 937 // multiplying for calculating K! / 2^T to avoid overflow. 938 // Other overflow doesn't matter because we only care about the bottom 939 // W bits of the result. 940 APInt OddFactorial(W, 1); 941 unsigned T = 1; 942 for (unsigned i = 3; i <= K; ++i) { 943 APInt Mult(W, i); 944 unsigned TwoFactors = Mult.countTrailingZeros(); 945 T += TwoFactors; 946 Mult.lshrInPlace(TwoFactors); 947 OddFactorial *= Mult; 948 } 949 950 // We need at least W + T bits for the multiplication step 951 unsigned CalculationBits = W + T; 952 953 // Calculate 2^T, at width T+W. 954 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 955 956 // Calculate the multiplicative inverse of K! / 2^T; 957 // this multiplication factor will perform the exact division by 958 // K! / 2^T. 959 APInt Mod = APInt::getSignedMinValue(W+1); 960 APInt MultiplyFactor = OddFactorial.zext(W+1); 961 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 962 MultiplyFactor = MultiplyFactor.trunc(W); 963 964 // Calculate the product, at width T+W 965 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 966 CalculationBits); 967 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 968 for (unsigned i = 1; i != K; ++i) { 969 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 970 Dividend = SE.getMulExpr(Dividend, 971 SE.getTruncateOrZeroExtend(S, CalculationTy)); 972 } 973 974 // Divide by 2^T 975 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 976 977 // Truncate the result, and divide by K! / 2^T. 978 979 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 980 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 981 } 982 983 /// Return the value of this chain of recurrences at the specified iteration 984 /// number. We can evaluate this recurrence by multiplying each element in the 985 /// chain by the binomial coefficient corresponding to it. In other words, we 986 /// can evaluate {A,+,B,+,C,+,D} as: 987 /// 988 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 989 /// 990 /// where BC(It, k) stands for binomial coefficient. 991 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 992 ScalarEvolution &SE) const { 993 const SCEV *Result = getStart(); 994 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 995 // The computation is correct in the face of overflow provided that the 996 // multiplication is performed _after_ the evaluation of the binomial 997 // coefficient. 998 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 999 if (isa<SCEVCouldNotCompute>(Coeff)) 1000 return Coeff; 1001 1002 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1003 } 1004 return Result; 1005 } 1006 1007 //===----------------------------------------------------------------------===// 1008 // SCEV Expression folder implementations 1009 //===----------------------------------------------------------------------===// 1010 1011 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1012 unsigned Depth) { 1013 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1014 "This is not a truncating conversion!"); 1015 assert(isSCEVable(Ty) && 1016 "This is not a conversion to a SCEVable type!"); 1017 Ty = getEffectiveSCEVType(Ty); 1018 1019 FoldingSetNodeID ID; 1020 ID.AddInteger(scTruncate); 1021 ID.AddPointer(Op); 1022 ID.AddPointer(Ty); 1023 void *IP = nullptr; 1024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1025 1026 // Fold if the operand is constant. 1027 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1028 return getConstant( 1029 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1030 1031 // trunc(trunc(x)) --> trunc(x) 1032 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1033 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1034 1035 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1036 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1037 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1038 1039 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1040 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1041 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1042 1043 if (Depth > MaxCastDepth) { 1044 SCEV *S = 1045 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1046 UniqueSCEVs.InsertNode(S, IP); 1047 addToLoopUseLists(S); 1048 return S; 1049 } 1050 1051 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1052 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1053 // if after transforming we have at most one truncate, not counting truncates 1054 // that replace other casts. 1055 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1056 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1057 SmallVector<const SCEV *, 4> Operands; 1058 unsigned numTruncs = 0; 1059 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1060 ++i) { 1061 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1062 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1063 isa<SCEVTruncateExpr>(S)) 1064 numTruncs++; 1065 Operands.push_back(S); 1066 } 1067 if (numTruncs < 2) { 1068 if (isa<SCEVAddExpr>(Op)) 1069 return getAddExpr(Operands); 1070 else if (isa<SCEVMulExpr>(Op)) 1071 return getMulExpr(Operands); 1072 else 1073 llvm_unreachable("Unexpected SCEV type for Op."); 1074 } 1075 // Although we checked in the beginning that ID is not in the cache, it is 1076 // possible that during recursion and different modification ID was inserted 1077 // into the cache. So if we find it, just return it. 1078 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1079 return S; 1080 } 1081 1082 // If the input value is a chrec scev, truncate the chrec's operands. 1083 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1084 SmallVector<const SCEV *, 4> Operands; 1085 for (const SCEV *Op : AddRec->operands()) 1086 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1087 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1088 } 1089 1090 // The cast wasn't folded; create an explicit cast node. We can reuse 1091 // the existing insert position since if we get here, we won't have 1092 // made any changes which would invalidate it. 1093 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1094 Op, Ty); 1095 UniqueSCEVs.InsertNode(S, IP); 1096 addToLoopUseLists(S); 1097 return S; 1098 } 1099 1100 // Get the limit of a recurrence such that incrementing by Step cannot cause 1101 // signed overflow as long as the value of the recurrence within the 1102 // loop does not exceed this limit before incrementing. 1103 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1104 ICmpInst::Predicate *Pred, 1105 ScalarEvolution *SE) { 1106 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1107 if (SE->isKnownPositive(Step)) { 1108 *Pred = ICmpInst::ICMP_SLT; 1109 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1110 SE->getSignedRangeMax(Step)); 1111 } 1112 if (SE->isKnownNegative(Step)) { 1113 *Pred = ICmpInst::ICMP_SGT; 1114 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1115 SE->getSignedRangeMin(Step)); 1116 } 1117 return nullptr; 1118 } 1119 1120 // Get the limit of a recurrence such that incrementing by Step cannot cause 1121 // unsigned overflow as long as the value of the recurrence within the loop does 1122 // not exceed this limit before incrementing. 1123 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1124 ICmpInst::Predicate *Pred, 1125 ScalarEvolution *SE) { 1126 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1127 *Pred = ICmpInst::ICMP_ULT; 1128 1129 return SE->getConstant(APInt::getMinValue(BitWidth) - 1130 SE->getUnsignedRangeMax(Step)); 1131 } 1132 1133 namespace { 1134 1135 struct ExtendOpTraitsBase { 1136 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1137 unsigned); 1138 }; 1139 1140 // Used to make code generic over signed and unsigned overflow. 1141 template <typename ExtendOp> struct ExtendOpTraits { 1142 // Members present: 1143 // 1144 // static const SCEV::NoWrapFlags WrapType; 1145 // 1146 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1147 // 1148 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1149 // ICmpInst::Predicate *Pred, 1150 // ScalarEvolution *SE); 1151 }; 1152 1153 template <> 1154 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1155 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1156 1157 static const GetExtendExprTy GetExtendExpr; 1158 1159 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1160 ICmpInst::Predicate *Pred, 1161 ScalarEvolution *SE) { 1162 return getSignedOverflowLimitForStep(Step, Pred, SE); 1163 } 1164 }; 1165 1166 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1167 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1168 1169 template <> 1170 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1171 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1172 1173 static const GetExtendExprTy GetExtendExpr; 1174 1175 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1176 ICmpInst::Predicate *Pred, 1177 ScalarEvolution *SE) { 1178 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1179 } 1180 }; 1181 1182 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1183 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1184 1185 } // end anonymous namespace 1186 1187 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1188 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1189 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1190 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1191 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1192 // expression "Step + sext/zext(PreIncAR)" is congruent with 1193 // "sext/zext(PostIncAR)" 1194 template <typename ExtendOpTy> 1195 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1196 ScalarEvolution *SE, unsigned Depth) { 1197 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1198 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1199 1200 const Loop *L = AR->getLoop(); 1201 const SCEV *Start = AR->getStart(); 1202 const SCEV *Step = AR->getStepRecurrence(*SE); 1203 1204 // Check for a simple looking step prior to loop entry. 1205 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1206 if (!SA) 1207 return nullptr; 1208 1209 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1210 // subtraction is expensive. For this purpose, perform a quick and dirty 1211 // difference, by checking for Step in the operand list. 1212 SmallVector<const SCEV *, 4> DiffOps; 1213 for (const SCEV *Op : SA->operands()) 1214 if (Op != Step) 1215 DiffOps.push_back(Op); 1216 1217 if (DiffOps.size() == SA->getNumOperands()) 1218 return nullptr; 1219 1220 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1221 // `Step`: 1222 1223 // 1. NSW/NUW flags on the step increment. 1224 auto PreStartFlags = 1225 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1226 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1227 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1228 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1229 1230 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1231 // "S+X does not sign/unsign-overflow". 1232 // 1233 1234 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1235 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1236 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1237 return PreStart; 1238 1239 // 2. Direct overflow check on the step operation's expression. 1240 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1241 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1242 const SCEV *OperandExtendedStart = 1243 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1244 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1245 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1246 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1247 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1248 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1249 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1250 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1251 } 1252 return PreStart; 1253 } 1254 1255 // 3. Loop precondition. 1256 ICmpInst::Predicate Pred; 1257 const SCEV *OverflowLimit = 1258 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1259 1260 if (OverflowLimit && 1261 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1262 return PreStart; 1263 1264 return nullptr; 1265 } 1266 1267 // Get the normalized zero or sign extended expression for this AddRec's Start. 1268 template <typename ExtendOpTy> 1269 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1270 ScalarEvolution *SE, 1271 unsigned Depth) { 1272 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1273 1274 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1275 if (!PreStart) 1276 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1277 1278 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1279 Depth), 1280 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1281 } 1282 1283 // Try to prove away overflow by looking at "nearby" add recurrences. A 1284 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1285 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1286 // 1287 // Formally: 1288 // 1289 // {S,+,X} == {S-T,+,X} + T 1290 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1291 // 1292 // If ({S-T,+,X} + T) does not overflow ... (1) 1293 // 1294 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1295 // 1296 // If {S-T,+,X} does not overflow ... (2) 1297 // 1298 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1299 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1300 // 1301 // If (S-T)+T does not overflow ... (3) 1302 // 1303 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1304 // == {Ext(S),+,Ext(X)} == LHS 1305 // 1306 // Thus, if (1), (2) and (3) are true for some T, then 1307 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1308 // 1309 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1310 // does not overflow" restricted to the 0th iteration. Therefore we only need 1311 // to check for (1) and (2). 1312 // 1313 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1314 // is `Delta` (defined below). 1315 template <typename ExtendOpTy> 1316 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1317 const SCEV *Step, 1318 const Loop *L) { 1319 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1320 1321 // We restrict `Start` to a constant to prevent SCEV from spending too much 1322 // time here. It is correct (but more expensive) to continue with a 1323 // non-constant `Start` and do a general SCEV subtraction to compute 1324 // `PreStart` below. 1325 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1326 if (!StartC) 1327 return false; 1328 1329 APInt StartAI = StartC->getAPInt(); 1330 1331 for (unsigned Delta : {-2, -1, 1, 2}) { 1332 const SCEV *PreStart = getConstant(StartAI - Delta); 1333 1334 FoldingSetNodeID ID; 1335 ID.AddInteger(scAddRecExpr); 1336 ID.AddPointer(PreStart); 1337 ID.AddPointer(Step); 1338 ID.AddPointer(L); 1339 void *IP = nullptr; 1340 const auto *PreAR = 1341 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1342 1343 // Give up if we don't already have the add recurrence we need because 1344 // actually constructing an add recurrence is relatively expensive. 1345 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1346 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1347 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1348 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1349 DeltaS, &Pred, this); 1350 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1351 return true; 1352 } 1353 } 1354 1355 return false; 1356 } 1357 1358 // Finds an integer D for an expression (C + x + y + ...) such that the top 1359 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1360 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1361 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1362 // the (C + x + y + ...) expression is \p WholeAddExpr. 1363 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1364 const SCEVConstant *ConstantTerm, 1365 const SCEVAddExpr *WholeAddExpr) { 1366 const APInt &C = ConstantTerm->getAPInt(); 1367 const unsigned BitWidth = C.getBitWidth(); 1368 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1369 uint32_t TZ = BitWidth; 1370 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1371 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1372 if (TZ) { 1373 // Set D to be as many least significant bits of C as possible while still 1374 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1375 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1376 } 1377 return APInt(BitWidth, 0); 1378 } 1379 1380 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1381 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1382 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1383 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1384 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1385 const APInt &ConstantStart, 1386 const SCEV *Step) { 1387 const unsigned BitWidth = ConstantStart.getBitWidth(); 1388 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1389 if (TZ) 1390 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1391 : ConstantStart; 1392 return APInt(BitWidth, 0); 1393 } 1394 1395 const SCEV * 1396 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1397 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1398 "This is not an extending conversion!"); 1399 assert(isSCEVable(Ty) && 1400 "This is not a conversion to a SCEVable type!"); 1401 Ty = getEffectiveSCEVType(Ty); 1402 1403 // Fold if the operand is constant. 1404 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1405 return getConstant( 1406 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1407 1408 // zext(zext(x)) --> zext(x) 1409 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1410 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1411 1412 // Before doing any expensive analysis, check to see if we've already 1413 // computed a SCEV for this Op and Ty. 1414 FoldingSetNodeID ID; 1415 ID.AddInteger(scZeroExtend); 1416 ID.AddPointer(Op); 1417 ID.AddPointer(Ty); 1418 void *IP = nullptr; 1419 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1420 if (Depth > MaxCastDepth) { 1421 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1422 Op, Ty); 1423 UniqueSCEVs.InsertNode(S, IP); 1424 addToLoopUseLists(S); 1425 return S; 1426 } 1427 1428 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1429 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1430 // It's possible the bits taken off by the truncate were all zero bits. If 1431 // so, we should be able to simplify this further. 1432 const SCEV *X = ST->getOperand(); 1433 ConstantRange CR = getUnsignedRange(X); 1434 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1435 unsigned NewBits = getTypeSizeInBits(Ty); 1436 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1437 CR.zextOrTrunc(NewBits))) 1438 return getTruncateOrZeroExtend(X, Ty, Depth); 1439 } 1440 1441 // If the input value is a chrec scev, and we can prove that the value 1442 // did not overflow the old, smaller, value, we can zero extend all of the 1443 // operands (often constants). This allows analysis of something like 1444 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1445 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1446 if (AR->isAffine()) { 1447 const SCEV *Start = AR->getStart(); 1448 const SCEV *Step = AR->getStepRecurrence(*this); 1449 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1450 const Loop *L = AR->getLoop(); 1451 1452 if (!AR->hasNoUnsignedWrap()) { 1453 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1454 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1455 } 1456 1457 // If we have special knowledge that this addrec won't overflow, 1458 // we don't need to do any further analysis. 1459 if (AR->hasNoUnsignedWrap()) 1460 return getAddRecExpr( 1461 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1462 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1463 1464 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1465 // Note that this serves two purposes: It filters out loops that are 1466 // simply not analyzable, and it covers the case where this code is 1467 // being called from within backedge-taken count analysis, such that 1468 // attempting to ask for the backedge-taken count would likely result 1469 // in infinite recursion. In the later case, the analysis code will 1470 // cope with a conservative value, and it will take care to purge 1471 // that value once it has finished. 1472 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1473 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1474 // Manually compute the final value for AR, checking for 1475 // overflow. 1476 1477 // Check whether the backedge-taken count can be losslessly casted to 1478 // the addrec's type. The count is always unsigned. 1479 const SCEV *CastedMaxBECount = 1480 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1481 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1482 CastedMaxBECount, MaxBECount->getType(), Depth); 1483 if (MaxBECount == RecastedMaxBECount) { 1484 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1485 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1486 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1487 SCEV::FlagAnyWrap, Depth + 1); 1488 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1489 SCEV::FlagAnyWrap, 1490 Depth + 1), 1491 WideTy, Depth + 1); 1492 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1493 const SCEV *WideMaxBECount = 1494 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1495 const SCEV *OperandExtendedAdd = 1496 getAddExpr(WideStart, 1497 getMulExpr(WideMaxBECount, 1498 getZeroExtendExpr(Step, WideTy, Depth + 1), 1499 SCEV::FlagAnyWrap, Depth + 1), 1500 SCEV::FlagAnyWrap, Depth + 1); 1501 if (ZAdd == OperandExtendedAdd) { 1502 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1503 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1504 // Return the expression with the addrec on the outside. 1505 return getAddRecExpr( 1506 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1507 Depth + 1), 1508 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1509 AR->getNoWrapFlags()); 1510 } 1511 // Similar to above, only this time treat the step value as signed. 1512 // This covers loops that count down. 1513 OperandExtendedAdd = 1514 getAddExpr(WideStart, 1515 getMulExpr(WideMaxBECount, 1516 getSignExtendExpr(Step, WideTy, Depth + 1), 1517 SCEV::FlagAnyWrap, Depth + 1), 1518 SCEV::FlagAnyWrap, Depth + 1); 1519 if (ZAdd == OperandExtendedAdd) { 1520 // Cache knowledge of AR NW, which is propagated to this AddRec. 1521 // Negative step causes unsigned wrap, but it still can't self-wrap. 1522 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1523 // Return the expression with the addrec on the outside. 1524 return getAddRecExpr( 1525 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1526 Depth + 1), 1527 getSignExtendExpr(Step, Ty, Depth + 1), L, 1528 AR->getNoWrapFlags()); 1529 } 1530 } 1531 } 1532 1533 // Normally, in the cases we can prove no-overflow via a 1534 // backedge guarding condition, we can also compute a backedge 1535 // taken count for the loop. The exceptions are assumptions and 1536 // guards present in the loop -- SCEV is not great at exploiting 1537 // these to compute max backedge taken counts, but can still use 1538 // these to prove lack of overflow. Use this fact to avoid 1539 // doing extra work that may not pay off. 1540 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1541 !AC.assumptions().empty()) { 1542 // If the backedge is guarded by a comparison with the pre-inc 1543 // value the addrec is safe. Also, if the entry is guarded by 1544 // a comparison with the start value and the backedge is 1545 // guarded by a comparison with the post-inc value, the addrec 1546 // is safe. 1547 if (isKnownPositive(Step)) { 1548 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1549 getUnsignedRangeMax(Step)); 1550 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1551 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1552 // Cache knowledge of AR NUW, which is propagated to this 1553 // AddRec. 1554 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1555 // Return the expression with the addrec on the outside. 1556 return getAddRecExpr( 1557 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1558 Depth + 1), 1559 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1560 AR->getNoWrapFlags()); 1561 } 1562 } else if (isKnownNegative(Step)) { 1563 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1564 getSignedRangeMin(Step)); 1565 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1566 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1567 // Cache knowledge of AR NW, which is propagated to this 1568 // AddRec. Negative step causes unsigned wrap, but it 1569 // still can't self-wrap. 1570 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1571 // Return the expression with the addrec on the outside. 1572 return getAddRecExpr( 1573 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1574 Depth + 1), 1575 getSignExtendExpr(Step, Ty, Depth + 1), L, 1576 AR->getNoWrapFlags()); 1577 } 1578 } 1579 } 1580 1581 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1582 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1583 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1584 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1585 const APInt &C = SC->getAPInt(); 1586 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1587 if (D != 0) { 1588 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1589 const SCEV *SResidual = 1590 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1591 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1592 return getAddExpr(SZExtD, SZExtR, 1593 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1594 Depth + 1); 1595 } 1596 } 1597 1598 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1599 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1600 return getAddRecExpr( 1601 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1602 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1603 } 1604 } 1605 1606 // zext(A % B) --> zext(A) % zext(B) 1607 { 1608 const SCEV *LHS; 1609 const SCEV *RHS; 1610 if (matchURem(Op, LHS, RHS)) 1611 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1612 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1613 } 1614 1615 // zext(A / B) --> zext(A) / zext(B). 1616 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1617 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1618 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1619 1620 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1621 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1622 if (SA->hasNoUnsignedWrap()) { 1623 // If the addition does not unsign overflow then we can, by definition, 1624 // commute the zero extension with the addition operation. 1625 SmallVector<const SCEV *, 4> Ops; 1626 for (const auto *Op : SA->operands()) 1627 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1628 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1629 } 1630 1631 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1632 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1633 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1634 // 1635 // Often address arithmetics contain expressions like 1636 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1637 // This transformation is useful while proving that such expressions are 1638 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1639 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1640 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1641 if (D != 0) { 1642 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1643 const SCEV *SResidual = 1644 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1645 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1646 return getAddExpr(SZExtD, SZExtR, 1647 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1648 Depth + 1); 1649 } 1650 } 1651 } 1652 1653 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1654 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1655 if (SM->hasNoUnsignedWrap()) { 1656 // If the multiply does not unsign overflow then we can, by definition, 1657 // commute the zero extension with the multiply operation. 1658 SmallVector<const SCEV *, 4> Ops; 1659 for (const auto *Op : SM->operands()) 1660 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1661 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1662 } 1663 1664 // zext(2^K * (trunc X to iN)) to iM -> 1665 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1666 // 1667 // Proof: 1668 // 1669 // zext(2^K * (trunc X to iN)) to iM 1670 // = zext((trunc X to iN) << K) to iM 1671 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1672 // (because shl removes the top K bits) 1673 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1674 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1675 // 1676 if (SM->getNumOperands() == 2) 1677 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1678 if (MulLHS->getAPInt().isPowerOf2()) 1679 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1680 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1681 MulLHS->getAPInt().logBase2(); 1682 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1683 return getMulExpr( 1684 getZeroExtendExpr(MulLHS, Ty), 1685 getZeroExtendExpr( 1686 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1687 SCEV::FlagNUW, Depth + 1); 1688 } 1689 } 1690 1691 // The cast wasn't folded; create an explicit cast node. 1692 // Recompute the insert position, as it may have been invalidated. 1693 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1694 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1695 Op, Ty); 1696 UniqueSCEVs.InsertNode(S, IP); 1697 addToLoopUseLists(S); 1698 return S; 1699 } 1700 1701 const SCEV * 1702 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1703 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1704 "This is not an extending conversion!"); 1705 assert(isSCEVable(Ty) && 1706 "This is not a conversion to a SCEVable type!"); 1707 Ty = getEffectiveSCEVType(Ty); 1708 1709 // Fold if the operand is constant. 1710 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1711 return getConstant( 1712 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1713 1714 // sext(sext(x)) --> sext(x) 1715 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1716 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1717 1718 // sext(zext(x)) --> zext(x) 1719 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1720 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1721 1722 // Before doing any expensive analysis, check to see if we've already 1723 // computed a SCEV for this Op and Ty. 1724 FoldingSetNodeID ID; 1725 ID.AddInteger(scSignExtend); 1726 ID.AddPointer(Op); 1727 ID.AddPointer(Ty); 1728 void *IP = nullptr; 1729 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1730 // Limit recursion depth. 1731 if (Depth > MaxCastDepth) { 1732 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1733 Op, Ty); 1734 UniqueSCEVs.InsertNode(S, IP); 1735 addToLoopUseLists(S); 1736 return S; 1737 } 1738 1739 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1740 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1741 // It's possible the bits taken off by the truncate were all sign bits. If 1742 // so, we should be able to simplify this further. 1743 const SCEV *X = ST->getOperand(); 1744 ConstantRange CR = getSignedRange(X); 1745 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1746 unsigned NewBits = getTypeSizeInBits(Ty); 1747 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1748 CR.sextOrTrunc(NewBits))) 1749 return getTruncateOrSignExtend(X, Ty, Depth); 1750 } 1751 1752 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1753 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1754 if (SA->hasNoSignedWrap()) { 1755 // If the addition does not sign overflow then we can, by definition, 1756 // commute the sign extension with the addition operation. 1757 SmallVector<const SCEV *, 4> Ops; 1758 for (const auto *Op : SA->operands()) 1759 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1760 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1761 } 1762 1763 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1764 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1765 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1766 // 1767 // For instance, this will bring two seemingly different expressions: 1768 // 1 + sext(5 + 20 * %x + 24 * %y) and 1769 // sext(6 + 20 * %x + 24 * %y) 1770 // to the same form: 1771 // 2 + sext(4 + 20 * %x + 24 * %y) 1772 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1773 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1774 if (D != 0) { 1775 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1776 const SCEV *SResidual = 1777 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1778 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1779 return getAddExpr(SSExtD, SSExtR, 1780 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1781 Depth + 1); 1782 } 1783 } 1784 } 1785 // If the input value is a chrec scev, and we can prove that the value 1786 // did not overflow the old, smaller, value, we can sign extend all of the 1787 // operands (often constants). This allows analysis of something like 1788 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1790 if (AR->isAffine()) { 1791 const SCEV *Start = AR->getStart(); 1792 const SCEV *Step = AR->getStepRecurrence(*this); 1793 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1794 const Loop *L = AR->getLoop(); 1795 1796 if (!AR->hasNoSignedWrap()) { 1797 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1798 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1799 } 1800 1801 // If we have special knowledge that this addrec won't overflow, 1802 // we don't need to do any further analysis. 1803 if (AR->hasNoSignedWrap()) 1804 return getAddRecExpr( 1805 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1806 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1807 1808 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1809 // Note that this serves two purposes: It filters out loops that are 1810 // simply not analyzable, and it covers the case where this code is 1811 // being called from within backedge-taken count analysis, such that 1812 // attempting to ask for the backedge-taken count would likely result 1813 // in infinite recursion. In the later case, the analysis code will 1814 // cope with a conservative value, and it will take care to purge 1815 // that value once it has finished. 1816 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1817 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1818 // Manually compute the final value for AR, checking for 1819 // overflow. 1820 1821 // Check whether the backedge-taken count can be losslessly casted to 1822 // the addrec's type. The count is always unsigned. 1823 const SCEV *CastedMaxBECount = 1824 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1825 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1826 CastedMaxBECount, MaxBECount->getType(), Depth); 1827 if (MaxBECount == RecastedMaxBECount) { 1828 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1829 // Check whether Start+Step*MaxBECount has no signed overflow. 1830 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1831 SCEV::FlagAnyWrap, Depth + 1); 1832 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1833 SCEV::FlagAnyWrap, 1834 Depth + 1), 1835 WideTy, Depth + 1); 1836 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1837 const SCEV *WideMaxBECount = 1838 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1839 const SCEV *OperandExtendedAdd = 1840 getAddExpr(WideStart, 1841 getMulExpr(WideMaxBECount, 1842 getSignExtendExpr(Step, WideTy, Depth + 1), 1843 SCEV::FlagAnyWrap, Depth + 1), 1844 SCEV::FlagAnyWrap, Depth + 1); 1845 if (SAdd == OperandExtendedAdd) { 1846 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1847 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1848 // Return the expression with the addrec on the outside. 1849 return getAddRecExpr( 1850 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1851 Depth + 1), 1852 getSignExtendExpr(Step, Ty, Depth + 1), L, 1853 AR->getNoWrapFlags()); 1854 } 1855 // Similar to above, only this time treat the step value as unsigned. 1856 // This covers loops that count up with an unsigned step. 1857 OperandExtendedAdd = 1858 getAddExpr(WideStart, 1859 getMulExpr(WideMaxBECount, 1860 getZeroExtendExpr(Step, WideTy, Depth + 1), 1861 SCEV::FlagAnyWrap, Depth + 1), 1862 SCEV::FlagAnyWrap, Depth + 1); 1863 if (SAdd == OperandExtendedAdd) { 1864 // If AR wraps around then 1865 // 1866 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1867 // => SAdd != OperandExtendedAdd 1868 // 1869 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1870 // (SAdd == OperandExtendedAdd => AR is NW) 1871 1872 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1873 1874 // Return the expression with the addrec on the outside. 1875 return getAddRecExpr( 1876 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1877 Depth + 1), 1878 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1879 AR->getNoWrapFlags()); 1880 } 1881 } 1882 } 1883 1884 // Normally, in the cases we can prove no-overflow via a 1885 // backedge guarding condition, we can also compute a backedge 1886 // taken count for the loop. The exceptions are assumptions and 1887 // guards present in the loop -- SCEV is not great at exploiting 1888 // these to compute max backedge taken counts, but can still use 1889 // these to prove lack of overflow. Use this fact to avoid 1890 // doing extra work that may not pay off. 1891 1892 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1893 !AC.assumptions().empty()) { 1894 // If the backedge is guarded by a comparison with the pre-inc 1895 // value the addrec is safe. Also, if the entry is guarded by 1896 // a comparison with the start value and the backedge is 1897 // guarded by a comparison with the post-inc value, the addrec 1898 // is safe. 1899 ICmpInst::Predicate Pred; 1900 const SCEV *OverflowLimit = 1901 getSignedOverflowLimitForStep(Step, &Pred, this); 1902 if (OverflowLimit && 1903 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1904 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 1905 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1906 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1907 return getAddRecExpr( 1908 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1909 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1910 } 1911 } 1912 1913 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 1914 // if D + (C - D + Step * n) could be proven to not signed wrap 1915 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1916 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1917 const APInt &C = SC->getAPInt(); 1918 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1919 if (D != 0) { 1920 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1921 const SCEV *SResidual = 1922 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1923 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1924 return getAddExpr(SSExtD, SSExtR, 1925 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1926 Depth + 1); 1927 } 1928 } 1929 1930 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1931 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1932 return getAddRecExpr( 1933 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1934 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1935 } 1936 } 1937 1938 // If the input value is provably positive and we could not simplify 1939 // away the sext build a zext instead. 1940 if (isKnownNonNegative(Op)) 1941 return getZeroExtendExpr(Op, Ty, Depth + 1); 1942 1943 // The cast wasn't folded; create an explicit cast node. 1944 // Recompute the insert position, as it may have been invalidated. 1945 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1946 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1947 Op, Ty); 1948 UniqueSCEVs.InsertNode(S, IP); 1949 addToLoopUseLists(S); 1950 return S; 1951 } 1952 1953 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1954 /// unspecified bits out to the given type. 1955 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1956 Type *Ty) { 1957 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1958 "This is not an extending conversion!"); 1959 assert(isSCEVable(Ty) && 1960 "This is not a conversion to a SCEVable type!"); 1961 Ty = getEffectiveSCEVType(Ty); 1962 1963 // Sign-extend negative constants. 1964 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1965 if (SC->getAPInt().isNegative()) 1966 return getSignExtendExpr(Op, Ty); 1967 1968 // Peel off a truncate cast. 1969 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1970 const SCEV *NewOp = T->getOperand(); 1971 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1972 return getAnyExtendExpr(NewOp, Ty); 1973 return getTruncateOrNoop(NewOp, Ty); 1974 } 1975 1976 // Next try a zext cast. If the cast is folded, use it. 1977 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1978 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1979 return ZExt; 1980 1981 // Next try a sext cast. If the cast is folded, use it. 1982 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1983 if (!isa<SCEVSignExtendExpr>(SExt)) 1984 return SExt; 1985 1986 // Force the cast to be folded into the operands of an addrec. 1987 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1988 SmallVector<const SCEV *, 4> Ops; 1989 for (const SCEV *Op : AR->operands()) 1990 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1991 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1992 } 1993 1994 // If the expression is obviously signed, use the sext cast value. 1995 if (isa<SCEVSMaxExpr>(Op)) 1996 return SExt; 1997 1998 // Absent any other information, use the zext cast value. 1999 return ZExt; 2000 } 2001 2002 /// Process the given Ops list, which is a list of operands to be added under 2003 /// the given scale, update the given map. This is a helper function for 2004 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2005 /// that would form an add expression like this: 2006 /// 2007 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2008 /// 2009 /// where A and B are constants, update the map with these values: 2010 /// 2011 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2012 /// 2013 /// and add 13 + A*B*29 to AccumulatedConstant. 2014 /// This will allow getAddRecExpr to produce this: 2015 /// 2016 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2017 /// 2018 /// This form often exposes folding opportunities that are hidden in 2019 /// the original operand list. 2020 /// 2021 /// Return true iff it appears that any interesting folding opportunities 2022 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2023 /// the common case where no interesting opportunities are present, and 2024 /// is also used as a check to avoid infinite recursion. 2025 static bool 2026 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2027 SmallVectorImpl<const SCEV *> &NewOps, 2028 APInt &AccumulatedConstant, 2029 const SCEV *const *Ops, size_t NumOperands, 2030 const APInt &Scale, 2031 ScalarEvolution &SE) { 2032 bool Interesting = false; 2033 2034 // Iterate over the add operands. They are sorted, with constants first. 2035 unsigned i = 0; 2036 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2037 ++i; 2038 // Pull a buried constant out to the outside. 2039 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2040 Interesting = true; 2041 AccumulatedConstant += Scale * C->getAPInt(); 2042 } 2043 2044 // Next comes everything else. We're especially interested in multiplies 2045 // here, but they're in the middle, so just visit the rest with one loop. 2046 for (; i != NumOperands; ++i) { 2047 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2048 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2049 APInt NewScale = 2050 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2051 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2052 // A multiplication of a constant with another add; recurse. 2053 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2054 Interesting |= 2055 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2056 Add->op_begin(), Add->getNumOperands(), 2057 NewScale, SE); 2058 } else { 2059 // A multiplication of a constant with some other value. Update 2060 // the map. 2061 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2062 const SCEV *Key = SE.getMulExpr(MulOps); 2063 auto Pair = M.insert({Key, NewScale}); 2064 if (Pair.second) { 2065 NewOps.push_back(Pair.first->first); 2066 } else { 2067 Pair.first->second += NewScale; 2068 // The map already had an entry for this value, which may indicate 2069 // a folding opportunity. 2070 Interesting = true; 2071 } 2072 } 2073 } else { 2074 // An ordinary operand. Update the map. 2075 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2076 M.insert({Ops[i], Scale}); 2077 if (Pair.second) { 2078 NewOps.push_back(Pair.first->first); 2079 } else { 2080 Pair.first->second += Scale; 2081 // The map already had an entry for this value, which may indicate 2082 // a folding opportunity. 2083 Interesting = true; 2084 } 2085 } 2086 } 2087 2088 return Interesting; 2089 } 2090 2091 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2092 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2093 // can't-overflow flags for the operation if possible. 2094 static SCEV::NoWrapFlags 2095 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2096 const ArrayRef<const SCEV *> Ops, 2097 SCEV::NoWrapFlags Flags) { 2098 using namespace std::placeholders; 2099 2100 using OBO = OverflowingBinaryOperator; 2101 2102 bool CanAnalyze = 2103 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2104 (void)CanAnalyze; 2105 assert(CanAnalyze && "don't call from other places!"); 2106 2107 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2108 SCEV::NoWrapFlags SignOrUnsignWrap = 2109 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2110 2111 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2112 auto IsKnownNonNegative = [&](const SCEV *S) { 2113 return SE->isKnownNonNegative(S); 2114 }; 2115 2116 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2117 Flags = 2118 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2119 2120 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2121 2122 if (SignOrUnsignWrap != SignOrUnsignMask && 2123 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2124 isa<SCEVConstant>(Ops[0])) { 2125 2126 auto Opcode = [&] { 2127 switch (Type) { 2128 case scAddExpr: 2129 return Instruction::Add; 2130 case scMulExpr: 2131 return Instruction::Mul; 2132 default: 2133 llvm_unreachable("Unexpected SCEV op."); 2134 } 2135 }(); 2136 2137 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2138 2139 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2140 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2141 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2142 Opcode, C, OBO::NoSignedWrap); 2143 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2144 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2145 } 2146 2147 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2148 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2149 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2150 Opcode, C, OBO::NoUnsignedWrap); 2151 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2152 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2153 } 2154 } 2155 2156 return Flags; 2157 } 2158 2159 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2160 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2161 } 2162 2163 /// Get a canonical add expression, or something simpler if possible. 2164 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2165 SCEV::NoWrapFlags Flags, 2166 unsigned Depth) { 2167 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2168 "only nuw or nsw allowed"); 2169 assert(!Ops.empty() && "Cannot get empty add!"); 2170 if (Ops.size() == 1) return Ops[0]; 2171 #ifndef NDEBUG 2172 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2173 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2174 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2175 "SCEVAddExpr operand types don't match!"); 2176 #endif 2177 2178 // Sort by complexity, this groups all similar expression types together. 2179 GroupByComplexity(Ops, &LI, DT); 2180 2181 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2182 2183 // If there are any constants, fold them together. 2184 unsigned Idx = 0; 2185 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2186 ++Idx; 2187 assert(Idx < Ops.size()); 2188 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2189 // We found two constants, fold them together! 2190 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2191 if (Ops.size() == 2) return Ops[0]; 2192 Ops.erase(Ops.begin()+1); // Erase the folded element 2193 LHSC = cast<SCEVConstant>(Ops[0]); 2194 } 2195 2196 // If we are left with a constant zero being added, strip it off. 2197 if (LHSC->getValue()->isZero()) { 2198 Ops.erase(Ops.begin()); 2199 --Idx; 2200 } 2201 2202 if (Ops.size() == 1) return Ops[0]; 2203 } 2204 2205 // Limit recursion calls depth. 2206 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2207 return getOrCreateAddExpr(Ops, Flags); 2208 2209 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2210 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2211 return S; 2212 } 2213 2214 // Okay, check to see if the same value occurs in the operand list more than 2215 // once. If so, merge them together into an multiply expression. Since we 2216 // sorted the list, these values are required to be adjacent. 2217 Type *Ty = Ops[0]->getType(); 2218 bool FoundMatch = false; 2219 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2220 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2221 // Scan ahead to count how many equal operands there are. 2222 unsigned Count = 2; 2223 while (i+Count != e && Ops[i+Count] == Ops[i]) 2224 ++Count; 2225 // Merge the values into a multiply. 2226 const SCEV *Scale = getConstant(Ty, Count); 2227 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2228 if (Ops.size() == Count) 2229 return Mul; 2230 Ops[i] = Mul; 2231 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2232 --i; e -= Count - 1; 2233 FoundMatch = true; 2234 } 2235 if (FoundMatch) 2236 return getAddExpr(Ops, Flags, Depth + 1); 2237 2238 // Check for truncates. If all the operands are truncated from the same 2239 // type, see if factoring out the truncate would permit the result to be 2240 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2241 // if the contents of the resulting outer trunc fold to something simple. 2242 auto FindTruncSrcType = [&]() -> Type * { 2243 // We're ultimately looking to fold an addrec of truncs and muls of only 2244 // constants and truncs, so if we find any other types of SCEV 2245 // as operands of the addrec then we bail and return nullptr here. 2246 // Otherwise, we return the type of the operand of a trunc that we find. 2247 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2248 return T->getOperand()->getType(); 2249 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2250 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2251 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2252 return T->getOperand()->getType(); 2253 } 2254 return nullptr; 2255 }; 2256 if (auto *SrcType = FindTruncSrcType()) { 2257 SmallVector<const SCEV *, 8> LargeOps; 2258 bool Ok = true; 2259 // Check all the operands to see if they can be represented in the 2260 // source type of the truncate. 2261 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2262 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2263 if (T->getOperand()->getType() != SrcType) { 2264 Ok = false; 2265 break; 2266 } 2267 LargeOps.push_back(T->getOperand()); 2268 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2269 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2270 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2271 SmallVector<const SCEV *, 8> LargeMulOps; 2272 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2273 if (const SCEVTruncateExpr *T = 2274 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2275 if (T->getOperand()->getType() != SrcType) { 2276 Ok = false; 2277 break; 2278 } 2279 LargeMulOps.push_back(T->getOperand()); 2280 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2281 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2282 } else { 2283 Ok = false; 2284 break; 2285 } 2286 } 2287 if (Ok) 2288 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2289 } else { 2290 Ok = false; 2291 break; 2292 } 2293 } 2294 if (Ok) { 2295 // Evaluate the expression in the larger type. 2296 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2297 // If it folds to something simple, use it. Otherwise, don't. 2298 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2299 return getTruncateExpr(Fold, Ty); 2300 } 2301 } 2302 2303 // Skip past any other cast SCEVs. 2304 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2305 ++Idx; 2306 2307 // If there are add operands they would be next. 2308 if (Idx < Ops.size()) { 2309 bool DeletedAdd = false; 2310 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2311 if (Ops.size() > AddOpsInlineThreshold || 2312 Add->getNumOperands() > AddOpsInlineThreshold) 2313 break; 2314 // If we have an add, expand the add operands onto the end of the operands 2315 // list. 2316 Ops.erase(Ops.begin()+Idx); 2317 Ops.append(Add->op_begin(), Add->op_end()); 2318 DeletedAdd = true; 2319 } 2320 2321 // If we deleted at least one add, we added operands to the end of the list, 2322 // and they are not necessarily sorted. Recurse to resort and resimplify 2323 // any operands we just acquired. 2324 if (DeletedAdd) 2325 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2326 } 2327 2328 // Skip over the add expression until we get to a multiply. 2329 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2330 ++Idx; 2331 2332 // Check to see if there are any folding opportunities present with 2333 // operands multiplied by constant values. 2334 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2335 uint64_t BitWidth = getTypeSizeInBits(Ty); 2336 DenseMap<const SCEV *, APInt> M; 2337 SmallVector<const SCEV *, 8> NewOps; 2338 APInt AccumulatedConstant(BitWidth, 0); 2339 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2340 Ops.data(), Ops.size(), 2341 APInt(BitWidth, 1), *this)) { 2342 struct APIntCompare { 2343 bool operator()(const APInt &LHS, const APInt &RHS) const { 2344 return LHS.ult(RHS); 2345 } 2346 }; 2347 2348 // Some interesting folding opportunity is present, so its worthwhile to 2349 // re-generate the operands list. Group the operands by constant scale, 2350 // to avoid multiplying by the same constant scale multiple times. 2351 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2352 for (const SCEV *NewOp : NewOps) 2353 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2354 // Re-generate the operands list. 2355 Ops.clear(); 2356 if (AccumulatedConstant != 0) 2357 Ops.push_back(getConstant(AccumulatedConstant)); 2358 for (auto &MulOp : MulOpLists) 2359 if (MulOp.first != 0) 2360 Ops.push_back(getMulExpr( 2361 getConstant(MulOp.first), 2362 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2363 SCEV::FlagAnyWrap, Depth + 1)); 2364 if (Ops.empty()) 2365 return getZero(Ty); 2366 if (Ops.size() == 1) 2367 return Ops[0]; 2368 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2369 } 2370 } 2371 2372 // If we are adding something to a multiply expression, make sure the 2373 // something is not already an operand of the multiply. If so, merge it into 2374 // the multiply. 2375 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2376 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2377 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2378 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2379 if (isa<SCEVConstant>(MulOpSCEV)) 2380 continue; 2381 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2382 if (MulOpSCEV == Ops[AddOp]) { 2383 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2384 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2385 if (Mul->getNumOperands() != 2) { 2386 // If the multiply has more than two operands, we must get the 2387 // Y*Z term. 2388 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2389 Mul->op_begin()+MulOp); 2390 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2391 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2392 } 2393 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2394 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2395 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2396 SCEV::FlagAnyWrap, Depth + 1); 2397 if (Ops.size() == 2) return OuterMul; 2398 if (AddOp < Idx) { 2399 Ops.erase(Ops.begin()+AddOp); 2400 Ops.erase(Ops.begin()+Idx-1); 2401 } else { 2402 Ops.erase(Ops.begin()+Idx); 2403 Ops.erase(Ops.begin()+AddOp-1); 2404 } 2405 Ops.push_back(OuterMul); 2406 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2407 } 2408 2409 // Check this multiply against other multiplies being added together. 2410 for (unsigned OtherMulIdx = Idx+1; 2411 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2412 ++OtherMulIdx) { 2413 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2414 // If MulOp occurs in OtherMul, we can fold the two multiplies 2415 // together. 2416 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2417 OMulOp != e; ++OMulOp) 2418 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2419 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2420 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2421 if (Mul->getNumOperands() != 2) { 2422 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2423 Mul->op_begin()+MulOp); 2424 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2425 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2426 } 2427 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2428 if (OtherMul->getNumOperands() != 2) { 2429 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2430 OtherMul->op_begin()+OMulOp); 2431 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2432 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2433 } 2434 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2435 const SCEV *InnerMulSum = 2436 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2437 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2438 SCEV::FlagAnyWrap, Depth + 1); 2439 if (Ops.size() == 2) return OuterMul; 2440 Ops.erase(Ops.begin()+Idx); 2441 Ops.erase(Ops.begin()+OtherMulIdx-1); 2442 Ops.push_back(OuterMul); 2443 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2444 } 2445 } 2446 } 2447 } 2448 2449 // If there are any add recurrences in the operands list, see if any other 2450 // added values are loop invariant. If so, we can fold them into the 2451 // recurrence. 2452 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2453 ++Idx; 2454 2455 // Scan over all recurrences, trying to fold loop invariants into them. 2456 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2457 // Scan all of the other operands to this add and add them to the vector if 2458 // they are loop invariant w.r.t. the recurrence. 2459 SmallVector<const SCEV *, 8> LIOps; 2460 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2461 const Loop *AddRecLoop = AddRec->getLoop(); 2462 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2463 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2464 LIOps.push_back(Ops[i]); 2465 Ops.erase(Ops.begin()+i); 2466 --i; --e; 2467 } 2468 2469 // If we found some loop invariants, fold them into the recurrence. 2470 if (!LIOps.empty()) { 2471 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2472 LIOps.push_back(AddRec->getStart()); 2473 2474 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2475 AddRec->op_end()); 2476 // This follows from the fact that the no-wrap flags on the outer add 2477 // expression are applicable on the 0th iteration, when the add recurrence 2478 // will be equal to its start value. 2479 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2480 2481 // Build the new addrec. Propagate the NUW and NSW flags if both the 2482 // outer add and the inner addrec are guaranteed to have no overflow. 2483 // Always propagate NW. 2484 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2485 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2486 2487 // If all of the other operands were loop invariant, we are done. 2488 if (Ops.size() == 1) return NewRec; 2489 2490 // Otherwise, add the folded AddRec by the non-invariant parts. 2491 for (unsigned i = 0;; ++i) 2492 if (Ops[i] == AddRec) { 2493 Ops[i] = NewRec; 2494 break; 2495 } 2496 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2497 } 2498 2499 // Okay, if there weren't any loop invariants to be folded, check to see if 2500 // there are multiple AddRec's with the same loop induction variable being 2501 // added together. If so, we can fold them. 2502 for (unsigned OtherIdx = Idx+1; 2503 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2504 ++OtherIdx) { 2505 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2506 // so that the 1st found AddRecExpr is dominated by all others. 2507 assert(DT.dominates( 2508 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2509 AddRec->getLoop()->getHeader()) && 2510 "AddRecExprs are not sorted in reverse dominance order?"); 2511 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2512 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2513 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2514 AddRec->op_end()); 2515 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2516 ++OtherIdx) { 2517 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2518 if (OtherAddRec->getLoop() == AddRecLoop) { 2519 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2520 i != e; ++i) { 2521 if (i >= AddRecOps.size()) { 2522 AddRecOps.append(OtherAddRec->op_begin()+i, 2523 OtherAddRec->op_end()); 2524 break; 2525 } 2526 SmallVector<const SCEV *, 2> TwoOps = { 2527 AddRecOps[i], OtherAddRec->getOperand(i)}; 2528 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2529 } 2530 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2531 } 2532 } 2533 // Step size has changed, so we cannot guarantee no self-wraparound. 2534 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2535 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2536 } 2537 } 2538 2539 // Otherwise couldn't fold anything into this recurrence. Move onto the 2540 // next one. 2541 } 2542 2543 // Okay, it looks like we really DO need an add expr. Check to see if we 2544 // already have one, otherwise create a new one. 2545 return getOrCreateAddExpr(Ops, Flags); 2546 } 2547 2548 const SCEV * 2549 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2550 SCEV::NoWrapFlags Flags) { 2551 FoldingSetNodeID ID; 2552 ID.AddInteger(scAddExpr); 2553 for (const SCEV *Op : Ops) 2554 ID.AddPointer(Op); 2555 void *IP = nullptr; 2556 SCEVAddExpr *S = 2557 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2558 if (!S) { 2559 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2560 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2561 S = new (SCEVAllocator) 2562 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2563 UniqueSCEVs.InsertNode(S, IP); 2564 addToLoopUseLists(S); 2565 } 2566 S->setNoWrapFlags(Flags); 2567 return S; 2568 } 2569 2570 const SCEV * 2571 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2572 const Loop *L, SCEV::NoWrapFlags Flags) { 2573 FoldingSetNodeID ID; 2574 ID.AddInteger(scAddRecExpr); 2575 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2576 ID.AddPointer(Ops[i]); 2577 ID.AddPointer(L); 2578 void *IP = nullptr; 2579 SCEVAddRecExpr *S = 2580 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2581 if (!S) { 2582 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2583 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2584 S = new (SCEVAllocator) 2585 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2586 UniqueSCEVs.InsertNode(S, IP); 2587 addToLoopUseLists(S); 2588 } 2589 S->setNoWrapFlags(Flags); 2590 return S; 2591 } 2592 2593 const SCEV * 2594 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2595 SCEV::NoWrapFlags Flags) { 2596 FoldingSetNodeID ID; 2597 ID.AddInteger(scMulExpr); 2598 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2599 ID.AddPointer(Ops[i]); 2600 void *IP = nullptr; 2601 SCEVMulExpr *S = 2602 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2603 if (!S) { 2604 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2605 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2606 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2607 O, Ops.size()); 2608 UniqueSCEVs.InsertNode(S, IP); 2609 addToLoopUseLists(S); 2610 } 2611 S->setNoWrapFlags(Flags); 2612 return S; 2613 } 2614 2615 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2616 uint64_t k = i*j; 2617 if (j > 1 && k / j != i) Overflow = true; 2618 return k; 2619 } 2620 2621 /// Compute the result of "n choose k", the binomial coefficient. If an 2622 /// intermediate computation overflows, Overflow will be set and the return will 2623 /// be garbage. Overflow is not cleared on absence of overflow. 2624 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2625 // We use the multiplicative formula: 2626 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2627 // At each iteration, we take the n-th term of the numeral and divide by the 2628 // (k-n)th term of the denominator. This division will always produce an 2629 // integral result, and helps reduce the chance of overflow in the 2630 // intermediate computations. However, we can still overflow even when the 2631 // final result would fit. 2632 2633 if (n == 0 || n == k) return 1; 2634 if (k > n) return 0; 2635 2636 if (k > n/2) 2637 k = n-k; 2638 2639 uint64_t r = 1; 2640 for (uint64_t i = 1; i <= k; ++i) { 2641 r = umul_ov(r, n-(i-1), Overflow); 2642 r /= i; 2643 } 2644 return r; 2645 } 2646 2647 /// Determine if any of the operands in this SCEV are a constant or if 2648 /// any of the add or multiply expressions in this SCEV contain a constant. 2649 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2650 struct FindConstantInAddMulChain { 2651 bool FoundConstant = false; 2652 2653 bool follow(const SCEV *S) { 2654 FoundConstant |= isa<SCEVConstant>(S); 2655 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2656 } 2657 2658 bool isDone() const { 2659 return FoundConstant; 2660 } 2661 }; 2662 2663 FindConstantInAddMulChain F; 2664 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2665 ST.visitAll(StartExpr); 2666 return F.FoundConstant; 2667 } 2668 2669 /// Get a canonical multiply expression, or something simpler if possible. 2670 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2671 SCEV::NoWrapFlags Flags, 2672 unsigned Depth) { 2673 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2674 "only nuw or nsw allowed"); 2675 assert(!Ops.empty() && "Cannot get empty mul!"); 2676 if (Ops.size() == 1) return Ops[0]; 2677 #ifndef NDEBUG 2678 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2679 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2680 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2681 "SCEVMulExpr operand types don't match!"); 2682 #endif 2683 2684 // Sort by complexity, this groups all similar expression types together. 2685 GroupByComplexity(Ops, &LI, DT); 2686 2687 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2688 2689 // Limit recursion calls depth, but fold all-constant expressions. 2690 // `Ops` is sorted, so it's enough to check just last one. 2691 if ((Depth > MaxArithDepth || hasHugeExpression(Ops)) && 2692 !isa<SCEVConstant>(Ops.back())) 2693 return getOrCreateMulExpr(Ops, Flags); 2694 2695 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2696 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2697 return S; 2698 } 2699 2700 // If there are any constants, fold them together. 2701 unsigned Idx = 0; 2702 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2703 2704 if (Ops.size() == 2) 2705 // C1*(C2+V) -> C1*C2 + C1*V 2706 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2707 // If any of Add's ops are Adds or Muls with a constant, apply this 2708 // transformation as well. 2709 // 2710 // TODO: There are some cases where this transformation is not 2711 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2712 // this transformation should be narrowed down. 2713 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2714 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2715 SCEV::FlagAnyWrap, Depth + 1), 2716 getMulExpr(LHSC, Add->getOperand(1), 2717 SCEV::FlagAnyWrap, Depth + 1), 2718 SCEV::FlagAnyWrap, Depth + 1); 2719 2720 ++Idx; 2721 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2722 // We found two constants, fold them together! 2723 ConstantInt *Fold = 2724 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2725 Ops[0] = getConstant(Fold); 2726 Ops.erase(Ops.begin()+1); // Erase the folded element 2727 if (Ops.size() == 1) return Ops[0]; 2728 LHSC = cast<SCEVConstant>(Ops[0]); 2729 } 2730 2731 // If we are left with a constant one being multiplied, strip it off. 2732 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2733 Ops.erase(Ops.begin()); 2734 --Idx; 2735 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2736 // If we have a multiply of zero, it will always be zero. 2737 return Ops[0]; 2738 } else if (Ops[0]->isAllOnesValue()) { 2739 // If we have a mul by -1 of an add, try distributing the -1 among the 2740 // add operands. 2741 if (Ops.size() == 2) { 2742 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2743 SmallVector<const SCEV *, 4> NewOps; 2744 bool AnyFolded = false; 2745 for (const SCEV *AddOp : Add->operands()) { 2746 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2747 Depth + 1); 2748 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2749 NewOps.push_back(Mul); 2750 } 2751 if (AnyFolded) 2752 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2753 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2754 // Negation preserves a recurrence's no self-wrap property. 2755 SmallVector<const SCEV *, 4> Operands; 2756 for (const SCEV *AddRecOp : AddRec->operands()) 2757 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2758 Depth + 1)); 2759 2760 return getAddRecExpr(Operands, AddRec->getLoop(), 2761 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2762 } 2763 } 2764 } 2765 2766 if (Ops.size() == 1) 2767 return Ops[0]; 2768 } 2769 2770 // Skip over the add expression until we get to a multiply. 2771 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2772 ++Idx; 2773 2774 // If there are mul operands inline them all into this expression. 2775 if (Idx < Ops.size()) { 2776 bool DeletedMul = false; 2777 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2778 if (Ops.size() > MulOpsInlineThreshold) 2779 break; 2780 // If we have an mul, expand the mul operands onto the end of the 2781 // operands list. 2782 Ops.erase(Ops.begin()+Idx); 2783 Ops.append(Mul->op_begin(), Mul->op_end()); 2784 DeletedMul = true; 2785 } 2786 2787 // If we deleted at least one mul, we added operands to the end of the 2788 // list, and they are not necessarily sorted. Recurse to resort and 2789 // resimplify any operands we just acquired. 2790 if (DeletedMul) 2791 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2792 } 2793 2794 // If there are any add recurrences in the operands list, see if any other 2795 // added values are loop invariant. If so, we can fold them into the 2796 // recurrence. 2797 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2798 ++Idx; 2799 2800 // Scan over all recurrences, trying to fold loop invariants into them. 2801 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2802 // Scan all of the other operands to this mul and add them to the vector 2803 // if they are loop invariant w.r.t. the recurrence. 2804 SmallVector<const SCEV *, 8> LIOps; 2805 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2806 const Loop *AddRecLoop = AddRec->getLoop(); 2807 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2808 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2809 LIOps.push_back(Ops[i]); 2810 Ops.erase(Ops.begin()+i); 2811 --i; --e; 2812 } 2813 2814 // If we found some loop invariants, fold them into the recurrence. 2815 if (!LIOps.empty()) { 2816 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2817 SmallVector<const SCEV *, 4> NewOps; 2818 NewOps.reserve(AddRec->getNumOperands()); 2819 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2820 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2821 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2822 SCEV::FlagAnyWrap, Depth + 1)); 2823 2824 // Build the new addrec. Propagate the NUW and NSW flags if both the 2825 // outer mul and the inner addrec are guaranteed to have no overflow. 2826 // 2827 // No self-wrap cannot be guaranteed after changing the step size, but 2828 // will be inferred if either NUW or NSW is true. 2829 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2830 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2831 2832 // If all of the other operands were loop invariant, we are done. 2833 if (Ops.size() == 1) return NewRec; 2834 2835 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2836 for (unsigned i = 0;; ++i) 2837 if (Ops[i] == AddRec) { 2838 Ops[i] = NewRec; 2839 break; 2840 } 2841 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2842 } 2843 2844 // Okay, if there weren't any loop invariants to be folded, check to see 2845 // if there are multiple AddRec's with the same loop induction variable 2846 // being multiplied together. If so, we can fold them. 2847 2848 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2849 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2850 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2851 // ]]],+,...up to x=2n}. 2852 // Note that the arguments to choose() are always integers with values 2853 // known at compile time, never SCEV objects. 2854 // 2855 // The implementation avoids pointless extra computations when the two 2856 // addrec's are of different length (mathematically, it's equivalent to 2857 // an infinite stream of zeros on the right). 2858 bool OpsModified = false; 2859 for (unsigned OtherIdx = Idx+1; 2860 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2861 ++OtherIdx) { 2862 const SCEVAddRecExpr *OtherAddRec = 2863 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2864 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2865 continue; 2866 2867 // Limit max number of arguments to avoid creation of unreasonably big 2868 // SCEVAddRecs with very complex operands. 2869 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2870 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 2871 continue; 2872 2873 bool Overflow = false; 2874 Type *Ty = AddRec->getType(); 2875 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2876 SmallVector<const SCEV*, 7> AddRecOps; 2877 for (int x = 0, xe = AddRec->getNumOperands() + 2878 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2879 SmallVector <const SCEV *, 7> SumOps; 2880 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2881 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2882 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2883 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2884 z < ze && !Overflow; ++z) { 2885 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2886 uint64_t Coeff; 2887 if (LargerThan64Bits) 2888 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2889 else 2890 Coeff = Coeff1*Coeff2; 2891 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2892 const SCEV *Term1 = AddRec->getOperand(y-z); 2893 const SCEV *Term2 = OtherAddRec->getOperand(z); 2894 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 2895 SCEV::FlagAnyWrap, Depth + 1)); 2896 } 2897 } 2898 if (SumOps.empty()) 2899 SumOps.push_back(getZero(Ty)); 2900 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 2901 } 2902 if (!Overflow) { 2903 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 2904 SCEV::FlagAnyWrap); 2905 if (Ops.size() == 2) return NewAddRec; 2906 Ops[Idx] = NewAddRec; 2907 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2908 OpsModified = true; 2909 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2910 if (!AddRec) 2911 break; 2912 } 2913 } 2914 if (OpsModified) 2915 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2916 2917 // Otherwise couldn't fold anything into this recurrence. Move onto the 2918 // next one. 2919 } 2920 2921 // Okay, it looks like we really DO need an mul expr. Check to see if we 2922 // already have one, otherwise create a new one. 2923 return getOrCreateMulExpr(Ops, Flags); 2924 } 2925 2926 /// Represents an unsigned remainder expression based on unsigned division. 2927 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 2928 const SCEV *RHS) { 2929 assert(getEffectiveSCEVType(LHS->getType()) == 2930 getEffectiveSCEVType(RHS->getType()) && 2931 "SCEVURemExpr operand types don't match!"); 2932 2933 // Short-circuit easy cases 2934 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2935 // If constant is one, the result is trivial 2936 if (RHSC->getValue()->isOne()) 2937 return getZero(LHS->getType()); // X urem 1 --> 0 2938 2939 // If constant is a power of two, fold into a zext(trunc(LHS)). 2940 if (RHSC->getAPInt().isPowerOf2()) { 2941 Type *FullTy = LHS->getType(); 2942 Type *TruncTy = 2943 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 2944 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 2945 } 2946 } 2947 2948 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 2949 const SCEV *UDiv = getUDivExpr(LHS, RHS); 2950 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 2951 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 2952 } 2953 2954 /// Get a canonical unsigned division expression, or something simpler if 2955 /// possible. 2956 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2957 const SCEV *RHS) { 2958 assert(getEffectiveSCEVType(LHS->getType()) == 2959 getEffectiveSCEVType(RHS->getType()) && 2960 "SCEVUDivExpr operand types don't match!"); 2961 2962 FoldingSetNodeID ID; 2963 ID.AddInteger(scUDivExpr); 2964 ID.AddPointer(LHS); 2965 ID.AddPointer(RHS); 2966 void *IP = nullptr; 2967 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 2968 return S; 2969 2970 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2971 if (RHSC->getValue()->isOne()) 2972 return LHS; // X udiv 1 --> x 2973 // If the denominator is zero, the result of the udiv is undefined. Don't 2974 // try to analyze it, because the resolution chosen here may differ from 2975 // the resolution chosen in other parts of the compiler. 2976 if (!RHSC->getValue()->isZero()) { 2977 // Determine if the division can be folded into the operands of 2978 // its operands. 2979 // TODO: Generalize this to non-constants by using known-bits information. 2980 Type *Ty = LHS->getType(); 2981 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2982 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2983 // For non-power-of-two values, effectively round the value up to the 2984 // nearest power of two. 2985 if (!RHSC->getAPInt().isPowerOf2()) 2986 ++MaxShiftAmt; 2987 IntegerType *ExtTy = 2988 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2989 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2990 if (const SCEVConstant *Step = 2991 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2992 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2993 const APInt &StepInt = Step->getAPInt(); 2994 const APInt &DivInt = RHSC->getAPInt(); 2995 if (!StepInt.urem(DivInt) && 2996 getZeroExtendExpr(AR, ExtTy) == 2997 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2998 getZeroExtendExpr(Step, ExtTy), 2999 AR->getLoop(), SCEV::FlagAnyWrap)) { 3000 SmallVector<const SCEV *, 4> Operands; 3001 for (const SCEV *Op : AR->operands()) 3002 Operands.push_back(getUDivExpr(Op, RHS)); 3003 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3004 } 3005 /// Get a canonical UDivExpr for a recurrence. 3006 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3007 // We can currently only fold X%N if X is constant. 3008 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3009 if (StartC && !DivInt.urem(StepInt) && 3010 getZeroExtendExpr(AR, ExtTy) == 3011 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3012 getZeroExtendExpr(Step, ExtTy), 3013 AR->getLoop(), SCEV::FlagAnyWrap)) { 3014 const APInt &StartInt = StartC->getAPInt(); 3015 const APInt &StartRem = StartInt.urem(StepInt); 3016 if (StartRem != 0) { 3017 const SCEV *NewLHS = 3018 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3019 AR->getLoop(), SCEV::FlagNW); 3020 if (LHS != NewLHS) { 3021 LHS = NewLHS; 3022 3023 // Reset the ID to include the new LHS, and check if it is 3024 // already cached. 3025 ID.clear(); 3026 ID.AddInteger(scUDivExpr); 3027 ID.AddPointer(LHS); 3028 ID.AddPointer(RHS); 3029 IP = nullptr; 3030 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3031 return S; 3032 } 3033 } 3034 } 3035 } 3036 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3037 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3038 SmallVector<const SCEV *, 4> Operands; 3039 for (const SCEV *Op : M->operands()) 3040 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3041 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3042 // Find an operand that's safely divisible. 3043 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3044 const SCEV *Op = M->getOperand(i); 3045 const SCEV *Div = getUDivExpr(Op, RHSC); 3046 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3047 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3048 M->op_end()); 3049 Operands[i] = Div; 3050 return getMulExpr(Operands); 3051 } 3052 } 3053 } 3054 3055 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3056 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3057 if (auto *DivisorConstant = 3058 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3059 bool Overflow = false; 3060 APInt NewRHS = 3061 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3062 if (Overflow) { 3063 return getConstant(RHSC->getType(), 0, false); 3064 } 3065 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3066 } 3067 } 3068 3069 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3070 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3071 SmallVector<const SCEV *, 4> Operands; 3072 for (const SCEV *Op : A->operands()) 3073 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3074 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3075 Operands.clear(); 3076 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3077 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3078 if (isa<SCEVUDivExpr>(Op) || 3079 getMulExpr(Op, RHS) != A->getOperand(i)) 3080 break; 3081 Operands.push_back(Op); 3082 } 3083 if (Operands.size() == A->getNumOperands()) 3084 return getAddExpr(Operands); 3085 } 3086 } 3087 3088 // Fold if both operands are constant. 3089 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3090 Constant *LHSCV = LHSC->getValue(); 3091 Constant *RHSCV = RHSC->getValue(); 3092 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3093 RHSCV))); 3094 } 3095 } 3096 } 3097 3098 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3099 // changes). Make sure we get a new one. 3100 IP = nullptr; 3101 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3102 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3103 LHS, RHS); 3104 UniqueSCEVs.InsertNode(S, IP); 3105 addToLoopUseLists(S); 3106 return S; 3107 } 3108 3109 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3110 APInt A = C1->getAPInt().abs(); 3111 APInt B = C2->getAPInt().abs(); 3112 uint32_t ABW = A.getBitWidth(); 3113 uint32_t BBW = B.getBitWidth(); 3114 3115 if (ABW > BBW) 3116 B = B.zext(ABW); 3117 else if (ABW < BBW) 3118 A = A.zext(BBW); 3119 3120 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3121 } 3122 3123 /// Get a canonical unsigned division expression, or something simpler if 3124 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3125 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3126 /// it's not exact because the udiv may be clearing bits. 3127 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3128 const SCEV *RHS) { 3129 // TODO: we could try to find factors in all sorts of things, but for now we 3130 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3131 // end of this file for inspiration. 3132 3133 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3134 if (!Mul || !Mul->hasNoUnsignedWrap()) 3135 return getUDivExpr(LHS, RHS); 3136 3137 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3138 // If the mulexpr multiplies by a constant, then that constant must be the 3139 // first element of the mulexpr. 3140 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3141 if (LHSCst == RHSCst) { 3142 SmallVector<const SCEV *, 2> Operands; 3143 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3144 return getMulExpr(Operands); 3145 } 3146 3147 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3148 // that there's a factor provided by one of the other terms. We need to 3149 // check. 3150 APInt Factor = gcd(LHSCst, RHSCst); 3151 if (!Factor.isIntN(1)) { 3152 LHSCst = 3153 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3154 RHSCst = 3155 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3156 SmallVector<const SCEV *, 2> Operands; 3157 Operands.push_back(LHSCst); 3158 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3159 LHS = getMulExpr(Operands); 3160 RHS = RHSCst; 3161 Mul = dyn_cast<SCEVMulExpr>(LHS); 3162 if (!Mul) 3163 return getUDivExactExpr(LHS, RHS); 3164 } 3165 } 3166 } 3167 3168 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3169 if (Mul->getOperand(i) == RHS) { 3170 SmallVector<const SCEV *, 2> Operands; 3171 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3172 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3173 return getMulExpr(Operands); 3174 } 3175 } 3176 3177 return getUDivExpr(LHS, RHS); 3178 } 3179 3180 /// Get an add recurrence expression for the specified loop. Simplify the 3181 /// expression as much as possible. 3182 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3183 const Loop *L, 3184 SCEV::NoWrapFlags Flags) { 3185 SmallVector<const SCEV *, 4> Operands; 3186 Operands.push_back(Start); 3187 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3188 if (StepChrec->getLoop() == L) { 3189 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3190 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3191 } 3192 3193 Operands.push_back(Step); 3194 return getAddRecExpr(Operands, L, Flags); 3195 } 3196 3197 /// Get an add recurrence expression for the specified loop. Simplify the 3198 /// expression as much as possible. 3199 const SCEV * 3200 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3201 const Loop *L, SCEV::NoWrapFlags Flags) { 3202 if (Operands.size() == 1) return Operands[0]; 3203 #ifndef NDEBUG 3204 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3205 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3206 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3207 "SCEVAddRecExpr operand types don't match!"); 3208 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3209 assert(isLoopInvariant(Operands[i], L) && 3210 "SCEVAddRecExpr operand is not loop-invariant!"); 3211 #endif 3212 3213 if (Operands.back()->isZero()) { 3214 Operands.pop_back(); 3215 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3216 } 3217 3218 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3219 // use that information to infer NUW and NSW flags. However, computing a 3220 // BE count requires calling getAddRecExpr, so we may not yet have a 3221 // meaningful BE count at this point (and if we don't, we'd be stuck 3222 // with a SCEVCouldNotCompute as the cached BE count). 3223 3224 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3225 3226 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3227 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3228 const Loop *NestedLoop = NestedAR->getLoop(); 3229 if (L->contains(NestedLoop) 3230 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3231 : (!NestedLoop->contains(L) && 3232 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3233 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3234 NestedAR->op_end()); 3235 Operands[0] = NestedAR->getStart(); 3236 // AddRecs require their operands be loop-invariant with respect to their 3237 // loops. Don't perform this transformation if it would break this 3238 // requirement. 3239 bool AllInvariant = all_of( 3240 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3241 3242 if (AllInvariant) { 3243 // Create a recurrence for the outer loop with the same step size. 3244 // 3245 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3246 // inner recurrence has the same property. 3247 SCEV::NoWrapFlags OuterFlags = 3248 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3249 3250 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3251 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3252 return isLoopInvariant(Op, NestedLoop); 3253 }); 3254 3255 if (AllInvariant) { 3256 // Ok, both add recurrences are valid after the transformation. 3257 // 3258 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3259 // the outer recurrence has the same property. 3260 SCEV::NoWrapFlags InnerFlags = 3261 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3262 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3263 } 3264 } 3265 // Reset Operands to its original state. 3266 Operands[0] = NestedAR; 3267 } 3268 } 3269 3270 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3271 // already have one, otherwise create a new one. 3272 return getOrCreateAddRecExpr(Operands, L, Flags); 3273 } 3274 3275 const SCEV * 3276 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3277 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3278 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3279 // getSCEV(Base)->getType() has the same address space as Base->getType() 3280 // because SCEV::getType() preserves the address space. 3281 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3282 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3283 // instruction to its SCEV, because the Instruction may be guarded by control 3284 // flow and the no-overflow bits may not be valid for the expression in any 3285 // context. This can be fixed similarly to how these flags are handled for 3286 // adds. 3287 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3288 : SCEV::FlagAnyWrap; 3289 3290 const SCEV *TotalOffset = getZero(IntIdxTy); 3291 Type *CurTy = GEP->getType(); 3292 bool FirstIter = true; 3293 for (const SCEV *IndexExpr : IndexExprs) { 3294 // Compute the (potentially symbolic) offset in bytes for this index. 3295 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3296 // For a struct, add the member offset. 3297 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3298 unsigned FieldNo = Index->getZExtValue(); 3299 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3300 3301 // Add the field offset to the running total offset. 3302 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3303 3304 // Update CurTy to the type of the field at Index. 3305 CurTy = STy->getTypeAtIndex(Index); 3306 } else { 3307 // Update CurTy to its element type. 3308 if (FirstIter) { 3309 assert(isa<PointerType>(CurTy) && 3310 "The first index of a GEP indexes a pointer"); 3311 CurTy = GEP->getSourceElementType(); 3312 FirstIter = false; 3313 } else { 3314 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3315 } 3316 // For an array, add the element offset, explicitly scaled. 3317 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3318 // Getelementptr indices are signed. 3319 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3320 3321 // Multiply the index by the element size to compute the element offset. 3322 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3323 3324 // Add the element offset to the running total offset. 3325 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3326 } 3327 } 3328 3329 // Add the total offset from all the GEP indices to the base. 3330 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3331 } 3332 3333 std::tuple<SCEV *, FoldingSetNodeID, void *> 3334 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3335 ArrayRef<const SCEV *> Ops) { 3336 FoldingSetNodeID ID; 3337 void *IP = nullptr; 3338 ID.AddInteger(SCEVType); 3339 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3340 ID.AddPointer(Ops[i]); 3341 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3342 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3343 } 3344 3345 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3346 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3347 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3348 } 3349 3350 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) { 3351 Type *Ty = Op->getType(); 3352 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty)); 3353 } 3354 3355 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3356 SmallVectorImpl<const SCEV *> &Ops) { 3357 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3358 if (Ops.size() == 1) return Ops[0]; 3359 #ifndef NDEBUG 3360 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3361 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3362 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3363 "Operand types don't match!"); 3364 #endif 3365 3366 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3367 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3368 3369 // Sort by complexity, this groups all similar expression types together. 3370 GroupByComplexity(Ops, &LI, DT); 3371 3372 // Check if we have created the same expression before. 3373 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3374 return S; 3375 } 3376 3377 // If there are any constants, fold them together. 3378 unsigned Idx = 0; 3379 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3380 ++Idx; 3381 assert(Idx < Ops.size()); 3382 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3383 if (Kind == scSMaxExpr) 3384 return APIntOps::smax(LHS, RHS); 3385 else if (Kind == scSMinExpr) 3386 return APIntOps::smin(LHS, RHS); 3387 else if (Kind == scUMaxExpr) 3388 return APIntOps::umax(LHS, RHS); 3389 else if (Kind == scUMinExpr) 3390 return APIntOps::umin(LHS, RHS); 3391 llvm_unreachable("Unknown SCEV min/max opcode"); 3392 }; 3393 3394 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3395 // We found two constants, fold them together! 3396 ConstantInt *Fold = ConstantInt::get( 3397 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3398 Ops[0] = getConstant(Fold); 3399 Ops.erase(Ops.begin()+1); // Erase the folded element 3400 if (Ops.size() == 1) return Ops[0]; 3401 LHSC = cast<SCEVConstant>(Ops[0]); 3402 } 3403 3404 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3405 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3406 3407 if (IsMax ? IsMinV : IsMaxV) { 3408 // If we are left with a constant minimum(/maximum)-int, strip it off. 3409 Ops.erase(Ops.begin()); 3410 --Idx; 3411 } else if (IsMax ? IsMaxV : IsMinV) { 3412 // If we have a max(/min) with a constant maximum(/minimum)-int, 3413 // it will always be the extremum. 3414 return LHSC; 3415 } 3416 3417 if (Ops.size() == 1) return Ops[0]; 3418 } 3419 3420 // Find the first operation of the same kind 3421 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3422 ++Idx; 3423 3424 // Check to see if one of the operands is of the same kind. If so, expand its 3425 // operands onto our operand list, and recurse to simplify. 3426 if (Idx < Ops.size()) { 3427 bool DeletedAny = false; 3428 while (Ops[Idx]->getSCEVType() == Kind) { 3429 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3430 Ops.erase(Ops.begin()+Idx); 3431 Ops.append(SMME->op_begin(), SMME->op_end()); 3432 DeletedAny = true; 3433 } 3434 3435 if (DeletedAny) 3436 return getMinMaxExpr(Kind, Ops); 3437 } 3438 3439 // Okay, check to see if the same value occurs in the operand list twice. If 3440 // so, delete one. Since we sorted the list, these values are required to 3441 // be adjacent. 3442 llvm::CmpInst::Predicate GEPred = 3443 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3444 llvm::CmpInst::Predicate LEPred = 3445 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3446 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3447 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3448 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3449 if (Ops[i] == Ops[i + 1] || 3450 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3451 // X op Y op Y --> X op Y 3452 // X op Y --> X, if we know X, Y are ordered appropriately 3453 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3454 --i; 3455 --e; 3456 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3457 Ops[i + 1])) { 3458 // X op Y --> Y, if we know X, Y are ordered appropriately 3459 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3460 --i; 3461 --e; 3462 } 3463 } 3464 3465 if (Ops.size() == 1) return Ops[0]; 3466 3467 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3468 3469 // Okay, it looks like we really DO need an expr. Check to see if we 3470 // already have one, otherwise create a new one. 3471 const SCEV *ExistingSCEV; 3472 FoldingSetNodeID ID; 3473 void *IP; 3474 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3475 if (ExistingSCEV) 3476 return ExistingSCEV; 3477 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3478 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3479 SCEV *S = new (SCEVAllocator) 3480 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3481 3482 UniqueSCEVs.InsertNode(S, IP); 3483 addToLoopUseLists(S); 3484 return S; 3485 } 3486 3487 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3488 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3489 return getSMaxExpr(Ops); 3490 } 3491 3492 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3493 return getMinMaxExpr(scSMaxExpr, Ops); 3494 } 3495 3496 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3497 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3498 return getUMaxExpr(Ops); 3499 } 3500 3501 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3502 return getMinMaxExpr(scUMaxExpr, Ops); 3503 } 3504 3505 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3506 const SCEV *RHS) { 3507 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3508 return getSMinExpr(Ops); 3509 } 3510 3511 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3512 return getMinMaxExpr(scSMinExpr, Ops); 3513 } 3514 3515 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3516 const SCEV *RHS) { 3517 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3518 return getUMinExpr(Ops); 3519 } 3520 3521 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3522 return getMinMaxExpr(scUMinExpr, Ops); 3523 } 3524 3525 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3526 // We can bypass creating a target-independent 3527 // constant expression and then folding it back into a ConstantInt. 3528 // This is just a compile-time optimization. 3529 if (isa<ScalableVectorType>(AllocTy)) { 3530 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3531 Constant *One = ConstantInt::get(IntTy, 1); 3532 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3533 return getSCEV(ConstantExpr::getPtrToInt(GEP, IntTy)); 3534 } 3535 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3536 } 3537 3538 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3539 StructType *STy, 3540 unsigned FieldNo) { 3541 // We can bypass creating a target-independent 3542 // constant expression and then folding it back into a ConstantInt. 3543 // This is just a compile-time optimization. 3544 return getConstant( 3545 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3546 } 3547 3548 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3549 // Don't attempt to do anything other than create a SCEVUnknown object 3550 // here. createSCEV only calls getUnknown after checking for all other 3551 // interesting possibilities, and any other code that calls getUnknown 3552 // is doing so in order to hide a value from SCEV canonicalization. 3553 3554 FoldingSetNodeID ID; 3555 ID.AddInteger(scUnknown); 3556 ID.AddPointer(V); 3557 void *IP = nullptr; 3558 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3559 assert(cast<SCEVUnknown>(S)->getValue() == V && 3560 "Stale SCEVUnknown in uniquing map!"); 3561 return S; 3562 } 3563 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3564 FirstUnknown); 3565 FirstUnknown = cast<SCEVUnknown>(S); 3566 UniqueSCEVs.InsertNode(S, IP); 3567 return S; 3568 } 3569 3570 //===----------------------------------------------------------------------===// 3571 // Basic SCEV Analysis and PHI Idiom Recognition Code 3572 // 3573 3574 /// Test if values of the given type are analyzable within the SCEV 3575 /// framework. This primarily includes integer types, and it can optionally 3576 /// include pointer types if the ScalarEvolution class has access to 3577 /// target-specific information. 3578 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3579 // Integers and pointers are always SCEVable. 3580 return Ty->isIntOrPtrTy(); 3581 } 3582 3583 /// Return the size in bits of the specified type, for which isSCEVable must 3584 /// return true. 3585 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3586 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3587 if (Ty->isPointerTy()) 3588 return getDataLayout().getIndexTypeSizeInBits(Ty); 3589 return getDataLayout().getTypeSizeInBits(Ty); 3590 } 3591 3592 /// Return a type with the same bitwidth as the given type and which represents 3593 /// how SCEV will treat the given type, for which isSCEVable must return 3594 /// true. For pointer types, this is the pointer index sized integer type. 3595 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3596 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3597 3598 if (Ty->isIntegerTy()) 3599 return Ty; 3600 3601 // The only other support type is pointer. 3602 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3603 return getDataLayout().getIndexType(Ty); 3604 } 3605 3606 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3607 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3608 } 3609 3610 const SCEV *ScalarEvolution::getCouldNotCompute() { 3611 return CouldNotCompute.get(); 3612 } 3613 3614 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3615 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3616 auto *SU = dyn_cast<SCEVUnknown>(S); 3617 return SU && SU->getValue() == nullptr; 3618 }); 3619 3620 return !ContainsNulls; 3621 } 3622 3623 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3624 HasRecMapType::iterator I = HasRecMap.find(S); 3625 if (I != HasRecMap.end()) 3626 return I->second; 3627 3628 bool FoundAddRec = 3629 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3630 HasRecMap.insert({S, FoundAddRec}); 3631 return FoundAddRec; 3632 } 3633 3634 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3635 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3636 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3637 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3638 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3639 if (!Add) 3640 return {S, nullptr}; 3641 3642 if (Add->getNumOperands() != 2) 3643 return {S, nullptr}; 3644 3645 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3646 if (!ConstOp) 3647 return {S, nullptr}; 3648 3649 return {Add->getOperand(1), ConstOp->getValue()}; 3650 } 3651 3652 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3653 /// by the value and offset from any ValueOffsetPair in the set. 3654 SetVector<ScalarEvolution::ValueOffsetPair> * 3655 ScalarEvolution::getSCEVValues(const SCEV *S) { 3656 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3657 if (SI == ExprValueMap.end()) 3658 return nullptr; 3659 #ifndef NDEBUG 3660 if (VerifySCEVMap) { 3661 // Check there is no dangling Value in the set returned. 3662 for (const auto &VE : SI->second) 3663 assert(ValueExprMap.count(VE.first)); 3664 } 3665 #endif 3666 return &SI->second; 3667 } 3668 3669 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3670 /// cannot be used separately. eraseValueFromMap should be used to remove 3671 /// V from ValueExprMap and ExprValueMap at the same time. 3672 void ScalarEvolution::eraseValueFromMap(Value *V) { 3673 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3674 if (I != ValueExprMap.end()) { 3675 const SCEV *S = I->second; 3676 // Remove {V, 0} from the set of ExprValueMap[S] 3677 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3678 SV->remove({V, nullptr}); 3679 3680 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3681 const SCEV *Stripped; 3682 ConstantInt *Offset; 3683 std::tie(Stripped, Offset) = splitAddExpr(S); 3684 if (Offset != nullptr) { 3685 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3686 SV->remove({V, Offset}); 3687 } 3688 ValueExprMap.erase(V); 3689 } 3690 } 3691 3692 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3693 /// TODO: In reality it is better to check the poison recursively 3694 /// but this is better than nothing. 3695 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3696 if (auto *I = dyn_cast<Instruction>(V)) { 3697 if (isa<OverflowingBinaryOperator>(I)) { 3698 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3699 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3700 return true; 3701 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3702 return true; 3703 } 3704 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3705 return true; 3706 } 3707 return false; 3708 } 3709 3710 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3711 /// create a new one. 3712 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3713 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3714 3715 const SCEV *S = getExistingSCEV(V); 3716 if (S == nullptr) { 3717 S = createSCEV(V); 3718 // During PHI resolution, it is possible to create two SCEVs for the same 3719 // V, so it is needed to double check whether V->S is inserted into 3720 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3721 std::pair<ValueExprMapType::iterator, bool> Pair = 3722 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3723 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3724 ExprValueMap[S].insert({V, nullptr}); 3725 3726 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3727 // ExprValueMap. 3728 const SCEV *Stripped = S; 3729 ConstantInt *Offset = nullptr; 3730 std::tie(Stripped, Offset) = splitAddExpr(S); 3731 // If stripped is SCEVUnknown, don't bother to save 3732 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3733 // increase the complexity of the expansion code. 3734 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3735 // because it may generate add/sub instead of GEP in SCEV expansion. 3736 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3737 !isa<GetElementPtrInst>(V)) 3738 ExprValueMap[Stripped].insert({V, Offset}); 3739 } 3740 } 3741 return S; 3742 } 3743 3744 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3745 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3746 3747 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3748 if (I != ValueExprMap.end()) { 3749 const SCEV *S = I->second; 3750 if (checkValidity(S)) 3751 return S; 3752 eraseValueFromMap(V); 3753 forgetMemoizedResults(S); 3754 } 3755 return nullptr; 3756 } 3757 3758 /// Return a SCEV corresponding to -V = -1*V 3759 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3760 SCEV::NoWrapFlags Flags) { 3761 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3762 return getConstant( 3763 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3764 3765 Type *Ty = V->getType(); 3766 Ty = getEffectiveSCEVType(Ty); 3767 return getMulExpr(V, getMinusOne(Ty), Flags); 3768 } 3769 3770 /// If Expr computes ~A, return A else return nullptr 3771 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3772 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3773 if (!Add || Add->getNumOperands() != 2 || 3774 !Add->getOperand(0)->isAllOnesValue()) 3775 return nullptr; 3776 3777 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3778 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3779 !AddRHS->getOperand(0)->isAllOnesValue()) 3780 return nullptr; 3781 3782 return AddRHS->getOperand(1); 3783 } 3784 3785 /// Return a SCEV corresponding to ~V = -1-V 3786 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3787 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3788 return getConstant( 3789 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3790 3791 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3792 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3793 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3794 SmallVector<const SCEV *, 2> MatchedOperands; 3795 for (const SCEV *Operand : MME->operands()) { 3796 const SCEV *Matched = MatchNotExpr(Operand); 3797 if (!Matched) 3798 return (const SCEV *)nullptr; 3799 MatchedOperands.push_back(Matched); 3800 } 3801 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3802 MatchedOperands); 3803 }; 3804 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3805 return Replaced; 3806 } 3807 3808 Type *Ty = V->getType(); 3809 Ty = getEffectiveSCEVType(Ty); 3810 return getMinusSCEV(getMinusOne(Ty), V); 3811 } 3812 3813 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3814 SCEV::NoWrapFlags Flags, 3815 unsigned Depth) { 3816 // Fast path: X - X --> 0. 3817 if (LHS == RHS) 3818 return getZero(LHS->getType()); 3819 3820 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3821 // makes it so that we cannot make much use of NUW. 3822 auto AddFlags = SCEV::FlagAnyWrap; 3823 const bool RHSIsNotMinSigned = 3824 !getSignedRangeMin(RHS).isMinSignedValue(); 3825 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3826 // Let M be the minimum representable signed value. Then (-1)*RHS 3827 // signed-wraps if and only if RHS is M. That can happen even for 3828 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3829 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3830 // (-1)*RHS, we need to prove that RHS != M. 3831 // 3832 // If LHS is non-negative and we know that LHS - RHS does not 3833 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3834 // either by proving that RHS > M or that LHS >= 0. 3835 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3836 AddFlags = SCEV::FlagNSW; 3837 } 3838 } 3839 3840 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3841 // RHS is NSW and LHS >= 0. 3842 // 3843 // The difficulty here is that the NSW flag may have been proven 3844 // relative to a loop that is to be found in a recurrence in LHS and 3845 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3846 // larger scope than intended. 3847 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3848 3849 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3850 } 3851 3852 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 3853 unsigned Depth) { 3854 Type *SrcTy = V->getType(); 3855 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3856 "Cannot truncate or zero extend with non-integer arguments!"); 3857 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3858 return V; // No conversion 3859 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3860 return getTruncateExpr(V, Ty, Depth); 3861 return getZeroExtendExpr(V, Ty, Depth); 3862 } 3863 3864 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 3865 unsigned Depth) { 3866 Type *SrcTy = V->getType(); 3867 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3868 "Cannot truncate or zero extend with non-integer arguments!"); 3869 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3870 return V; // No conversion 3871 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3872 return getTruncateExpr(V, Ty, Depth); 3873 return getSignExtendExpr(V, Ty, Depth); 3874 } 3875 3876 const SCEV * 3877 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3878 Type *SrcTy = V->getType(); 3879 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3880 "Cannot noop or zero extend with non-integer arguments!"); 3881 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3882 "getNoopOrZeroExtend cannot truncate!"); 3883 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3884 return V; // No conversion 3885 return getZeroExtendExpr(V, Ty); 3886 } 3887 3888 const SCEV * 3889 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3890 Type *SrcTy = V->getType(); 3891 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3892 "Cannot noop or sign extend with non-integer arguments!"); 3893 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3894 "getNoopOrSignExtend cannot truncate!"); 3895 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3896 return V; // No conversion 3897 return getSignExtendExpr(V, Ty); 3898 } 3899 3900 const SCEV * 3901 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3902 Type *SrcTy = V->getType(); 3903 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3904 "Cannot noop or any extend with non-integer arguments!"); 3905 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3906 "getNoopOrAnyExtend cannot truncate!"); 3907 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3908 return V; // No conversion 3909 return getAnyExtendExpr(V, Ty); 3910 } 3911 3912 const SCEV * 3913 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3914 Type *SrcTy = V->getType(); 3915 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3916 "Cannot truncate or noop with non-integer arguments!"); 3917 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3918 "getTruncateOrNoop cannot extend!"); 3919 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3920 return V; // No conversion 3921 return getTruncateExpr(V, Ty); 3922 } 3923 3924 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3925 const SCEV *RHS) { 3926 const SCEV *PromotedLHS = LHS; 3927 const SCEV *PromotedRHS = RHS; 3928 3929 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3930 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3931 else 3932 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3933 3934 return getUMaxExpr(PromotedLHS, PromotedRHS); 3935 } 3936 3937 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3938 const SCEV *RHS) { 3939 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3940 return getUMinFromMismatchedTypes(Ops); 3941 } 3942 3943 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 3944 SmallVectorImpl<const SCEV *> &Ops) { 3945 assert(!Ops.empty() && "At least one operand must be!"); 3946 // Trivial case. 3947 if (Ops.size() == 1) 3948 return Ops[0]; 3949 3950 // Find the max type first. 3951 Type *MaxType = nullptr; 3952 for (auto *S : Ops) 3953 if (MaxType) 3954 MaxType = getWiderType(MaxType, S->getType()); 3955 else 3956 MaxType = S->getType(); 3957 assert(MaxType && "Failed to find maximum type!"); 3958 3959 // Extend all ops to max type. 3960 SmallVector<const SCEV *, 2> PromotedOps; 3961 for (auto *S : Ops) 3962 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 3963 3964 // Generate umin. 3965 return getUMinExpr(PromotedOps); 3966 } 3967 3968 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3969 // A pointer operand may evaluate to a nonpointer expression, such as null. 3970 if (!V->getType()->isPointerTy()) 3971 return V; 3972 3973 while (true) { 3974 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 3975 V = Cast->getOperand(); 3976 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3977 const SCEV *PtrOp = nullptr; 3978 for (const SCEV *NAryOp : NAry->operands()) { 3979 if (NAryOp->getType()->isPointerTy()) { 3980 // Cannot find the base of an expression with multiple pointer ops. 3981 if (PtrOp) 3982 return V; 3983 PtrOp = NAryOp; 3984 } 3985 } 3986 if (!PtrOp) // All operands were non-pointer. 3987 return V; 3988 V = PtrOp; 3989 } else // Not something we can look further into. 3990 return V; 3991 } 3992 } 3993 3994 /// Push users of the given Instruction onto the given Worklist. 3995 static void 3996 PushDefUseChildren(Instruction *I, 3997 SmallVectorImpl<Instruction *> &Worklist) { 3998 // Push the def-use children onto the Worklist stack. 3999 for (User *U : I->users()) 4000 Worklist.push_back(cast<Instruction>(U)); 4001 } 4002 4003 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4004 SmallVector<Instruction *, 16> Worklist; 4005 PushDefUseChildren(PN, Worklist); 4006 4007 SmallPtrSet<Instruction *, 8> Visited; 4008 Visited.insert(PN); 4009 while (!Worklist.empty()) { 4010 Instruction *I = Worklist.pop_back_val(); 4011 if (!Visited.insert(I).second) 4012 continue; 4013 4014 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4015 if (It != ValueExprMap.end()) { 4016 const SCEV *Old = It->second; 4017 4018 // Short-circuit the def-use traversal if the symbolic name 4019 // ceases to appear in expressions. 4020 if (Old != SymName && !hasOperand(Old, SymName)) 4021 continue; 4022 4023 // SCEVUnknown for a PHI either means that it has an unrecognized 4024 // structure, it's a PHI that's in the progress of being computed 4025 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4026 // additional loop trip count information isn't going to change anything. 4027 // In the second case, createNodeForPHI will perform the necessary 4028 // updates on its own when it gets to that point. In the third, we do 4029 // want to forget the SCEVUnknown. 4030 if (!isa<PHINode>(I) || 4031 !isa<SCEVUnknown>(Old) || 4032 (I != PN && Old == SymName)) { 4033 eraseValueFromMap(It->first); 4034 forgetMemoizedResults(Old); 4035 } 4036 } 4037 4038 PushDefUseChildren(I, Worklist); 4039 } 4040 } 4041 4042 namespace { 4043 4044 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4045 /// expression in case its Loop is L. If it is not L then 4046 /// if IgnoreOtherLoops is true then use AddRec itself 4047 /// otherwise rewrite cannot be done. 4048 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4049 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4050 public: 4051 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4052 bool IgnoreOtherLoops = true) { 4053 SCEVInitRewriter Rewriter(L, SE); 4054 const SCEV *Result = Rewriter.visit(S); 4055 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4056 return SE.getCouldNotCompute(); 4057 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4058 ? SE.getCouldNotCompute() 4059 : Result; 4060 } 4061 4062 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4063 if (!SE.isLoopInvariant(Expr, L)) 4064 SeenLoopVariantSCEVUnknown = true; 4065 return Expr; 4066 } 4067 4068 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4069 // Only re-write AddRecExprs for this loop. 4070 if (Expr->getLoop() == L) 4071 return Expr->getStart(); 4072 SeenOtherLoops = true; 4073 return Expr; 4074 } 4075 4076 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4077 4078 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4079 4080 private: 4081 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4082 : SCEVRewriteVisitor(SE), L(L) {} 4083 4084 const Loop *L; 4085 bool SeenLoopVariantSCEVUnknown = false; 4086 bool SeenOtherLoops = false; 4087 }; 4088 4089 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4090 /// increment expression in case its Loop is L. If it is not L then 4091 /// use AddRec itself. 4092 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4093 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4094 public: 4095 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4096 SCEVPostIncRewriter Rewriter(L, SE); 4097 const SCEV *Result = Rewriter.visit(S); 4098 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4099 ? SE.getCouldNotCompute() 4100 : Result; 4101 } 4102 4103 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4104 if (!SE.isLoopInvariant(Expr, L)) 4105 SeenLoopVariantSCEVUnknown = true; 4106 return Expr; 4107 } 4108 4109 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4110 // Only re-write AddRecExprs for this loop. 4111 if (Expr->getLoop() == L) 4112 return Expr->getPostIncExpr(SE); 4113 SeenOtherLoops = true; 4114 return Expr; 4115 } 4116 4117 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4118 4119 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4120 4121 private: 4122 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4123 : SCEVRewriteVisitor(SE), L(L) {} 4124 4125 const Loop *L; 4126 bool SeenLoopVariantSCEVUnknown = false; 4127 bool SeenOtherLoops = false; 4128 }; 4129 4130 /// This class evaluates the compare condition by matching it against the 4131 /// condition of loop latch. If there is a match we assume a true value 4132 /// for the condition while building SCEV nodes. 4133 class SCEVBackedgeConditionFolder 4134 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4135 public: 4136 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4137 ScalarEvolution &SE) { 4138 bool IsPosBECond = false; 4139 Value *BECond = nullptr; 4140 if (BasicBlock *Latch = L->getLoopLatch()) { 4141 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4142 if (BI && BI->isConditional()) { 4143 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4144 "Both outgoing branches should not target same header!"); 4145 BECond = BI->getCondition(); 4146 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4147 } else { 4148 return S; 4149 } 4150 } 4151 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4152 return Rewriter.visit(S); 4153 } 4154 4155 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4156 const SCEV *Result = Expr; 4157 bool InvariantF = SE.isLoopInvariant(Expr, L); 4158 4159 if (!InvariantF) { 4160 Instruction *I = cast<Instruction>(Expr->getValue()); 4161 switch (I->getOpcode()) { 4162 case Instruction::Select: { 4163 SelectInst *SI = cast<SelectInst>(I); 4164 Optional<const SCEV *> Res = 4165 compareWithBackedgeCondition(SI->getCondition()); 4166 if (Res.hasValue()) { 4167 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4168 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4169 } 4170 break; 4171 } 4172 default: { 4173 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4174 if (Res.hasValue()) 4175 Result = Res.getValue(); 4176 break; 4177 } 4178 } 4179 } 4180 return Result; 4181 } 4182 4183 private: 4184 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4185 bool IsPosBECond, ScalarEvolution &SE) 4186 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4187 IsPositiveBECond(IsPosBECond) {} 4188 4189 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4190 4191 const Loop *L; 4192 /// Loop back condition. 4193 Value *BackedgeCond = nullptr; 4194 /// Set to true if loop back is on positive branch condition. 4195 bool IsPositiveBECond; 4196 }; 4197 4198 Optional<const SCEV *> 4199 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4200 4201 // If value matches the backedge condition for loop latch, 4202 // then return a constant evolution node based on loopback 4203 // branch taken. 4204 if (BackedgeCond == IC) 4205 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4206 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4207 return None; 4208 } 4209 4210 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4211 public: 4212 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4213 ScalarEvolution &SE) { 4214 SCEVShiftRewriter Rewriter(L, SE); 4215 const SCEV *Result = Rewriter.visit(S); 4216 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4217 } 4218 4219 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4220 // Only allow AddRecExprs for this loop. 4221 if (!SE.isLoopInvariant(Expr, L)) 4222 Valid = false; 4223 return Expr; 4224 } 4225 4226 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4227 if (Expr->getLoop() == L && Expr->isAffine()) 4228 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4229 Valid = false; 4230 return Expr; 4231 } 4232 4233 bool isValid() { return Valid; } 4234 4235 private: 4236 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4237 : SCEVRewriteVisitor(SE), L(L) {} 4238 4239 const Loop *L; 4240 bool Valid = true; 4241 }; 4242 4243 } // end anonymous namespace 4244 4245 SCEV::NoWrapFlags 4246 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4247 if (!AR->isAffine()) 4248 return SCEV::FlagAnyWrap; 4249 4250 using OBO = OverflowingBinaryOperator; 4251 4252 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4253 4254 if (!AR->hasNoSignedWrap()) { 4255 ConstantRange AddRecRange = getSignedRange(AR); 4256 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4257 4258 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4259 Instruction::Add, IncRange, OBO::NoSignedWrap); 4260 if (NSWRegion.contains(AddRecRange)) 4261 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4262 } 4263 4264 if (!AR->hasNoUnsignedWrap()) { 4265 ConstantRange AddRecRange = getUnsignedRange(AR); 4266 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4267 4268 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4269 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4270 if (NUWRegion.contains(AddRecRange)) 4271 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4272 } 4273 4274 return Result; 4275 } 4276 4277 namespace { 4278 4279 /// Represents an abstract binary operation. This may exist as a 4280 /// normal instruction or constant expression, or may have been 4281 /// derived from an expression tree. 4282 struct BinaryOp { 4283 unsigned Opcode; 4284 Value *LHS; 4285 Value *RHS; 4286 bool IsNSW = false; 4287 bool IsNUW = false; 4288 bool IsExact = false; 4289 4290 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4291 /// constant expression. 4292 Operator *Op = nullptr; 4293 4294 explicit BinaryOp(Operator *Op) 4295 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4296 Op(Op) { 4297 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4298 IsNSW = OBO->hasNoSignedWrap(); 4299 IsNUW = OBO->hasNoUnsignedWrap(); 4300 } 4301 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op)) 4302 IsExact = PEO->isExact(); 4303 } 4304 4305 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4306 bool IsNUW = false, bool IsExact = false) 4307 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4308 IsExact(IsExact) {} 4309 }; 4310 4311 } // end anonymous namespace 4312 4313 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4314 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4315 auto *Op = dyn_cast<Operator>(V); 4316 if (!Op) 4317 return None; 4318 4319 // Implementation detail: all the cleverness here should happen without 4320 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4321 // SCEV expressions when possible, and we should not break that. 4322 4323 switch (Op->getOpcode()) { 4324 case Instruction::Add: 4325 case Instruction::Sub: 4326 case Instruction::Mul: 4327 case Instruction::UDiv: 4328 case Instruction::URem: 4329 case Instruction::And: 4330 case Instruction::Or: 4331 case Instruction::AShr: 4332 case Instruction::Shl: 4333 return BinaryOp(Op); 4334 4335 case Instruction::Xor: 4336 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4337 // If the RHS of the xor is a signmask, then this is just an add. 4338 // Instcombine turns add of signmask into xor as a strength reduction step. 4339 if (RHSC->getValue().isSignMask()) 4340 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4341 return BinaryOp(Op); 4342 4343 case Instruction::LShr: 4344 // Turn logical shift right of a constant into a unsigned divide. 4345 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4346 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4347 4348 // If the shift count is not less than the bitwidth, the result of 4349 // the shift is undefined. Don't try to analyze it, because the 4350 // resolution chosen here may differ from the resolution chosen in 4351 // other parts of the compiler. 4352 if (SA->getValue().ult(BitWidth)) { 4353 Constant *X = 4354 ConstantInt::get(SA->getContext(), 4355 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4356 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4357 } 4358 } 4359 return BinaryOp(Op); 4360 4361 case Instruction::ExtractValue: { 4362 auto *EVI = cast<ExtractValueInst>(Op); 4363 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4364 break; 4365 4366 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4367 if (!WO) 4368 break; 4369 4370 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4371 bool Signed = WO->isSigned(); 4372 // TODO: Should add nuw/nsw flags for mul as well. 4373 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4374 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4375 4376 // Now that we know that all uses of the arithmetic-result component of 4377 // CI are guarded by the overflow check, we can go ahead and pretend 4378 // that the arithmetic is non-overflowing. 4379 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4380 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4381 } 4382 4383 default: 4384 break; 4385 } 4386 4387 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4388 // semantics as a Sub, return a binary sub expression. 4389 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4390 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4391 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4392 4393 return None; 4394 } 4395 4396 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4397 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4398 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4399 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4400 /// follows one of the following patterns: 4401 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4402 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4403 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4404 /// we return the type of the truncation operation, and indicate whether the 4405 /// truncated type should be treated as signed/unsigned by setting 4406 /// \p Signed to true/false, respectively. 4407 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4408 bool &Signed, ScalarEvolution &SE) { 4409 // The case where Op == SymbolicPHI (that is, with no type conversions on 4410 // the way) is handled by the regular add recurrence creating logic and 4411 // would have already been triggered in createAddRecForPHI. Reaching it here 4412 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4413 // because one of the other operands of the SCEVAddExpr updating this PHI is 4414 // not invariant). 4415 // 4416 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4417 // this case predicates that allow us to prove that Op == SymbolicPHI will 4418 // be added. 4419 if (Op == SymbolicPHI) 4420 return nullptr; 4421 4422 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4423 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4424 if (SourceBits != NewBits) 4425 return nullptr; 4426 4427 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4428 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4429 if (!SExt && !ZExt) 4430 return nullptr; 4431 const SCEVTruncateExpr *Trunc = 4432 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4433 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4434 if (!Trunc) 4435 return nullptr; 4436 const SCEV *X = Trunc->getOperand(); 4437 if (X != SymbolicPHI) 4438 return nullptr; 4439 Signed = SExt != nullptr; 4440 return Trunc->getType(); 4441 } 4442 4443 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4444 if (!PN->getType()->isIntegerTy()) 4445 return nullptr; 4446 const Loop *L = LI.getLoopFor(PN->getParent()); 4447 if (!L || L->getHeader() != PN->getParent()) 4448 return nullptr; 4449 return L; 4450 } 4451 4452 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4453 // computation that updates the phi follows the following pattern: 4454 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4455 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4456 // If so, try to see if it can be rewritten as an AddRecExpr under some 4457 // Predicates. If successful, return them as a pair. Also cache the results 4458 // of the analysis. 4459 // 4460 // Example usage scenario: 4461 // Say the Rewriter is called for the following SCEV: 4462 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4463 // where: 4464 // %X = phi i64 (%Start, %BEValue) 4465 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4466 // and call this function with %SymbolicPHI = %X. 4467 // 4468 // The analysis will find that the value coming around the backedge has 4469 // the following SCEV: 4470 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4471 // Upon concluding that this matches the desired pattern, the function 4472 // will return the pair {NewAddRec, SmallPredsVec} where: 4473 // NewAddRec = {%Start,+,%Step} 4474 // SmallPredsVec = {P1, P2, P3} as follows: 4475 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4476 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4477 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4478 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4479 // under the predicates {P1,P2,P3}. 4480 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4481 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4482 // 4483 // TODO's: 4484 // 4485 // 1) Extend the Induction descriptor to also support inductions that involve 4486 // casts: When needed (namely, when we are called in the context of the 4487 // vectorizer induction analysis), a Set of cast instructions will be 4488 // populated by this method, and provided back to isInductionPHI. This is 4489 // needed to allow the vectorizer to properly record them to be ignored by 4490 // the cost model and to avoid vectorizing them (otherwise these casts, 4491 // which are redundant under the runtime overflow checks, will be 4492 // vectorized, which can be costly). 4493 // 4494 // 2) Support additional induction/PHISCEV patterns: We also want to support 4495 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4496 // after the induction update operation (the induction increment): 4497 // 4498 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4499 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4500 // 4501 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4502 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4503 // 4504 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4505 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4506 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4507 SmallVector<const SCEVPredicate *, 3> Predicates; 4508 4509 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4510 // return an AddRec expression under some predicate. 4511 4512 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4513 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4514 assert(L && "Expecting an integer loop header phi"); 4515 4516 // The loop may have multiple entrances or multiple exits; we can analyze 4517 // this phi as an addrec if it has a unique entry value and a unique 4518 // backedge value. 4519 Value *BEValueV = nullptr, *StartValueV = nullptr; 4520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4521 Value *V = PN->getIncomingValue(i); 4522 if (L->contains(PN->getIncomingBlock(i))) { 4523 if (!BEValueV) { 4524 BEValueV = V; 4525 } else if (BEValueV != V) { 4526 BEValueV = nullptr; 4527 break; 4528 } 4529 } else if (!StartValueV) { 4530 StartValueV = V; 4531 } else if (StartValueV != V) { 4532 StartValueV = nullptr; 4533 break; 4534 } 4535 } 4536 if (!BEValueV || !StartValueV) 4537 return None; 4538 4539 const SCEV *BEValue = getSCEV(BEValueV); 4540 4541 // If the value coming around the backedge is an add with the symbolic 4542 // value we just inserted, possibly with casts that we can ignore under 4543 // an appropriate runtime guard, then we found a simple induction variable! 4544 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4545 if (!Add) 4546 return None; 4547 4548 // If there is a single occurrence of the symbolic value, possibly 4549 // casted, replace it with a recurrence. 4550 unsigned FoundIndex = Add->getNumOperands(); 4551 Type *TruncTy = nullptr; 4552 bool Signed; 4553 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4554 if ((TruncTy = 4555 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4556 if (FoundIndex == e) { 4557 FoundIndex = i; 4558 break; 4559 } 4560 4561 if (FoundIndex == Add->getNumOperands()) 4562 return None; 4563 4564 // Create an add with everything but the specified operand. 4565 SmallVector<const SCEV *, 8> Ops; 4566 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4567 if (i != FoundIndex) 4568 Ops.push_back(Add->getOperand(i)); 4569 const SCEV *Accum = getAddExpr(Ops); 4570 4571 // The runtime checks will not be valid if the step amount is 4572 // varying inside the loop. 4573 if (!isLoopInvariant(Accum, L)) 4574 return None; 4575 4576 // *** Part2: Create the predicates 4577 4578 // Analysis was successful: we have a phi-with-cast pattern for which we 4579 // can return an AddRec expression under the following predicates: 4580 // 4581 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4582 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4583 // P2: An Equal predicate that guarantees that 4584 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4585 // P3: An Equal predicate that guarantees that 4586 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4587 // 4588 // As we next prove, the above predicates guarantee that: 4589 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4590 // 4591 // 4592 // More formally, we want to prove that: 4593 // Expr(i+1) = Start + (i+1) * Accum 4594 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4595 // 4596 // Given that: 4597 // 1) Expr(0) = Start 4598 // 2) Expr(1) = Start + Accum 4599 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4600 // 3) Induction hypothesis (step i): 4601 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4602 // 4603 // Proof: 4604 // Expr(i+1) = 4605 // = Start + (i+1)*Accum 4606 // = (Start + i*Accum) + Accum 4607 // = Expr(i) + Accum 4608 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4609 // :: from step i 4610 // 4611 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4612 // 4613 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4614 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4615 // + Accum :: from P3 4616 // 4617 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4618 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4619 // 4620 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4621 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4622 // 4623 // By induction, the same applies to all iterations 1<=i<n: 4624 // 4625 4626 // Create a truncated addrec for which we will add a no overflow check (P1). 4627 const SCEV *StartVal = getSCEV(StartValueV); 4628 const SCEV *PHISCEV = 4629 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4630 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4631 4632 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4633 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4634 // will be constant. 4635 // 4636 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4637 // add P1. 4638 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4639 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4640 Signed ? SCEVWrapPredicate::IncrementNSSW 4641 : SCEVWrapPredicate::IncrementNUSW; 4642 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4643 Predicates.push_back(AddRecPred); 4644 } 4645 4646 // Create the Equal Predicates P2,P3: 4647 4648 // It is possible that the predicates P2 and/or P3 are computable at 4649 // compile time due to StartVal and/or Accum being constants. 4650 // If either one is, then we can check that now and escape if either P2 4651 // or P3 is false. 4652 4653 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4654 // for each of StartVal and Accum 4655 auto getExtendedExpr = [&](const SCEV *Expr, 4656 bool CreateSignExtend) -> const SCEV * { 4657 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4658 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4659 const SCEV *ExtendedExpr = 4660 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4661 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4662 return ExtendedExpr; 4663 }; 4664 4665 // Given: 4666 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4667 // = getExtendedExpr(Expr) 4668 // Determine whether the predicate P: Expr == ExtendedExpr 4669 // is known to be false at compile time 4670 auto PredIsKnownFalse = [&](const SCEV *Expr, 4671 const SCEV *ExtendedExpr) -> bool { 4672 return Expr != ExtendedExpr && 4673 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4674 }; 4675 4676 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4677 if (PredIsKnownFalse(StartVal, StartExtended)) { 4678 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4679 return None; 4680 } 4681 4682 // The Step is always Signed (because the overflow checks are either 4683 // NSSW or NUSW) 4684 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4685 if (PredIsKnownFalse(Accum, AccumExtended)) { 4686 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4687 return None; 4688 } 4689 4690 auto AppendPredicate = [&](const SCEV *Expr, 4691 const SCEV *ExtendedExpr) -> void { 4692 if (Expr != ExtendedExpr && 4693 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4694 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4695 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4696 Predicates.push_back(Pred); 4697 } 4698 }; 4699 4700 AppendPredicate(StartVal, StartExtended); 4701 AppendPredicate(Accum, AccumExtended); 4702 4703 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4704 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4705 // into NewAR if it will also add the runtime overflow checks specified in 4706 // Predicates. 4707 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4708 4709 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4710 std::make_pair(NewAR, Predicates); 4711 // Remember the result of the analysis for this SCEV at this locayyytion. 4712 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4713 return PredRewrite; 4714 } 4715 4716 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4717 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4718 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4719 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4720 if (!L) 4721 return None; 4722 4723 // Check to see if we already analyzed this PHI. 4724 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4725 if (I != PredicatedSCEVRewrites.end()) { 4726 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4727 I->second; 4728 // Analysis was done before and failed to create an AddRec: 4729 if (Rewrite.first == SymbolicPHI) 4730 return None; 4731 // Analysis was done before and succeeded to create an AddRec under 4732 // a predicate: 4733 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4734 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4735 return Rewrite; 4736 } 4737 4738 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4739 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4740 4741 // Record in the cache that the analysis failed 4742 if (!Rewrite) { 4743 SmallVector<const SCEVPredicate *, 3> Predicates; 4744 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4745 return None; 4746 } 4747 4748 return Rewrite; 4749 } 4750 4751 // FIXME: This utility is currently required because the Rewriter currently 4752 // does not rewrite this expression: 4753 // {0, +, (sext ix (trunc iy to ix) to iy)} 4754 // into {0, +, %step}, 4755 // even when the following Equal predicate exists: 4756 // "%step == (sext ix (trunc iy to ix) to iy)". 4757 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4758 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4759 if (AR1 == AR2) 4760 return true; 4761 4762 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4763 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4764 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4765 return false; 4766 return true; 4767 }; 4768 4769 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4770 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4771 return false; 4772 return true; 4773 } 4774 4775 /// A helper function for createAddRecFromPHI to handle simple cases. 4776 /// 4777 /// This function tries to find an AddRec expression for the simplest (yet most 4778 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4779 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4780 /// technique for finding the AddRec expression. 4781 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4782 Value *BEValueV, 4783 Value *StartValueV) { 4784 const Loop *L = LI.getLoopFor(PN->getParent()); 4785 assert(L && L->getHeader() == PN->getParent()); 4786 assert(BEValueV && StartValueV); 4787 4788 auto BO = MatchBinaryOp(BEValueV, DT); 4789 if (!BO) 4790 return nullptr; 4791 4792 if (BO->Opcode != Instruction::Add) 4793 return nullptr; 4794 4795 const SCEV *Accum = nullptr; 4796 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4797 Accum = getSCEV(BO->RHS); 4798 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4799 Accum = getSCEV(BO->LHS); 4800 4801 if (!Accum) 4802 return nullptr; 4803 4804 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4805 if (BO->IsNUW) 4806 Flags = setFlags(Flags, SCEV::FlagNUW); 4807 if (BO->IsNSW) 4808 Flags = setFlags(Flags, SCEV::FlagNSW); 4809 4810 const SCEV *StartVal = getSCEV(StartValueV); 4811 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4812 4813 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4814 4815 // We can add Flags to the post-inc expression only if we 4816 // know that it is *undefined behavior* for BEValueV to 4817 // overflow. 4818 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4819 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4820 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4821 4822 return PHISCEV; 4823 } 4824 4825 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4826 const Loop *L = LI.getLoopFor(PN->getParent()); 4827 if (!L || L->getHeader() != PN->getParent()) 4828 return nullptr; 4829 4830 // The loop may have multiple entrances or multiple exits; we can analyze 4831 // this phi as an addrec if it has a unique entry value and a unique 4832 // backedge value. 4833 Value *BEValueV = nullptr, *StartValueV = nullptr; 4834 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4835 Value *V = PN->getIncomingValue(i); 4836 if (L->contains(PN->getIncomingBlock(i))) { 4837 if (!BEValueV) { 4838 BEValueV = V; 4839 } else if (BEValueV != V) { 4840 BEValueV = nullptr; 4841 break; 4842 } 4843 } else if (!StartValueV) { 4844 StartValueV = V; 4845 } else if (StartValueV != V) { 4846 StartValueV = nullptr; 4847 break; 4848 } 4849 } 4850 if (!BEValueV || !StartValueV) 4851 return nullptr; 4852 4853 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4854 "PHI node already processed?"); 4855 4856 // First, try to find AddRec expression without creating a fictituos symbolic 4857 // value for PN. 4858 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4859 return S; 4860 4861 // Handle PHI node value symbolically. 4862 const SCEV *SymbolicName = getUnknown(PN); 4863 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4864 4865 // Using this symbolic name for the PHI, analyze the value coming around 4866 // the back-edge. 4867 const SCEV *BEValue = getSCEV(BEValueV); 4868 4869 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4870 // has a special value for the first iteration of the loop. 4871 4872 // If the value coming around the backedge is an add with the symbolic 4873 // value we just inserted, then we found a simple induction variable! 4874 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4875 // If there is a single occurrence of the symbolic value, replace it 4876 // with a recurrence. 4877 unsigned FoundIndex = Add->getNumOperands(); 4878 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4879 if (Add->getOperand(i) == SymbolicName) 4880 if (FoundIndex == e) { 4881 FoundIndex = i; 4882 break; 4883 } 4884 4885 if (FoundIndex != Add->getNumOperands()) { 4886 // Create an add with everything but the specified operand. 4887 SmallVector<const SCEV *, 8> Ops; 4888 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4889 if (i != FoundIndex) 4890 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4891 L, *this)); 4892 const SCEV *Accum = getAddExpr(Ops); 4893 4894 // This is not a valid addrec if the step amount is varying each 4895 // loop iteration, but is not itself an addrec in this loop. 4896 if (isLoopInvariant(Accum, L) || 4897 (isa<SCEVAddRecExpr>(Accum) && 4898 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4899 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4900 4901 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4902 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4903 if (BO->IsNUW) 4904 Flags = setFlags(Flags, SCEV::FlagNUW); 4905 if (BO->IsNSW) 4906 Flags = setFlags(Flags, SCEV::FlagNSW); 4907 } 4908 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4909 // If the increment is an inbounds GEP, then we know the address 4910 // space cannot be wrapped around. We cannot make any guarantee 4911 // about signed or unsigned overflow because pointers are 4912 // unsigned but we may have a negative index from the base 4913 // pointer. We can guarantee that no unsigned wrap occurs if the 4914 // indices form a positive value. 4915 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4916 Flags = setFlags(Flags, SCEV::FlagNW); 4917 4918 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4919 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4920 Flags = setFlags(Flags, SCEV::FlagNUW); 4921 } 4922 4923 // We cannot transfer nuw and nsw flags from subtraction 4924 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4925 // for instance. 4926 } 4927 4928 const SCEV *StartVal = getSCEV(StartValueV); 4929 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4930 4931 // Okay, for the entire analysis of this edge we assumed the PHI 4932 // to be symbolic. We now need to go back and purge all of the 4933 // entries for the scalars that use the symbolic expression. 4934 forgetSymbolicName(PN, SymbolicName); 4935 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4936 4937 // We can add Flags to the post-inc expression only if we 4938 // know that it is *undefined behavior* for BEValueV to 4939 // overflow. 4940 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4941 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4942 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4943 4944 return PHISCEV; 4945 } 4946 } 4947 } else { 4948 // Otherwise, this could be a loop like this: 4949 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4950 // In this case, j = {1,+,1} and BEValue is j. 4951 // Because the other in-value of i (0) fits the evolution of BEValue 4952 // i really is an addrec evolution. 4953 // 4954 // We can generalize this saying that i is the shifted value of BEValue 4955 // by one iteration: 4956 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4957 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4958 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 4959 if (Shifted != getCouldNotCompute() && 4960 Start != getCouldNotCompute()) { 4961 const SCEV *StartVal = getSCEV(StartValueV); 4962 if (Start == StartVal) { 4963 // Okay, for the entire analysis of this edge we assumed the PHI 4964 // to be symbolic. We now need to go back and purge all of the 4965 // entries for the scalars that use the symbolic expression. 4966 forgetSymbolicName(PN, SymbolicName); 4967 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4968 return Shifted; 4969 } 4970 } 4971 } 4972 4973 // Remove the temporary PHI node SCEV that has been inserted while intending 4974 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4975 // as it will prevent later (possibly simpler) SCEV expressions to be added 4976 // to the ValueExprMap. 4977 eraseValueFromMap(PN); 4978 4979 return nullptr; 4980 } 4981 4982 // Checks if the SCEV S is available at BB. S is considered available at BB 4983 // if S can be materialized at BB without introducing a fault. 4984 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4985 BasicBlock *BB) { 4986 struct CheckAvailable { 4987 bool TraversalDone = false; 4988 bool Available = true; 4989 4990 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4991 BasicBlock *BB = nullptr; 4992 DominatorTree &DT; 4993 4994 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4995 : L(L), BB(BB), DT(DT) {} 4996 4997 bool setUnavailable() { 4998 TraversalDone = true; 4999 Available = false; 5000 return false; 5001 } 5002 5003 bool follow(const SCEV *S) { 5004 switch (S->getSCEVType()) { 5005 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5006 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5007 case scUMinExpr: 5008 case scSMinExpr: 5009 // These expressions are available if their operand(s) is/are. 5010 return true; 5011 5012 case scAddRecExpr: { 5013 // We allow add recurrences that are on the loop BB is in, or some 5014 // outer loop. This guarantees availability because the value of the 5015 // add recurrence at BB is simply the "current" value of the induction 5016 // variable. We can relax this in the future; for instance an add 5017 // recurrence on a sibling dominating loop is also available at BB. 5018 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5019 if (L && (ARLoop == L || ARLoop->contains(L))) 5020 return true; 5021 5022 return setUnavailable(); 5023 } 5024 5025 case scUnknown: { 5026 // For SCEVUnknown, we check for simple dominance. 5027 const auto *SU = cast<SCEVUnknown>(S); 5028 Value *V = SU->getValue(); 5029 5030 if (isa<Argument>(V)) 5031 return false; 5032 5033 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5034 return false; 5035 5036 return setUnavailable(); 5037 } 5038 5039 case scUDivExpr: 5040 case scCouldNotCompute: 5041 // We do not try to smart about these at all. 5042 return setUnavailable(); 5043 } 5044 llvm_unreachable("Unknown SCEV kind!"); 5045 } 5046 5047 bool isDone() { return TraversalDone; } 5048 }; 5049 5050 CheckAvailable CA(L, BB, DT); 5051 SCEVTraversal<CheckAvailable> ST(CA); 5052 5053 ST.visitAll(S); 5054 return CA.Available; 5055 } 5056 5057 // Try to match a control flow sequence that branches out at BI and merges back 5058 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5059 // match. 5060 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5061 Value *&C, Value *&LHS, Value *&RHS) { 5062 C = BI->getCondition(); 5063 5064 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5065 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5066 5067 if (!LeftEdge.isSingleEdge()) 5068 return false; 5069 5070 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5071 5072 Use &LeftUse = Merge->getOperandUse(0); 5073 Use &RightUse = Merge->getOperandUse(1); 5074 5075 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5076 LHS = LeftUse; 5077 RHS = RightUse; 5078 return true; 5079 } 5080 5081 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5082 LHS = RightUse; 5083 RHS = LeftUse; 5084 return true; 5085 } 5086 5087 return false; 5088 } 5089 5090 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5091 auto IsReachable = 5092 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5093 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5094 const Loop *L = LI.getLoopFor(PN->getParent()); 5095 5096 // We don't want to break LCSSA, even in a SCEV expression tree. 5097 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5098 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5099 return nullptr; 5100 5101 // Try to match 5102 // 5103 // br %cond, label %left, label %right 5104 // left: 5105 // br label %merge 5106 // right: 5107 // br label %merge 5108 // merge: 5109 // V = phi [ %x, %left ], [ %y, %right ] 5110 // 5111 // as "select %cond, %x, %y" 5112 5113 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5114 assert(IDom && "At least the entry block should dominate PN"); 5115 5116 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5117 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5118 5119 if (BI && BI->isConditional() && 5120 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5121 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5122 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5123 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5124 } 5125 5126 return nullptr; 5127 } 5128 5129 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5130 if (const SCEV *S = createAddRecFromPHI(PN)) 5131 return S; 5132 5133 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5134 return S; 5135 5136 // If the PHI has a single incoming value, follow that value, unless the 5137 // PHI's incoming blocks are in a different loop, in which case doing so 5138 // risks breaking LCSSA form. Instcombine would normally zap these, but 5139 // it doesn't have DominatorTree information, so it may miss cases. 5140 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5141 if (LI.replacementPreservesLCSSAForm(PN, V)) 5142 return getSCEV(V); 5143 5144 // If it's not a loop phi, we can't handle it yet. 5145 return getUnknown(PN); 5146 } 5147 5148 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5149 Value *Cond, 5150 Value *TrueVal, 5151 Value *FalseVal) { 5152 // Handle "constant" branch or select. This can occur for instance when a 5153 // loop pass transforms an inner loop and moves on to process the outer loop. 5154 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5155 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5156 5157 // Try to match some simple smax or umax patterns. 5158 auto *ICI = dyn_cast<ICmpInst>(Cond); 5159 if (!ICI) 5160 return getUnknown(I); 5161 5162 Value *LHS = ICI->getOperand(0); 5163 Value *RHS = ICI->getOperand(1); 5164 5165 switch (ICI->getPredicate()) { 5166 case ICmpInst::ICMP_SLT: 5167 case ICmpInst::ICMP_SLE: 5168 std::swap(LHS, RHS); 5169 LLVM_FALLTHROUGH; 5170 case ICmpInst::ICMP_SGT: 5171 case ICmpInst::ICMP_SGE: 5172 // a >s b ? a+x : b+x -> smax(a, b)+x 5173 // a >s b ? b+x : a+x -> smin(a, b)+x 5174 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5175 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5176 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5177 const SCEV *LA = getSCEV(TrueVal); 5178 const SCEV *RA = getSCEV(FalseVal); 5179 const SCEV *LDiff = getMinusSCEV(LA, LS); 5180 const SCEV *RDiff = getMinusSCEV(RA, RS); 5181 if (LDiff == RDiff) 5182 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5183 LDiff = getMinusSCEV(LA, RS); 5184 RDiff = getMinusSCEV(RA, LS); 5185 if (LDiff == RDiff) 5186 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5187 } 5188 break; 5189 case ICmpInst::ICMP_ULT: 5190 case ICmpInst::ICMP_ULE: 5191 std::swap(LHS, RHS); 5192 LLVM_FALLTHROUGH; 5193 case ICmpInst::ICMP_UGT: 5194 case ICmpInst::ICMP_UGE: 5195 // a >u b ? a+x : b+x -> umax(a, b)+x 5196 // a >u b ? b+x : a+x -> umin(a, b)+x 5197 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5198 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5199 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5200 const SCEV *LA = getSCEV(TrueVal); 5201 const SCEV *RA = getSCEV(FalseVal); 5202 const SCEV *LDiff = getMinusSCEV(LA, LS); 5203 const SCEV *RDiff = getMinusSCEV(RA, RS); 5204 if (LDiff == RDiff) 5205 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5206 LDiff = getMinusSCEV(LA, RS); 5207 RDiff = getMinusSCEV(RA, LS); 5208 if (LDiff == RDiff) 5209 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5210 } 5211 break; 5212 case ICmpInst::ICMP_NE: 5213 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5214 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5215 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5216 const SCEV *One = getOne(I->getType()); 5217 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5218 const SCEV *LA = getSCEV(TrueVal); 5219 const SCEV *RA = getSCEV(FalseVal); 5220 const SCEV *LDiff = getMinusSCEV(LA, LS); 5221 const SCEV *RDiff = getMinusSCEV(RA, One); 5222 if (LDiff == RDiff) 5223 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5224 } 5225 break; 5226 case ICmpInst::ICMP_EQ: 5227 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5228 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5229 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5230 const SCEV *One = getOne(I->getType()); 5231 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5232 const SCEV *LA = getSCEV(TrueVal); 5233 const SCEV *RA = getSCEV(FalseVal); 5234 const SCEV *LDiff = getMinusSCEV(LA, One); 5235 const SCEV *RDiff = getMinusSCEV(RA, LS); 5236 if (LDiff == RDiff) 5237 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5238 } 5239 break; 5240 default: 5241 break; 5242 } 5243 5244 return getUnknown(I); 5245 } 5246 5247 /// Expand GEP instructions into add and multiply operations. This allows them 5248 /// to be analyzed by regular SCEV code. 5249 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5250 // Don't attempt to analyze GEPs over unsized objects. 5251 if (!GEP->getSourceElementType()->isSized()) 5252 return getUnknown(GEP); 5253 5254 SmallVector<const SCEV *, 4> IndexExprs; 5255 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5256 IndexExprs.push_back(getSCEV(*Index)); 5257 return getGEPExpr(GEP, IndexExprs); 5258 } 5259 5260 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5261 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5262 return C->getAPInt().countTrailingZeros(); 5263 5264 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5265 return std::min(GetMinTrailingZeros(T->getOperand()), 5266 (uint32_t)getTypeSizeInBits(T->getType())); 5267 5268 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5269 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5270 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5271 ? getTypeSizeInBits(E->getType()) 5272 : OpRes; 5273 } 5274 5275 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5276 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5277 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5278 ? getTypeSizeInBits(E->getType()) 5279 : OpRes; 5280 } 5281 5282 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5283 // The result is the min of all operands results. 5284 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5285 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5286 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5287 return MinOpRes; 5288 } 5289 5290 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5291 // The result is the sum of all operands results. 5292 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5293 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5294 for (unsigned i = 1, e = M->getNumOperands(); 5295 SumOpRes != BitWidth && i != e; ++i) 5296 SumOpRes = 5297 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5298 return SumOpRes; 5299 } 5300 5301 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5302 // The result is the min of all operands results. 5303 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5304 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5305 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5306 return MinOpRes; 5307 } 5308 5309 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5310 // The result is the min of all operands results. 5311 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5312 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5313 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5314 return MinOpRes; 5315 } 5316 5317 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5318 // The result is the min of all operands results. 5319 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5320 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5321 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5322 return MinOpRes; 5323 } 5324 5325 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5326 // For a SCEVUnknown, ask ValueTracking. 5327 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5328 return Known.countMinTrailingZeros(); 5329 } 5330 5331 // SCEVUDivExpr 5332 return 0; 5333 } 5334 5335 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5336 auto I = MinTrailingZerosCache.find(S); 5337 if (I != MinTrailingZerosCache.end()) 5338 return I->second; 5339 5340 uint32_t Result = GetMinTrailingZerosImpl(S); 5341 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5342 assert(InsertPair.second && "Should insert a new key"); 5343 return InsertPair.first->second; 5344 } 5345 5346 /// Helper method to assign a range to V from metadata present in the IR. 5347 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5348 if (Instruction *I = dyn_cast<Instruction>(V)) 5349 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5350 return getConstantRangeFromMetadata(*MD); 5351 5352 return None; 5353 } 5354 5355 /// Determine the range for a particular SCEV. If SignHint is 5356 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5357 /// with a "cleaner" unsigned (resp. signed) representation. 5358 const ConstantRange & 5359 ScalarEvolution::getRangeRef(const SCEV *S, 5360 ScalarEvolution::RangeSignHint SignHint) { 5361 DenseMap<const SCEV *, ConstantRange> &Cache = 5362 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5363 : SignedRanges; 5364 ConstantRange::PreferredRangeType RangeType = 5365 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5366 ? ConstantRange::Unsigned : ConstantRange::Signed; 5367 5368 // See if we've computed this range already. 5369 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5370 if (I != Cache.end()) 5371 return I->second; 5372 5373 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5374 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5375 5376 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5377 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5378 using OBO = OverflowingBinaryOperator; 5379 5380 // If the value has known zeros, the maximum value will have those known zeros 5381 // as well. 5382 uint32_t TZ = GetMinTrailingZeros(S); 5383 if (TZ != 0) { 5384 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5385 ConservativeResult = 5386 ConstantRange(APInt::getMinValue(BitWidth), 5387 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5388 else 5389 ConservativeResult = ConstantRange( 5390 APInt::getSignedMinValue(BitWidth), 5391 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5392 } 5393 5394 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5395 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5396 unsigned WrapType = OBO::AnyWrap; 5397 if (Add->hasNoSignedWrap()) 5398 WrapType |= OBO::NoSignedWrap; 5399 if (Add->hasNoUnsignedWrap()) 5400 WrapType |= OBO::NoUnsignedWrap; 5401 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5402 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5403 WrapType, RangeType); 5404 return setRange(Add, SignHint, 5405 ConservativeResult.intersectWith(X, RangeType)); 5406 } 5407 5408 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5409 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5410 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5411 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5412 return setRange(Mul, SignHint, 5413 ConservativeResult.intersectWith(X, RangeType)); 5414 } 5415 5416 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5417 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5418 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5419 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5420 return setRange(SMax, SignHint, 5421 ConservativeResult.intersectWith(X, RangeType)); 5422 } 5423 5424 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5425 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5426 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5427 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5428 return setRange(UMax, SignHint, 5429 ConservativeResult.intersectWith(X, RangeType)); 5430 } 5431 5432 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5433 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5434 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5435 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5436 return setRange(SMin, SignHint, 5437 ConservativeResult.intersectWith(X, RangeType)); 5438 } 5439 5440 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5441 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5442 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5443 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5444 return setRange(UMin, SignHint, 5445 ConservativeResult.intersectWith(X, RangeType)); 5446 } 5447 5448 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5449 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5450 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5451 return setRange(UDiv, SignHint, 5452 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5453 } 5454 5455 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5456 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5457 return setRange(ZExt, SignHint, 5458 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5459 RangeType)); 5460 } 5461 5462 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5463 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5464 return setRange(SExt, SignHint, 5465 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5466 RangeType)); 5467 } 5468 5469 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5470 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5471 return setRange(Trunc, SignHint, 5472 ConservativeResult.intersectWith(X.truncate(BitWidth), 5473 RangeType)); 5474 } 5475 5476 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5477 // If there's no unsigned wrap, the value will never be less than its 5478 // initial value. 5479 if (AddRec->hasNoUnsignedWrap()) { 5480 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5481 if (!UnsignedMinValue.isNullValue()) 5482 ConservativeResult = ConservativeResult.intersectWith( 5483 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5484 } 5485 5486 // If there's no signed wrap, and all the operands except initial value have 5487 // the same sign or zero, the value won't ever be: 5488 // 1: smaller than initial value if operands are non negative, 5489 // 2: bigger than initial value if operands are non positive. 5490 // For both cases, value can not cross signed min/max boundary. 5491 if (AddRec->hasNoSignedWrap()) { 5492 bool AllNonNeg = true; 5493 bool AllNonPos = true; 5494 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5495 if (!isKnownNonNegative(AddRec->getOperand(i))) 5496 AllNonNeg = false; 5497 if (!isKnownNonPositive(AddRec->getOperand(i))) 5498 AllNonPos = false; 5499 } 5500 if (AllNonNeg) 5501 ConservativeResult = ConservativeResult.intersectWith( 5502 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5503 APInt::getSignedMinValue(BitWidth)), 5504 RangeType); 5505 else if (AllNonPos) 5506 ConservativeResult = ConservativeResult.intersectWith( 5507 ConstantRange::getNonEmpty( 5508 APInt::getSignedMinValue(BitWidth), 5509 getSignedRangeMax(AddRec->getStart()) + 1), 5510 RangeType); 5511 } 5512 5513 // TODO: non-affine addrec 5514 if (AddRec->isAffine()) { 5515 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5516 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5517 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5518 auto RangeFromAffine = getRangeForAffineAR( 5519 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5520 BitWidth); 5521 ConservativeResult = 5522 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5523 5524 auto RangeFromFactoring = getRangeViaFactoring( 5525 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5526 BitWidth); 5527 ConservativeResult = 5528 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5529 } 5530 5531 // Now try symbolic BE count and more powerful methods. 5532 MaxBECount = computeMaxBackedgeTakenCount(AddRec->getLoop()); 5533 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5534 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5535 AddRec->hasNoSelfWrap()) { 5536 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 5537 AddRec, MaxBECount, BitWidth, SignHint); 5538 ConservativeResult = 5539 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 5540 } 5541 } 5542 5543 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5544 } 5545 5546 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5547 // Check if the IR explicitly contains !range metadata. 5548 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5549 if (MDRange.hasValue()) 5550 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5551 RangeType); 5552 5553 // Split here to avoid paying the compile-time cost of calling both 5554 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5555 // if needed. 5556 const DataLayout &DL = getDataLayout(); 5557 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5558 // For a SCEVUnknown, ask ValueTracking. 5559 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5560 if (Known.getBitWidth() != BitWidth) 5561 Known = Known.zextOrTrunc(BitWidth); 5562 // If Known does not result in full-set, intersect with it. 5563 if (Known.getMinValue() != Known.getMaxValue() + 1) 5564 ConservativeResult = ConservativeResult.intersectWith( 5565 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5566 RangeType); 5567 } else { 5568 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5569 "generalize as needed!"); 5570 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5571 // If the pointer size is larger than the index size type, this can cause 5572 // NS to be larger than BitWidth. So compensate for this. 5573 if (U->getType()->isPointerTy()) { 5574 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5575 int ptrIdxDiff = ptrSize - BitWidth; 5576 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5577 NS -= ptrIdxDiff; 5578 } 5579 5580 if (NS > 1) 5581 ConservativeResult = ConservativeResult.intersectWith( 5582 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5583 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5584 RangeType); 5585 } 5586 5587 // A range of Phi is a subset of union of all ranges of its input. 5588 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5589 // Make sure that we do not run over cycled Phis. 5590 if (PendingPhiRanges.insert(Phi).second) { 5591 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5592 for (auto &Op : Phi->operands()) { 5593 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5594 RangeFromOps = RangeFromOps.unionWith(OpRange); 5595 // No point to continue if we already have a full set. 5596 if (RangeFromOps.isFullSet()) 5597 break; 5598 } 5599 ConservativeResult = 5600 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5601 bool Erased = PendingPhiRanges.erase(Phi); 5602 assert(Erased && "Failed to erase Phi properly?"); 5603 (void) Erased; 5604 } 5605 } 5606 5607 return setRange(U, SignHint, std::move(ConservativeResult)); 5608 } 5609 5610 return setRange(S, SignHint, std::move(ConservativeResult)); 5611 } 5612 5613 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5614 // values that the expression can take. Initially, the expression has a value 5615 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5616 // argument defines if we treat Step as signed or unsigned. 5617 static ConstantRange getRangeForAffineARHelper(APInt Step, 5618 const ConstantRange &StartRange, 5619 const APInt &MaxBECount, 5620 unsigned BitWidth, bool Signed) { 5621 // If either Step or MaxBECount is 0, then the expression won't change, and we 5622 // just need to return the initial range. 5623 if (Step == 0 || MaxBECount == 0) 5624 return StartRange; 5625 5626 // If we don't know anything about the initial value (i.e. StartRange is 5627 // FullRange), then we don't know anything about the final range either. 5628 // Return FullRange. 5629 if (StartRange.isFullSet()) 5630 return ConstantRange::getFull(BitWidth); 5631 5632 // If Step is signed and negative, then we use its absolute value, but we also 5633 // note that we're moving in the opposite direction. 5634 bool Descending = Signed && Step.isNegative(); 5635 5636 if (Signed) 5637 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5638 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5639 // This equations hold true due to the well-defined wrap-around behavior of 5640 // APInt. 5641 Step = Step.abs(); 5642 5643 // Check if Offset is more than full span of BitWidth. If it is, the 5644 // expression is guaranteed to overflow. 5645 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5646 return ConstantRange::getFull(BitWidth); 5647 5648 // Offset is by how much the expression can change. Checks above guarantee no 5649 // overflow here. 5650 APInt Offset = Step * MaxBECount; 5651 5652 // Minimum value of the final range will match the minimal value of StartRange 5653 // if the expression is increasing and will be decreased by Offset otherwise. 5654 // Maximum value of the final range will match the maximal value of StartRange 5655 // if the expression is decreasing and will be increased by Offset otherwise. 5656 APInt StartLower = StartRange.getLower(); 5657 APInt StartUpper = StartRange.getUpper() - 1; 5658 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5659 : (StartUpper + std::move(Offset)); 5660 5661 // It's possible that the new minimum/maximum value will fall into the initial 5662 // range (due to wrap around). This means that the expression can take any 5663 // value in this bitwidth, and we have to return full range. 5664 if (StartRange.contains(MovedBoundary)) 5665 return ConstantRange::getFull(BitWidth); 5666 5667 APInt NewLower = 5668 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5669 APInt NewUpper = 5670 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5671 NewUpper += 1; 5672 5673 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5674 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5675 } 5676 5677 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5678 const SCEV *Step, 5679 const SCEV *MaxBECount, 5680 unsigned BitWidth) { 5681 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5682 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5683 "Precondition!"); 5684 5685 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5686 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5687 5688 // First, consider step signed. 5689 ConstantRange StartSRange = getSignedRange(Start); 5690 ConstantRange StepSRange = getSignedRange(Step); 5691 5692 // If Step can be both positive and negative, we need to find ranges for the 5693 // maximum absolute step values in both directions and union them. 5694 ConstantRange SR = 5695 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5696 MaxBECountValue, BitWidth, /* Signed = */ true); 5697 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5698 StartSRange, MaxBECountValue, 5699 BitWidth, /* Signed = */ true)); 5700 5701 // Next, consider step unsigned. 5702 ConstantRange UR = getRangeForAffineARHelper( 5703 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5704 MaxBECountValue, BitWidth, /* Signed = */ false); 5705 5706 // Finally, intersect signed and unsigned ranges. 5707 return SR.intersectWith(UR, ConstantRange::Smallest); 5708 } 5709 5710 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 5711 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 5712 ScalarEvolution::RangeSignHint SignHint) { 5713 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 5714 assert(AddRec->hasNoSelfWrap() && 5715 "This only works for non-self-wrapping AddRecs!"); 5716 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 5717 const SCEV *Step = AddRec->getStepRecurrence(*this); 5718 // Let's make sure that we can prove that we do not self-wrap during 5719 // MaxBECount iterations. We need this because MaxBECount is a maximum 5720 // iteration count estimate, and we might infer nw from some exit for which we 5721 // do not know max exit count (or any other side reasoning). 5722 // TODO: Turn into assert at some point. 5723 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 5724 const SCEV *RangeWidth = getNegativeSCEV(getOne(AddRec->getType())); 5725 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 5726 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 5727 if (!isKnownPredicate(ICmpInst::ICMP_ULE, MaxBECount, MaxItersWithoutWrap)) 5728 return ConstantRange::getFull(BitWidth); 5729 5730 ICmpInst::Predicate LEPred = 5731 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 5732 ICmpInst::Predicate GEPred = 5733 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 5734 const SCEV *Start = AddRec->getStart(); 5735 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 5736 5737 // We know that there is no self-wrap. Let's take Start and End values and 5738 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 5739 // the iteration. They either lie inside the range [Min(Start, End), 5740 // Max(Start, End)] or outside it: 5741 // 5742 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 5743 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 5744 // 5745 // No self wrap flag guarantees that the intermediate values cannot be BOTH 5746 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 5747 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 5748 // Start <= End and step is positive, or Start >= End and step is negative. 5749 ConstantRange StartRange = 5750 IsSigned ? getSignedRange(Start) : getUnsignedRange(Start); 5751 ConstantRange EndRange = 5752 IsSigned ? getSignedRange(End) : getUnsignedRange(End); 5753 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 5754 // If they already cover full iteration space, we will know nothing useful 5755 // even if we prove what we want to prove. 5756 if (RangeBetween.isFullSet()) 5757 return RangeBetween; 5758 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 5759 bool IsWrappingRange = 5760 IsSigned ? RangeBetween.getLower().sge(RangeBetween.getUpper()) 5761 : RangeBetween.getLower().uge(RangeBetween.getUpper()); 5762 if (IsWrappingRange) 5763 return ConstantRange::getFull(BitWidth); 5764 5765 if (isKnownPositive(Step) && 5766 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 5767 return RangeBetween; 5768 else if (isKnownNegative(Step) && 5769 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 5770 return RangeBetween; 5771 return ConstantRange::getFull(BitWidth); 5772 } 5773 5774 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5775 const SCEV *Step, 5776 const SCEV *MaxBECount, 5777 unsigned BitWidth) { 5778 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5779 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5780 5781 struct SelectPattern { 5782 Value *Condition = nullptr; 5783 APInt TrueValue; 5784 APInt FalseValue; 5785 5786 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5787 const SCEV *S) { 5788 Optional<unsigned> CastOp; 5789 APInt Offset(BitWidth, 0); 5790 5791 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5792 "Should be!"); 5793 5794 // Peel off a constant offset: 5795 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5796 // In the future we could consider being smarter here and handle 5797 // {Start+Step,+,Step} too. 5798 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5799 return; 5800 5801 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5802 S = SA->getOperand(1); 5803 } 5804 5805 // Peel off a cast operation 5806 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 5807 CastOp = SCast->getSCEVType(); 5808 S = SCast->getOperand(); 5809 } 5810 5811 using namespace llvm::PatternMatch; 5812 5813 auto *SU = dyn_cast<SCEVUnknown>(S); 5814 const APInt *TrueVal, *FalseVal; 5815 if (!SU || 5816 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5817 m_APInt(FalseVal)))) { 5818 Condition = nullptr; 5819 return; 5820 } 5821 5822 TrueValue = *TrueVal; 5823 FalseValue = *FalseVal; 5824 5825 // Re-apply the cast we peeled off earlier 5826 if (CastOp.hasValue()) 5827 switch (*CastOp) { 5828 default: 5829 llvm_unreachable("Unknown SCEV cast type!"); 5830 5831 case scTruncate: 5832 TrueValue = TrueValue.trunc(BitWidth); 5833 FalseValue = FalseValue.trunc(BitWidth); 5834 break; 5835 case scZeroExtend: 5836 TrueValue = TrueValue.zext(BitWidth); 5837 FalseValue = FalseValue.zext(BitWidth); 5838 break; 5839 case scSignExtend: 5840 TrueValue = TrueValue.sext(BitWidth); 5841 FalseValue = FalseValue.sext(BitWidth); 5842 break; 5843 } 5844 5845 // Re-apply the constant offset we peeled off earlier 5846 TrueValue += Offset; 5847 FalseValue += Offset; 5848 } 5849 5850 bool isRecognized() { return Condition != nullptr; } 5851 }; 5852 5853 SelectPattern StartPattern(*this, BitWidth, Start); 5854 if (!StartPattern.isRecognized()) 5855 return ConstantRange::getFull(BitWidth); 5856 5857 SelectPattern StepPattern(*this, BitWidth, Step); 5858 if (!StepPattern.isRecognized()) 5859 return ConstantRange::getFull(BitWidth); 5860 5861 if (StartPattern.Condition != StepPattern.Condition) { 5862 // We don't handle this case today; but we could, by considering four 5863 // possibilities below instead of two. I'm not sure if there are cases where 5864 // that will help over what getRange already does, though. 5865 return ConstantRange::getFull(BitWidth); 5866 } 5867 5868 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5869 // construct arbitrary general SCEV expressions here. This function is called 5870 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5871 // say) can end up caching a suboptimal value. 5872 5873 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5874 // C2352 and C2512 (otherwise it isn't needed). 5875 5876 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5877 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5878 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5879 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5880 5881 ConstantRange TrueRange = 5882 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5883 ConstantRange FalseRange = 5884 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5885 5886 return TrueRange.unionWith(FalseRange); 5887 } 5888 5889 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5890 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5891 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5892 5893 // Return early if there are no flags to propagate to the SCEV. 5894 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5895 if (BinOp->hasNoUnsignedWrap()) 5896 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5897 if (BinOp->hasNoSignedWrap()) 5898 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5899 if (Flags == SCEV::FlagAnyWrap) 5900 return SCEV::FlagAnyWrap; 5901 5902 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5903 } 5904 5905 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5906 // Here we check that I is in the header of the innermost loop containing I, 5907 // since we only deal with instructions in the loop header. The actual loop we 5908 // need to check later will come from an add recurrence, but getting that 5909 // requires computing the SCEV of the operands, which can be expensive. This 5910 // check we can do cheaply to rule out some cases early. 5911 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5912 if (InnermostContainingLoop == nullptr || 5913 InnermostContainingLoop->getHeader() != I->getParent()) 5914 return false; 5915 5916 // Only proceed if we can prove that I does not yield poison. 5917 if (!programUndefinedIfPoison(I)) 5918 return false; 5919 5920 // At this point we know that if I is executed, then it does not wrap 5921 // according to at least one of NSW or NUW. If I is not executed, then we do 5922 // not know if the calculation that I represents would wrap. Multiple 5923 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5924 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5925 // derived from other instructions that map to the same SCEV. We cannot make 5926 // that guarantee for cases where I is not executed. So we need to find the 5927 // loop that I is considered in relation to and prove that I is executed for 5928 // every iteration of that loop. That implies that the value that I 5929 // calculates does not wrap anywhere in the loop, so then we can apply the 5930 // flags to the SCEV. 5931 // 5932 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5933 // from different loops, so that we know which loop to prove that I is 5934 // executed in. 5935 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5936 // I could be an extractvalue from a call to an overflow intrinsic. 5937 // TODO: We can do better here in some cases. 5938 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5939 return false; 5940 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5941 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5942 bool AllOtherOpsLoopInvariant = true; 5943 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5944 ++OtherOpIndex) { 5945 if (OtherOpIndex != OpIndex) { 5946 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5947 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5948 AllOtherOpsLoopInvariant = false; 5949 break; 5950 } 5951 } 5952 } 5953 if (AllOtherOpsLoopInvariant && 5954 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5955 return true; 5956 } 5957 } 5958 return false; 5959 } 5960 5961 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5962 // If we know that \c I can never be poison period, then that's enough. 5963 if (isSCEVExprNeverPoison(I)) 5964 return true; 5965 5966 // For an add recurrence specifically, we assume that infinite loops without 5967 // side effects are undefined behavior, and then reason as follows: 5968 // 5969 // If the add recurrence is poison in any iteration, it is poison on all 5970 // future iterations (since incrementing poison yields poison). If the result 5971 // of the add recurrence is fed into the loop latch condition and the loop 5972 // does not contain any throws or exiting blocks other than the latch, we now 5973 // have the ability to "choose" whether the backedge is taken or not (by 5974 // choosing a sufficiently evil value for the poison feeding into the branch) 5975 // for every iteration including and after the one in which \p I first became 5976 // poison. There are two possibilities (let's call the iteration in which \p 5977 // I first became poison as K): 5978 // 5979 // 1. In the set of iterations including and after K, the loop body executes 5980 // no side effects. In this case executing the backege an infinte number 5981 // of times will yield undefined behavior. 5982 // 5983 // 2. In the set of iterations including and after K, the loop body executes 5984 // at least one side effect. In this case, that specific instance of side 5985 // effect is control dependent on poison, which also yields undefined 5986 // behavior. 5987 5988 auto *ExitingBB = L->getExitingBlock(); 5989 auto *LatchBB = L->getLoopLatch(); 5990 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5991 return false; 5992 5993 SmallPtrSet<const Instruction *, 16> Pushed; 5994 SmallVector<const Instruction *, 8> PoisonStack; 5995 5996 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5997 // things that are known to be poison under that assumption go on the 5998 // PoisonStack. 5999 Pushed.insert(I); 6000 PoisonStack.push_back(I); 6001 6002 bool LatchControlDependentOnPoison = false; 6003 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6004 const Instruction *Poison = PoisonStack.pop_back_val(); 6005 6006 for (auto *PoisonUser : Poison->users()) { 6007 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6008 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6009 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6010 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6011 assert(BI->isConditional() && "Only possibility!"); 6012 if (BI->getParent() == LatchBB) { 6013 LatchControlDependentOnPoison = true; 6014 break; 6015 } 6016 } 6017 } 6018 } 6019 6020 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6021 } 6022 6023 ScalarEvolution::LoopProperties 6024 ScalarEvolution::getLoopProperties(const Loop *L) { 6025 using LoopProperties = ScalarEvolution::LoopProperties; 6026 6027 auto Itr = LoopPropertiesCache.find(L); 6028 if (Itr == LoopPropertiesCache.end()) { 6029 auto HasSideEffects = [](Instruction *I) { 6030 if (auto *SI = dyn_cast<StoreInst>(I)) 6031 return !SI->isSimple(); 6032 6033 return I->mayHaveSideEffects(); 6034 }; 6035 6036 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6037 /*HasNoSideEffects*/ true}; 6038 6039 for (auto *BB : L->getBlocks()) 6040 for (auto &I : *BB) { 6041 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6042 LP.HasNoAbnormalExits = false; 6043 if (HasSideEffects(&I)) 6044 LP.HasNoSideEffects = false; 6045 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6046 break; // We're already as pessimistic as we can get. 6047 } 6048 6049 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6050 assert(InsertPair.second && "We just checked!"); 6051 Itr = InsertPair.first; 6052 } 6053 6054 return Itr->second; 6055 } 6056 6057 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6058 if (!isSCEVable(V->getType())) 6059 return getUnknown(V); 6060 6061 if (Instruction *I = dyn_cast<Instruction>(V)) { 6062 // Don't attempt to analyze instructions in blocks that aren't 6063 // reachable. Such instructions don't matter, and they aren't required 6064 // to obey basic rules for definitions dominating uses which this 6065 // analysis depends on. 6066 if (!DT.isReachableFromEntry(I->getParent())) 6067 return getUnknown(UndefValue::get(V->getType())); 6068 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6069 return getConstant(CI); 6070 else if (isa<ConstantPointerNull>(V)) 6071 return getZero(V->getType()); 6072 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6073 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6074 else if (!isa<ConstantExpr>(V)) 6075 return getUnknown(V); 6076 6077 Operator *U = cast<Operator>(V); 6078 if (auto BO = MatchBinaryOp(U, DT)) { 6079 switch (BO->Opcode) { 6080 case Instruction::Add: { 6081 // The simple thing to do would be to just call getSCEV on both operands 6082 // and call getAddExpr with the result. However if we're looking at a 6083 // bunch of things all added together, this can be quite inefficient, 6084 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6085 // Instead, gather up all the operands and make a single getAddExpr call. 6086 // LLVM IR canonical form means we need only traverse the left operands. 6087 SmallVector<const SCEV *, 4> AddOps; 6088 do { 6089 if (BO->Op) { 6090 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6091 AddOps.push_back(OpSCEV); 6092 break; 6093 } 6094 6095 // If a NUW or NSW flag can be applied to the SCEV for this 6096 // addition, then compute the SCEV for this addition by itself 6097 // with a separate call to getAddExpr. We need to do that 6098 // instead of pushing the operands of the addition onto AddOps, 6099 // since the flags are only known to apply to this particular 6100 // addition - they may not apply to other additions that can be 6101 // formed with operands from AddOps. 6102 const SCEV *RHS = getSCEV(BO->RHS); 6103 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6104 if (Flags != SCEV::FlagAnyWrap) { 6105 const SCEV *LHS = getSCEV(BO->LHS); 6106 if (BO->Opcode == Instruction::Sub) 6107 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6108 else 6109 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6110 break; 6111 } 6112 } 6113 6114 if (BO->Opcode == Instruction::Sub) 6115 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6116 else 6117 AddOps.push_back(getSCEV(BO->RHS)); 6118 6119 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6120 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6121 NewBO->Opcode != Instruction::Sub)) { 6122 AddOps.push_back(getSCEV(BO->LHS)); 6123 break; 6124 } 6125 BO = NewBO; 6126 } while (true); 6127 6128 return getAddExpr(AddOps); 6129 } 6130 6131 case Instruction::Mul: { 6132 SmallVector<const SCEV *, 4> MulOps; 6133 do { 6134 if (BO->Op) { 6135 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6136 MulOps.push_back(OpSCEV); 6137 break; 6138 } 6139 6140 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6141 if (Flags != SCEV::FlagAnyWrap) { 6142 MulOps.push_back( 6143 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6144 break; 6145 } 6146 } 6147 6148 MulOps.push_back(getSCEV(BO->RHS)); 6149 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6150 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6151 MulOps.push_back(getSCEV(BO->LHS)); 6152 break; 6153 } 6154 BO = NewBO; 6155 } while (true); 6156 6157 return getMulExpr(MulOps); 6158 } 6159 case Instruction::UDiv: 6160 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6161 case Instruction::URem: 6162 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6163 case Instruction::Sub: { 6164 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6165 if (BO->Op) 6166 Flags = getNoWrapFlagsFromUB(BO->Op); 6167 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6168 } 6169 case Instruction::And: 6170 // For an expression like x&255 that merely masks off the high bits, 6171 // use zext(trunc(x)) as the SCEV expression. 6172 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6173 if (CI->isZero()) 6174 return getSCEV(BO->RHS); 6175 if (CI->isMinusOne()) 6176 return getSCEV(BO->LHS); 6177 const APInt &A = CI->getValue(); 6178 6179 // Instcombine's ShrinkDemandedConstant may strip bits out of 6180 // constants, obscuring what would otherwise be a low-bits mask. 6181 // Use computeKnownBits to compute what ShrinkDemandedConstant 6182 // knew about to reconstruct a low-bits mask value. 6183 unsigned LZ = A.countLeadingZeros(); 6184 unsigned TZ = A.countTrailingZeros(); 6185 unsigned BitWidth = A.getBitWidth(); 6186 KnownBits Known(BitWidth); 6187 computeKnownBits(BO->LHS, Known, getDataLayout(), 6188 0, &AC, nullptr, &DT); 6189 6190 APInt EffectiveMask = 6191 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6192 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6193 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6194 const SCEV *LHS = getSCEV(BO->LHS); 6195 const SCEV *ShiftedLHS = nullptr; 6196 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6197 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6198 // For an expression like (x * 8) & 8, simplify the multiply. 6199 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6200 unsigned GCD = std::min(MulZeros, TZ); 6201 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6202 SmallVector<const SCEV*, 4> MulOps; 6203 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6204 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6205 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6206 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6207 } 6208 } 6209 if (!ShiftedLHS) 6210 ShiftedLHS = getUDivExpr(LHS, MulCount); 6211 return getMulExpr( 6212 getZeroExtendExpr( 6213 getTruncateExpr(ShiftedLHS, 6214 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6215 BO->LHS->getType()), 6216 MulCount); 6217 } 6218 } 6219 break; 6220 6221 case Instruction::Or: 6222 // If the RHS of the Or is a constant, we may have something like: 6223 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6224 // optimizations will transparently handle this case. 6225 // 6226 // In order for this transformation to be safe, the LHS must be of the 6227 // form X*(2^n) and the Or constant must be less than 2^n. 6228 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6229 const SCEV *LHS = getSCEV(BO->LHS); 6230 const APInt &CIVal = CI->getValue(); 6231 if (GetMinTrailingZeros(LHS) >= 6232 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6233 // Build a plain add SCEV. 6234 return getAddExpr(LHS, getSCEV(CI), 6235 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6236 } 6237 } 6238 break; 6239 6240 case Instruction::Xor: 6241 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6242 // If the RHS of xor is -1, then this is a not operation. 6243 if (CI->isMinusOne()) 6244 return getNotSCEV(getSCEV(BO->LHS)); 6245 6246 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6247 // This is a variant of the check for xor with -1, and it handles 6248 // the case where instcombine has trimmed non-demanded bits out 6249 // of an xor with -1. 6250 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6251 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6252 if (LBO->getOpcode() == Instruction::And && 6253 LCI->getValue() == CI->getValue()) 6254 if (const SCEVZeroExtendExpr *Z = 6255 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6256 Type *UTy = BO->LHS->getType(); 6257 const SCEV *Z0 = Z->getOperand(); 6258 Type *Z0Ty = Z0->getType(); 6259 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6260 6261 // If C is a low-bits mask, the zero extend is serving to 6262 // mask off the high bits. Complement the operand and 6263 // re-apply the zext. 6264 if (CI->getValue().isMask(Z0TySize)) 6265 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6266 6267 // If C is a single bit, it may be in the sign-bit position 6268 // before the zero-extend. In this case, represent the xor 6269 // using an add, which is equivalent, and re-apply the zext. 6270 APInt Trunc = CI->getValue().trunc(Z0TySize); 6271 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6272 Trunc.isSignMask()) 6273 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6274 UTy); 6275 } 6276 } 6277 break; 6278 6279 case Instruction::Shl: 6280 // Turn shift left of a constant amount into a multiply. 6281 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6282 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6283 6284 // If the shift count is not less than the bitwidth, the result of 6285 // the shift is undefined. Don't try to analyze it, because the 6286 // resolution chosen here may differ from the resolution chosen in 6287 // other parts of the compiler. 6288 if (SA->getValue().uge(BitWidth)) 6289 break; 6290 6291 // We can safely preserve the nuw flag in all cases. It's also safe to 6292 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6293 // requires special handling. It can be preserved as long as we're not 6294 // left shifting by bitwidth - 1. 6295 auto Flags = SCEV::FlagAnyWrap; 6296 if (BO->Op) { 6297 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6298 if ((MulFlags & SCEV::FlagNSW) && 6299 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6300 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6301 if (MulFlags & SCEV::FlagNUW) 6302 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6303 } 6304 6305 Constant *X = ConstantInt::get( 6306 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6307 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6308 } 6309 break; 6310 6311 case Instruction::AShr: { 6312 // AShr X, C, where C is a constant. 6313 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6314 if (!CI) 6315 break; 6316 6317 Type *OuterTy = BO->LHS->getType(); 6318 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6319 // If the shift count is not less than the bitwidth, the result of 6320 // the shift is undefined. Don't try to analyze it, because the 6321 // resolution chosen here may differ from the resolution chosen in 6322 // other parts of the compiler. 6323 if (CI->getValue().uge(BitWidth)) 6324 break; 6325 6326 if (CI->isZero()) 6327 return getSCEV(BO->LHS); // shift by zero --> noop 6328 6329 uint64_t AShrAmt = CI->getZExtValue(); 6330 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6331 6332 Operator *L = dyn_cast<Operator>(BO->LHS); 6333 if (L && L->getOpcode() == Instruction::Shl) { 6334 // X = Shl A, n 6335 // Y = AShr X, m 6336 // Both n and m are constant. 6337 6338 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6339 if (L->getOperand(1) == BO->RHS) 6340 // For a two-shift sext-inreg, i.e. n = m, 6341 // use sext(trunc(x)) as the SCEV expression. 6342 return getSignExtendExpr( 6343 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6344 6345 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6346 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6347 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6348 if (ShlAmt > AShrAmt) { 6349 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6350 // expression. We already checked that ShlAmt < BitWidth, so 6351 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6352 // ShlAmt - AShrAmt < Amt. 6353 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6354 ShlAmt - AShrAmt); 6355 return getSignExtendExpr( 6356 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6357 getConstant(Mul)), OuterTy); 6358 } 6359 } 6360 } 6361 if (BO->IsExact) { 6362 // Given exact arithmetic in-bounds right-shift by a constant, 6363 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6364 const SCEV *X = getSCEV(BO->LHS); 6365 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6366 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6367 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6368 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6369 } 6370 break; 6371 } 6372 } 6373 } 6374 6375 switch (U->getOpcode()) { 6376 case Instruction::Trunc: 6377 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6378 6379 case Instruction::ZExt: 6380 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6381 6382 case Instruction::SExt: 6383 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6384 // The NSW flag of a subtract does not always survive the conversion to 6385 // A + (-1)*B. By pushing sign extension onto its operands we are much 6386 // more likely to preserve NSW and allow later AddRec optimisations. 6387 // 6388 // NOTE: This is effectively duplicating this logic from getSignExtend: 6389 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6390 // but by that point the NSW information has potentially been lost. 6391 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6392 Type *Ty = U->getType(); 6393 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6394 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6395 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6396 } 6397 } 6398 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6399 6400 case Instruction::BitCast: 6401 // BitCasts are no-op casts so we just eliminate the cast. 6402 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6403 return getSCEV(U->getOperand(0)); 6404 break; 6405 6406 case Instruction::SDiv: 6407 // If both operands are non-negative, this is just an udiv. 6408 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6409 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6410 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6411 break; 6412 6413 case Instruction::SRem: 6414 // If both operands are non-negative, this is just an urem. 6415 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6416 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6417 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6418 break; 6419 6420 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6421 // lead to pointer expressions which cannot safely be expanded to GEPs, 6422 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6423 // simplifying integer expressions. 6424 6425 case Instruction::GetElementPtr: 6426 return createNodeForGEP(cast<GEPOperator>(U)); 6427 6428 case Instruction::PHI: 6429 return createNodeForPHI(cast<PHINode>(U)); 6430 6431 case Instruction::Select: 6432 // U can also be a select constant expr, which let fall through. Since 6433 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6434 // constant expressions cannot have instructions as operands, we'd have 6435 // returned getUnknown for a select constant expressions anyway. 6436 if (isa<Instruction>(U)) 6437 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6438 U->getOperand(1), U->getOperand(2)); 6439 break; 6440 6441 case Instruction::Call: 6442 case Instruction::Invoke: 6443 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6444 return getSCEV(RV); 6445 6446 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6447 switch (II->getIntrinsicID()) { 6448 case Intrinsic::abs: 6449 return getAbsExpr( 6450 getSCEV(II->getArgOperand(0)), 6451 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6452 case Intrinsic::umax: 6453 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6454 getSCEV(II->getArgOperand(1))); 6455 case Intrinsic::umin: 6456 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6457 getSCEV(II->getArgOperand(1))); 6458 case Intrinsic::smax: 6459 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6460 getSCEV(II->getArgOperand(1))); 6461 case Intrinsic::smin: 6462 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6463 getSCEV(II->getArgOperand(1))); 6464 case Intrinsic::usub_sat: { 6465 const SCEV *X = getSCEV(II->getArgOperand(0)); 6466 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6467 const SCEV *ClampedY = getUMinExpr(X, Y); 6468 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6469 } 6470 case Intrinsic::uadd_sat: { 6471 const SCEV *X = getSCEV(II->getArgOperand(0)); 6472 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6473 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6474 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6475 } 6476 default: 6477 break; 6478 } 6479 } 6480 break; 6481 } 6482 6483 return getUnknown(V); 6484 } 6485 6486 //===----------------------------------------------------------------------===// 6487 // Iteration Count Computation Code 6488 // 6489 6490 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6491 if (!ExitCount) 6492 return 0; 6493 6494 ConstantInt *ExitConst = ExitCount->getValue(); 6495 6496 // Guard against huge trip counts. 6497 if (ExitConst->getValue().getActiveBits() > 32) 6498 return 0; 6499 6500 // In case of integer overflow, this returns 0, which is correct. 6501 return ((unsigned)ExitConst->getZExtValue()) + 1; 6502 } 6503 6504 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6505 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6506 return getSmallConstantTripCount(L, ExitingBB); 6507 6508 // No trip count information for multiple exits. 6509 return 0; 6510 } 6511 6512 unsigned 6513 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6514 const BasicBlock *ExitingBlock) { 6515 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6516 assert(L->isLoopExiting(ExitingBlock) && 6517 "Exiting block must actually branch out of the loop!"); 6518 const SCEVConstant *ExitCount = 6519 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6520 return getConstantTripCount(ExitCount); 6521 } 6522 6523 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6524 const auto *MaxExitCount = 6525 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6526 return getConstantTripCount(MaxExitCount); 6527 } 6528 6529 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6530 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6531 return getSmallConstantTripMultiple(L, ExitingBB); 6532 6533 // No trip multiple information for multiple exits. 6534 return 0; 6535 } 6536 6537 /// Returns the largest constant divisor of the trip count of this loop as a 6538 /// normal unsigned value, if possible. This means that the actual trip count is 6539 /// always a multiple of the returned value (don't forget the trip count could 6540 /// very well be zero as well!). 6541 /// 6542 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6543 /// multiple of a constant (which is also the case if the trip count is simply 6544 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6545 /// if the trip count is very large (>= 2^32). 6546 /// 6547 /// As explained in the comments for getSmallConstantTripCount, this assumes 6548 /// that control exits the loop via ExitingBlock. 6549 unsigned 6550 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6551 const BasicBlock *ExitingBlock) { 6552 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6553 assert(L->isLoopExiting(ExitingBlock) && 6554 "Exiting block must actually branch out of the loop!"); 6555 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6556 if (ExitCount == getCouldNotCompute()) 6557 return 1; 6558 6559 // Get the trip count from the BE count by adding 1. 6560 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6561 6562 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6563 if (!TC) 6564 // Attempt to factor more general cases. Returns the greatest power of 6565 // two divisor. If overflow happens, the trip count expression is still 6566 // divisible by the greatest power of 2 divisor returned. 6567 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6568 6569 ConstantInt *Result = TC->getValue(); 6570 6571 // Guard against huge trip counts (this requires checking 6572 // for zero to handle the case where the trip count == -1 and the 6573 // addition wraps). 6574 if (!Result || Result->getValue().getActiveBits() > 32 || 6575 Result->getValue().getActiveBits() == 0) 6576 return 1; 6577 6578 return (unsigned)Result->getZExtValue(); 6579 } 6580 6581 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6582 const BasicBlock *ExitingBlock, 6583 ExitCountKind Kind) { 6584 switch (Kind) { 6585 case Exact: 6586 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6587 case ConstantMaximum: 6588 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6589 }; 6590 llvm_unreachable("Invalid ExitCountKind!"); 6591 } 6592 6593 const SCEV * 6594 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6595 SCEVUnionPredicate &Preds) { 6596 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6597 } 6598 6599 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6600 ExitCountKind Kind) { 6601 switch (Kind) { 6602 case Exact: 6603 return getBackedgeTakenInfo(L).getExact(L, this); 6604 case ConstantMaximum: 6605 return getBackedgeTakenInfo(L).getMax(this); 6606 }; 6607 llvm_unreachable("Invalid ExitCountKind!"); 6608 } 6609 6610 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6611 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6612 } 6613 6614 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6615 static void 6616 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6617 BasicBlock *Header = L->getHeader(); 6618 6619 // Push all Loop-header PHIs onto the Worklist stack. 6620 for (PHINode &PN : Header->phis()) 6621 Worklist.push_back(&PN); 6622 } 6623 6624 const ScalarEvolution::BackedgeTakenInfo & 6625 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6626 auto &BTI = getBackedgeTakenInfo(L); 6627 if (BTI.hasFullInfo()) 6628 return BTI; 6629 6630 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6631 6632 if (!Pair.second) 6633 return Pair.first->second; 6634 6635 BackedgeTakenInfo Result = 6636 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6637 6638 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6639 } 6640 6641 const ScalarEvolution::BackedgeTakenInfo & 6642 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6643 // Initially insert an invalid entry for this loop. If the insertion 6644 // succeeds, proceed to actually compute a backedge-taken count and 6645 // update the value. The temporary CouldNotCompute value tells SCEV 6646 // code elsewhere that it shouldn't attempt to request a new 6647 // backedge-taken count, which could result in infinite recursion. 6648 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6649 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6650 if (!Pair.second) 6651 return Pair.first->second; 6652 6653 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6654 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6655 // must be cleared in this scope. 6656 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6657 6658 // In product build, there are no usage of statistic. 6659 (void)NumTripCountsComputed; 6660 (void)NumTripCountsNotComputed; 6661 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6662 const SCEV *BEExact = Result.getExact(L, this); 6663 if (BEExact != getCouldNotCompute()) { 6664 assert(isLoopInvariant(BEExact, L) && 6665 isLoopInvariant(Result.getMax(this), L) && 6666 "Computed backedge-taken count isn't loop invariant for loop!"); 6667 ++NumTripCountsComputed; 6668 } 6669 else if (Result.getMax(this) == getCouldNotCompute() && 6670 isa<PHINode>(L->getHeader()->begin())) { 6671 // Only count loops that have phi nodes as not being computable. 6672 ++NumTripCountsNotComputed; 6673 } 6674 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6675 6676 // Now that we know more about the trip count for this loop, forget any 6677 // existing SCEV values for PHI nodes in this loop since they are only 6678 // conservative estimates made without the benefit of trip count 6679 // information. This is similar to the code in forgetLoop, except that 6680 // it handles SCEVUnknown PHI nodes specially. 6681 if (Result.hasAnyInfo()) { 6682 SmallVector<Instruction *, 16> Worklist; 6683 PushLoopPHIs(L, Worklist); 6684 6685 SmallPtrSet<Instruction *, 8> Discovered; 6686 while (!Worklist.empty()) { 6687 Instruction *I = Worklist.pop_back_val(); 6688 6689 ValueExprMapType::iterator It = 6690 ValueExprMap.find_as(static_cast<Value *>(I)); 6691 if (It != ValueExprMap.end()) { 6692 const SCEV *Old = It->second; 6693 6694 // SCEVUnknown for a PHI either means that it has an unrecognized 6695 // structure, or it's a PHI that's in the progress of being computed 6696 // by createNodeForPHI. In the former case, additional loop trip 6697 // count information isn't going to change anything. In the later 6698 // case, createNodeForPHI will perform the necessary updates on its 6699 // own when it gets to that point. 6700 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6701 eraseValueFromMap(It->first); 6702 forgetMemoizedResults(Old); 6703 } 6704 if (PHINode *PN = dyn_cast<PHINode>(I)) 6705 ConstantEvolutionLoopExitValue.erase(PN); 6706 } 6707 6708 // Since we don't need to invalidate anything for correctness and we're 6709 // only invalidating to make SCEV's results more precise, we get to stop 6710 // early to avoid invalidating too much. This is especially important in 6711 // cases like: 6712 // 6713 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6714 // loop0: 6715 // %pn0 = phi 6716 // ... 6717 // loop1: 6718 // %pn1 = phi 6719 // ... 6720 // 6721 // where both loop0 and loop1's backedge taken count uses the SCEV 6722 // expression for %v. If we don't have the early stop below then in cases 6723 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6724 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6725 // count for loop1, effectively nullifying SCEV's trip count cache. 6726 for (auto *U : I->users()) 6727 if (auto *I = dyn_cast<Instruction>(U)) { 6728 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6729 if (LoopForUser && L->contains(LoopForUser) && 6730 Discovered.insert(I).second) 6731 Worklist.push_back(I); 6732 } 6733 } 6734 } 6735 6736 // Re-lookup the insert position, since the call to 6737 // computeBackedgeTakenCount above could result in a 6738 // recusive call to getBackedgeTakenInfo (on a different 6739 // loop), which would invalidate the iterator computed 6740 // earlier. 6741 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6742 } 6743 6744 void ScalarEvolution::forgetAllLoops() { 6745 // This method is intended to forget all info about loops. It should 6746 // invalidate caches as if the following happened: 6747 // - The trip counts of all loops have changed arbitrarily 6748 // - Every llvm::Value has been updated in place to produce a different 6749 // result. 6750 BackedgeTakenCounts.clear(); 6751 PredicatedBackedgeTakenCounts.clear(); 6752 LoopPropertiesCache.clear(); 6753 ConstantEvolutionLoopExitValue.clear(); 6754 ValueExprMap.clear(); 6755 ValuesAtScopes.clear(); 6756 LoopDispositions.clear(); 6757 BlockDispositions.clear(); 6758 UnsignedRanges.clear(); 6759 SignedRanges.clear(); 6760 ExprValueMap.clear(); 6761 HasRecMap.clear(); 6762 MinTrailingZerosCache.clear(); 6763 PredicatedSCEVRewrites.clear(); 6764 } 6765 6766 void ScalarEvolution::forgetLoop(const Loop *L) { 6767 // Drop any stored trip count value. 6768 auto RemoveLoopFromBackedgeMap = 6769 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6770 auto BTCPos = Map.find(L); 6771 if (BTCPos != Map.end()) { 6772 BTCPos->second.clear(); 6773 Map.erase(BTCPos); 6774 } 6775 }; 6776 6777 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6778 SmallVector<Instruction *, 32> Worklist; 6779 SmallPtrSet<Instruction *, 16> Visited; 6780 6781 // Iterate over all the loops and sub-loops to drop SCEV information. 6782 while (!LoopWorklist.empty()) { 6783 auto *CurrL = LoopWorklist.pop_back_val(); 6784 6785 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6786 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6787 6788 // Drop information about predicated SCEV rewrites for this loop. 6789 for (auto I = PredicatedSCEVRewrites.begin(); 6790 I != PredicatedSCEVRewrites.end();) { 6791 std::pair<const SCEV *, const Loop *> Entry = I->first; 6792 if (Entry.second == CurrL) 6793 PredicatedSCEVRewrites.erase(I++); 6794 else 6795 ++I; 6796 } 6797 6798 auto LoopUsersItr = LoopUsers.find(CurrL); 6799 if (LoopUsersItr != LoopUsers.end()) { 6800 for (auto *S : LoopUsersItr->second) 6801 forgetMemoizedResults(S); 6802 LoopUsers.erase(LoopUsersItr); 6803 } 6804 6805 // Drop information about expressions based on loop-header PHIs. 6806 PushLoopPHIs(CurrL, Worklist); 6807 6808 while (!Worklist.empty()) { 6809 Instruction *I = Worklist.pop_back_val(); 6810 if (!Visited.insert(I).second) 6811 continue; 6812 6813 ValueExprMapType::iterator It = 6814 ValueExprMap.find_as(static_cast<Value *>(I)); 6815 if (It != ValueExprMap.end()) { 6816 eraseValueFromMap(It->first); 6817 forgetMemoizedResults(It->second); 6818 if (PHINode *PN = dyn_cast<PHINode>(I)) 6819 ConstantEvolutionLoopExitValue.erase(PN); 6820 } 6821 6822 PushDefUseChildren(I, Worklist); 6823 } 6824 6825 LoopPropertiesCache.erase(CurrL); 6826 // Forget all contained loops too, to avoid dangling entries in the 6827 // ValuesAtScopes map. 6828 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6829 } 6830 } 6831 6832 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6833 while (Loop *Parent = L->getParentLoop()) 6834 L = Parent; 6835 forgetLoop(L); 6836 } 6837 6838 void ScalarEvolution::forgetValue(Value *V) { 6839 Instruction *I = dyn_cast<Instruction>(V); 6840 if (!I) return; 6841 6842 // Drop information about expressions based on loop-header PHIs. 6843 SmallVector<Instruction *, 16> Worklist; 6844 Worklist.push_back(I); 6845 6846 SmallPtrSet<Instruction *, 8> Visited; 6847 while (!Worklist.empty()) { 6848 I = Worklist.pop_back_val(); 6849 if (!Visited.insert(I).second) 6850 continue; 6851 6852 ValueExprMapType::iterator It = 6853 ValueExprMap.find_as(static_cast<Value *>(I)); 6854 if (It != ValueExprMap.end()) { 6855 eraseValueFromMap(It->first); 6856 forgetMemoizedResults(It->second); 6857 if (PHINode *PN = dyn_cast<PHINode>(I)) 6858 ConstantEvolutionLoopExitValue.erase(PN); 6859 } 6860 6861 PushDefUseChildren(I, Worklist); 6862 } 6863 } 6864 6865 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 6866 LoopDispositions.clear(); 6867 } 6868 6869 /// Get the exact loop backedge taken count considering all loop exits. A 6870 /// computable result can only be returned for loops with all exiting blocks 6871 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6872 /// is never skipped. This is a valid assumption as long as the loop exits via 6873 /// that test. For precise results, it is the caller's responsibility to specify 6874 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6875 const SCEV * 6876 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6877 SCEVUnionPredicate *Preds) const { 6878 // If any exits were not computable, the loop is not computable. 6879 if (!isComplete() || ExitNotTaken.empty()) 6880 return SE->getCouldNotCompute(); 6881 6882 const BasicBlock *Latch = L->getLoopLatch(); 6883 // All exiting blocks we have collected must dominate the only backedge. 6884 if (!Latch) 6885 return SE->getCouldNotCompute(); 6886 6887 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6888 // count is simply a minimum out of all these calculated exit counts. 6889 SmallVector<const SCEV *, 2> Ops; 6890 for (auto &ENT : ExitNotTaken) { 6891 const SCEV *BECount = ENT.ExactNotTaken; 6892 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6893 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6894 "We should only have known counts for exiting blocks that dominate " 6895 "latch!"); 6896 6897 Ops.push_back(BECount); 6898 6899 if (Preds && !ENT.hasAlwaysTruePredicate()) 6900 Preds->add(ENT.Predicate.get()); 6901 6902 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6903 "Predicate should be always true!"); 6904 } 6905 6906 return SE->getUMinFromMismatchedTypes(Ops); 6907 } 6908 6909 /// Get the exact not taken count for this loop exit. 6910 const SCEV * 6911 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 6912 ScalarEvolution *SE) const { 6913 for (auto &ENT : ExitNotTaken) 6914 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6915 return ENT.ExactNotTaken; 6916 6917 return SE->getCouldNotCompute(); 6918 } 6919 6920 const SCEV * 6921 ScalarEvolution::BackedgeTakenInfo::getMax(const BasicBlock *ExitingBlock, 6922 ScalarEvolution *SE) const { 6923 for (auto &ENT : ExitNotTaken) 6924 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6925 return ENT.MaxNotTaken; 6926 6927 return SE->getCouldNotCompute(); 6928 } 6929 6930 /// getMax - Get the max backedge taken count for the loop. 6931 const SCEV * 6932 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6933 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6934 return !ENT.hasAlwaysTruePredicate(); 6935 }; 6936 6937 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6938 return SE->getCouldNotCompute(); 6939 6940 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6941 "No point in having a non-constant max backedge taken count!"); 6942 return getMax(); 6943 } 6944 6945 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6946 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6947 return !ENT.hasAlwaysTruePredicate(); 6948 }; 6949 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6950 } 6951 6952 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6953 ScalarEvolution *SE) const { 6954 if (getMax() && getMax() != SE->getCouldNotCompute() && 6955 SE->hasOperand(getMax(), S)) 6956 return true; 6957 6958 for (auto &ENT : ExitNotTaken) 6959 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6960 SE->hasOperand(ENT.ExactNotTaken, S)) 6961 return true; 6962 6963 return false; 6964 } 6965 6966 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6967 : ExactNotTaken(E), MaxNotTaken(E) { 6968 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6969 isa<SCEVConstant>(MaxNotTaken)) && 6970 "No point in having a non-constant max backedge taken count!"); 6971 } 6972 6973 ScalarEvolution::ExitLimit::ExitLimit( 6974 const SCEV *E, const SCEV *M, bool MaxOrZero, 6975 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6976 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6977 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6978 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6979 "Exact is not allowed to be less precise than Max"); 6980 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6981 isa<SCEVConstant>(MaxNotTaken)) && 6982 "No point in having a non-constant max backedge taken count!"); 6983 for (auto *PredSet : PredSetList) 6984 for (auto *P : *PredSet) 6985 addPredicate(P); 6986 } 6987 6988 ScalarEvolution::ExitLimit::ExitLimit( 6989 const SCEV *E, const SCEV *M, bool MaxOrZero, 6990 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6991 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6992 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6993 isa<SCEVConstant>(MaxNotTaken)) && 6994 "No point in having a non-constant max backedge taken count!"); 6995 } 6996 6997 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6998 bool MaxOrZero) 6999 : ExitLimit(E, M, MaxOrZero, None) { 7000 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7001 isa<SCEVConstant>(MaxNotTaken)) && 7002 "No point in having a non-constant max backedge taken count!"); 7003 } 7004 7005 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7006 /// computable exit into a persistent ExitNotTakenInfo array. 7007 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7008 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7009 ExitCounts, 7010 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7011 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7012 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7013 7014 ExitNotTaken.reserve(ExitCounts.size()); 7015 std::transform( 7016 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7017 [&](const EdgeExitInfo &EEI) { 7018 BasicBlock *ExitBB = EEI.first; 7019 const ExitLimit &EL = EEI.second; 7020 if (EL.Predicates.empty()) 7021 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7022 nullptr); 7023 7024 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7025 for (auto *Pred : EL.Predicates) 7026 Predicate->add(Pred); 7027 7028 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7029 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 7062 // We canonicalize untaken exits to br (constant), ignore them so that 7063 // proving an exit untaken doesn't negatively impact our ability to reason 7064 // about the loop as whole. 7065 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7066 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7067 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7068 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7069 continue; 7070 } 7071 7072 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7073 7074 assert((AllowPredicates || EL.Predicates.empty()) && 7075 "Predicated exit limit when predicates are not allowed!"); 7076 7077 // 1. For each exit that can be computed, add an entry to ExitCounts. 7078 // CouldComputeBECount is true only if all exits can be computed. 7079 if (EL.ExactNotTaken == getCouldNotCompute()) 7080 // We couldn't compute an exact value for this exit, so 7081 // we won't be able to compute an exact value for the loop. 7082 CouldComputeBECount = false; 7083 else 7084 ExitCounts.emplace_back(ExitBB, EL); 7085 7086 // 2. Derive the loop's MaxBECount from each exit's max number of 7087 // non-exiting iterations. Partition the loop exits into two kinds: 7088 // LoopMustExits and LoopMayExits. 7089 // 7090 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7091 // is a LoopMayExit. If any computable LoopMustExit is found, then 7092 // MaxBECount is the minimum EL.MaxNotTaken of computable 7093 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7094 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7095 // computable EL.MaxNotTaken. 7096 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7097 DT.dominates(ExitBB, Latch)) { 7098 if (!MustExitMaxBECount) { 7099 MustExitMaxBECount = EL.MaxNotTaken; 7100 MustExitMaxOrZero = EL.MaxOrZero; 7101 } else { 7102 MustExitMaxBECount = 7103 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7104 } 7105 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7106 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7107 MayExitMaxBECount = EL.MaxNotTaken; 7108 else { 7109 MayExitMaxBECount = 7110 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7111 } 7112 } 7113 } 7114 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7115 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7116 // The loop backedge will be taken the maximum or zero times if there's 7117 // a single exit that must be taken the maximum or zero times. 7118 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7119 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7120 MaxBECount, MaxOrZero); 7121 } 7122 7123 ScalarEvolution::ExitLimit 7124 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7125 bool AllowPredicates) { 7126 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7127 // If our exiting block does not dominate the latch, then its connection with 7128 // loop's exit limit may be far from trivial. 7129 const BasicBlock *Latch = L->getLoopLatch(); 7130 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7131 return getCouldNotCompute(); 7132 7133 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7134 Instruction *Term = ExitingBlock->getTerminator(); 7135 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7136 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7137 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7138 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7139 "It should have one successor in loop and one exit block!"); 7140 // Proceed to the next level to examine the exit condition expression. 7141 return computeExitLimitFromCond( 7142 L, BI->getCondition(), ExitIfTrue, 7143 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7144 } 7145 7146 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7147 // For switch, make sure that there is a single exit from the loop. 7148 BasicBlock *Exit = nullptr; 7149 for (auto *SBB : successors(ExitingBlock)) 7150 if (!L->contains(SBB)) { 7151 if (Exit) // Multiple exit successors. 7152 return getCouldNotCompute(); 7153 Exit = SBB; 7154 } 7155 assert(Exit && "Exiting block must have at least one exit"); 7156 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7157 /*ControlsExit=*/IsOnlyExit); 7158 } 7159 7160 return getCouldNotCompute(); 7161 } 7162 7163 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7164 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7165 bool ControlsExit, bool AllowPredicates) { 7166 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7167 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7168 ControlsExit, AllowPredicates); 7169 } 7170 7171 Optional<ScalarEvolution::ExitLimit> 7172 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7173 bool ExitIfTrue, bool ControlsExit, 7174 bool AllowPredicates) { 7175 (void)this->L; 7176 (void)this->ExitIfTrue; 7177 (void)this->AllowPredicates; 7178 7179 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7180 this->AllowPredicates == AllowPredicates && 7181 "Variance in assumed invariant key components!"); 7182 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7183 if (Itr == TripCountMap.end()) 7184 return None; 7185 return Itr->second; 7186 } 7187 7188 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7189 bool ExitIfTrue, 7190 bool ControlsExit, 7191 bool AllowPredicates, 7192 const ExitLimit &EL) { 7193 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7194 this->AllowPredicates == AllowPredicates && 7195 "Variance in assumed invariant key components!"); 7196 7197 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7198 assert(InsertResult.second && "Expected successful insertion!"); 7199 (void)InsertResult; 7200 (void)ExitIfTrue; 7201 } 7202 7203 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7204 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7205 bool ControlsExit, bool AllowPredicates) { 7206 7207 if (auto MaybeEL = 7208 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7209 return *MaybeEL; 7210 7211 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7212 ControlsExit, AllowPredicates); 7213 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7214 return EL; 7215 } 7216 7217 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7218 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7219 bool ControlsExit, bool AllowPredicates) { 7220 // Check if the controlling expression for this loop is an And or Or. 7221 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7222 if (BO->getOpcode() == Instruction::And) { 7223 // Recurse on the operands of the and. 7224 bool EitherMayExit = !ExitIfTrue; 7225 ExitLimit EL0 = computeExitLimitFromCondCached( 7226 Cache, L, BO->getOperand(0), ExitIfTrue, 7227 ControlsExit && !EitherMayExit, AllowPredicates); 7228 ExitLimit EL1 = computeExitLimitFromCondCached( 7229 Cache, L, BO->getOperand(1), ExitIfTrue, 7230 ControlsExit && !EitherMayExit, AllowPredicates); 7231 // Be robust against unsimplified IR for the form "and i1 X, true" 7232 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7233 return CI->isOne() ? EL0 : EL1; 7234 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7235 return CI->isOne() ? EL1 : EL0; 7236 const SCEV *BECount = getCouldNotCompute(); 7237 const SCEV *MaxBECount = getCouldNotCompute(); 7238 if (EitherMayExit) { 7239 // Both conditions must be true for the loop to continue executing. 7240 // Choose the less conservative count. 7241 if (EL0.ExactNotTaken == getCouldNotCompute() || 7242 EL1.ExactNotTaken == getCouldNotCompute()) 7243 BECount = getCouldNotCompute(); 7244 else 7245 BECount = 7246 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7247 if (EL0.MaxNotTaken == getCouldNotCompute()) 7248 MaxBECount = EL1.MaxNotTaken; 7249 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7250 MaxBECount = EL0.MaxNotTaken; 7251 else 7252 MaxBECount = 7253 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7254 } else { 7255 // Both conditions must be true at the same time for the loop to exit. 7256 // For now, be conservative. 7257 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7258 MaxBECount = EL0.MaxNotTaken; 7259 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7260 BECount = EL0.ExactNotTaken; 7261 } 7262 7263 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7264 // to be more aggressive when computing BECount than when computing 7265 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7266 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7267 // to not. 7268 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7269 !isa<SCEVCouldNotCompute>(BECount)) 7270 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7271 7272 return ExitLimit(BECount, MaxBECount, false, 7273 {&EL0.Predicates, &EL1.Predicates}); 7274 } 7275 if (BO->getOpcode() == Instruction::Or) { 7276 // Recurse on the operands of the or. 7277 bool EitherMayExit = ExitIfTrue; 7278 ExitLimit EL0 = computeExitLimitFromCondCached( 7279 Cache, L, BO->getOperand(0), ExitIfTrue, 7280 ControlsExit && !EitherMayExit, AllowPredicates); 7281 ExitLimit EL1 = computeExitLimitFromCondCached( 7282 Cache, L, BO->getOperand(1), ExitIfTrue, 7283 ControlsExit && !EitherMayExit, AllowPredicates); 7284 // Be robust against unsimplified IR for the form "or i1 X, true" 7285 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7286 return CI->isZero() ? EL0 : EL1; 7287 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7288 return CI->isZero() ? EL1 : EL0; 7289 const SCEV *BECount = getCouldNotCompute(); 7290 const SCEV *MaxBECount = getCouldNotCompute(); 7291 if (EitherMayExit) { 7292 // Both conditions must be false for the loop to continue executing. 7293 // Choose the less conservative count. 7294 if (EL0.ExactNotTaken == getCouldNotCompute() || 7295 EL1.ExactNotTaken == getCouldNotCompute()) 7296 BECount = getCouldNotCompute(); 7297 else 7298 BECount = 7299 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7300 if (EL0.MaxNotTaken == getCouldNotCompute()) 7301 MaxBECount = EL1.MaxNotTaken; 7302 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7303 MaxBECount = EL0.MaxNotTaken; 7304 else 7305 MaxBECount = 7306 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7307 } else { 7308 // Both conditions must be false at the same time for the loop to exit. 7309 // For now, be conservative. 7310 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7311 MaxBECount = EL0.MaxNotTaken; 7312 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7313 BECount = EL0.ExactNotTaken; 7314 } 7315 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7316 // to be more aggressive when computing BECount than when computing 7317 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7318 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7319 // to not. 7320 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7321 !isa<SCEVCouldNotCompute>(BECount)) 7322 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7323 7324 return ExitLimit(BECount, MaxBECount, false, 7325 {&EL0.Predicates, &EL1.Predicates}); 7326 } 7327 } 7328 7329 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7330 // Proceed to the next level to examine the icmp. 7331 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7332 ExitLimit EL = 7333 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7334 if (EL.hasFullInfo() || !AllowPredicates) 7335 return EL; 7336 7337 // Try again, but use SCEV predicates this time. 7338 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7339 /*AllowPredicates=*/true); 7340 } 7341 7342 // Check for a constant condition. These are normally stripped out by 7343 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7344 // preserve the CFG and is temporarily leaving constant conditions 7345 // in place. 7346 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7347 if (ExitIfTrue == !CI->getZExtValue()) 7348 // The backedge is always taken. 7349 return getCouldNotCompute(); 7350 else 7351 // The backedge is never taken. 7352 return getZero(CI->getType()); 7353 } 7354 7355 // If it's not an integer or pointer comparison then compute it the hard way. 7356 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7357 } 7358 7359 ScalarEvolution::ExitLimit 7360 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7361 ICmpInst *ExitCond, 7362 bool ExitIfTrue, 7363 bool ControlsExit, 7364 bool AllowPredicates) { 7365 // If the condition was exit on true, convert the condition to exit on false 7366 ICmpInst::Predicate Pred; 7367 if (!ExitIfTrue) 7368 Pred = ExitCond->getPredicate(); 7369 else 7370 Pred = ExitCond->getInversePredicate(); 7371 const ICmpInst::Predicate OriginalPred = Pred; 7372 7373 // Handle common loops like: for (X = "string"; *X; ++X) 7374 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7375 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7376 ExitLimit ItCnt = 7377 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7378 if (ItCnt.hasAnyInfo()) 7379 return ItCnt; 7380 } 7381 7382 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7383 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7384 7385 // Try to evaluate any dependencies out of the loop. 7386 LHS = getSCEVAtScope(LHS, L); 7387 RHS = getSCEVAtScope(RHS, L); 7388 7389 // At this point, we would like to compute how many iterations of the 7390 // loop the predicate will return true for these inputs. 7391 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7392 // If there is a loop-invariant, force it into the RHS. 7393 std::swap(LHS, RHS); 7394 Pred = ICmpInst::getSwappedPredicate(Pred); 7395 } 7396 7397 // Simplify the operands before analyzing them. 7398 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7399 7400 // If we have a comparison of a chrec against a constant, try to use value 7401 // ranges to answer this query. 7402 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7403 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7404 if (AddRec->getLoop() == L) { 7405 // Form the constant range. 7406 ConstantRange CompRange = 7407 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7408 7409 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7410 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7411 } 7412 7413 switch (Pred) { 7414 case ICmpInst::ICMP_NE: { // while (X != Y) 7415 // Convert to: while (X-Y != 0) 7416 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7417 AllowPredicates); 7418 if (EL.hasAnyInfo()) return EL; 7419 break; 7420 } 7421 case ICmpInst::ICMP_EQ: { // while (X == Y) 7422 // Convert to: while (X-Y == 0) 7423 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7424 if (EL.hasAnyInfo()) return EL; 7425 break; 7426 } 7427 case ICmpInst::ICMP_SLT: 7428 case ICmpInst::ICMP_ULT: { // while (X < Y) 7429 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7430 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7431 AllowPredicates); 7432 if (EL.hasAnyInfo()) return EL; 7433 break; 7434 } 7435 case ICmpInst::ICMP_SGT: 7436 case ICmpInst::ICMP_UGT: { // while (X > Y) 7437 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7438 ExitLimit EL = 7439 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7440 AllowPredicates); 7441 if (EL.hasAnyInfo()) return EL; 7442 break; 7443 } 7444 default: 7445 break; 7446 } 7447 7448 auto *ExhaustiveCount = 7449 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7450 7451 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7452 return ExhaustiveCount; 7453 7454 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7455 ExitCond->getOperand(1), L, OriginalPred); 7456 } 7457 7458 ScalarEvolution::ExitLimit 7459 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7460 SwitchInst *Switch, 7461 BasicBlock *ExitingBlock, 7462 bool ControlsExit) { 7463 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7464 7465 // Give up if the exit is the default dest of a switch. 7466 if (Switch->getDefaultDest() == ExitingBlock) 7467 return getCouldNotCompute(); 7468 7469 assert(L->contains(Switch->getDefaultDest()) && 7470 "Default case must not exit the loop!"); 7471 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7472 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7473 7474 // while (X != Y) --> while (X-Y != 0) 7475 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7476 if (EL.hasAnyInfo()) 7477 return EL; 7478 7479 return getCouldNotCompute(); 7480 } 7481 7482 static ConstantInt * 7483 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7484 ScalarEvolution &SE) { 7485 const SCEV *InVal = SE.getConstant(C); 7486 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7487 assert(isa<SCEVConstant>(Val) && 7488 "Evaluation of SCEV at constant didn't fold correctly?"); 7489 return cast<SCEVConstant>(Val)->getValue(); 7490 } 7491 7492 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7493 /// compute the backedge execution count. 7494 ScalarEvolution::ExitLimit 7495 ScalarEvolution::computeLoadConstantCompareExitLimit( 7496 LoadInst *LI, 7497 Constant *RHS, 7498 const Loop *L, 7499 ICmpInst::Predicate predicate) { 7500 if (LI->isVolatile()) return getCouldNotCompute(); 7501 7502 // Check to see if the loaded pointer is a getelementptr of a global. 7503 // TODO: Use SCEV instead of manually grubbing with GEPs. 7504 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7505 if (!GEP) return getCouldNotCompute(); 7506 7507 // Make sure that it is really a constant global we are gepping, with an 7508 // initializer, and make sure the first IDX is really 0. 7509 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7510 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7511 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7512 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7513 return getCouldNotCompute(); 7514 7515 // Okay, we allow one non-constant index into the GEP instruction. 7516 Value *VarIdx = nullptr; 7517 std::vector<Constant*> Indexes; 7518 unsigned VarIdxNum = 0; 7519 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7520 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7521 Indexes.push_back(CI); 7522 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7523 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7524 VarIdx = GEP->getOperand(i); 7525 VarIdxNum = i-2; 7526 Indexes.push_back(nullptr); 7527 } 7528 7529 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7530 if (!VarIdx) 7531 return getCouldNotCompute(); 7532 7533 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7534 // Check to see if X is a loop variant variable value now. 7535 const SCEV *Idx = getSCEV(VarIdx); 7536 Idx = getSCEVAtScope(Idx, L); 7537 7538 // We can only recognize very limited forms of loop index expressions, in 7539 // particular, only affine AddRec's like {C1,+,C2}. 7540 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7541 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7542 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7543 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7544 return getCouldNotCompute(); 7545 7546 unsigned MaxSteps = MaxBruteForceIterations; 7547 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7548 ConstantInt *ItCst = ConstantInt::get( 7549 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7550 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7551 7552 // Form the GEP offset. 7553 Indexes[VarIdxNum] = Val; 7554 7555 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7556 Indexes); 7557 if (!Result) break; // Cannot compute! 7558 7559 // Evaluate the condition for this iteration. 7560 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7561 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7562 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7563 ++NumArrayLenItCounts; 7564 return getConstant(ItCst); // Found terminating iteration! 7565 } 7566 } 7567 return getCouldNotCompute(); 7568 } 7569 7570 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7571 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7572 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7573 if (!RHS) 7574 return getCouldNotCompute(); 7575 7576 const BasicBlock *Latch = L->getLoopLatch(); 7577 if (!Latch) 7578 return getCouldNotCompute(); 7579 7580 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7581 if (!Predecessor) 7582 return getCouldNotCompute(); 7583 7584 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7585 // Return LHS in OutLHS and shift_opt in OutOpCode. 7586 auto MatchPositiveShift = 7587 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7588 7589 using namespace PatternMatch; 7590 7591 ConstantInt *ShiftAmt; 7592 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7593 OutOpCode = Instruction::LShr; 7594 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7595 OutOpCode = Instruction::AShr; 7596 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7597 OutOpCode = Instruction::Shl; 7598 else 7599 return false; 7600 7601 return ShiftAmt->getValue().isStrictlyPositive(); 7602 }; 7603 7604 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7605 // 7606 // loop: 7607 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7608 // %iv.shifted = lshr i32 %iv, <positive constant> 7609 // 7610 // Return true on a successful match. Return the corresponding PHI node (%iv 7611 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7612 auto MatchShiftRecurrence = 7613 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7614 Optional<Instruction::BinaryOps> PostShiftOpCode; 7615 7616 { 7617 Instruction::BinaryOps OpC; 7618 Value *V; 7619 7620 // If we encounter a shift instruction, "peel off" the shift operation, 7621 // and remember that we did so. Later when we inspect %iv's backedge 7622 // value, we will make sure that the backedge value uses the same 7623 // operation. 7624 // 7625 // Note: the peeled shift operation does not have to be the same 7626 // instruction as the one feeding into the PHI's backedge value. We only 7627 // really care about it being the same *kind* of shift instruction -- 7628 // that's all that is required for our later inferences to hold. 7629 if (MatchPositiveShift(LHS, V, OpC)) { 7630 PostShiftOpCode = OpC; 7631 LHS = V; 7632 } 7633 } 7634 7635 PNOut = dyn_cast<PHINode>(LHS); 7636 if (!PNOut || PNOut->getParent() != L->getHeader()) 7637 return false; 7638 7639 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7640 Value *OpLHS; 7641 7642 return 7643 // The backedge value for the PHI node must be a shift by a positive 7644 // amount 7645 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7646 7647 // of the PHI node itself 7648 OpLHS == PNOut && 7649 7650 // and the kind of shift should be match the kind of shift we peeled 7651 // off, if any. 7652 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7653 }; 7654 7655 PHINode *PN; 7656 Instruction::BinaryOps OpCode; 7657 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7658 return getCouldNotCompute(); 7659 7660 const DataLayout &DL = getDataLayout(); 7661 7662 // The key rationale for this optimization is that for some kinds of shift 7663 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7664 // within a finite number of iterations. If the condition guarding the 7665 // backedge (in the sense that the backedge is taken if the condition is true) 7666 // is false for the value the shift recurrence stabilizes to, then we know 7667 // that the backedge is taken only a finite number of times. 7668 7669 ConstantInt *StableValue = nullptr; 7670 switch (OpCode) { 7671 default: 7672 llvm_unreachable("Impossible case!"); 7673 7674 case Instruction::AShr: { 7675 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7676 // bitwidth(K) iterations. 7677 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7678 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7679 Predecessor->getTerminator(), &DT); 7680 auto *Ty = cast<IntegerType>(RHS->getType()); 7681 if (Known.isNonNegative()) 7682 StableValue = ConstantInt::get(Ty, 0); 7683 else if (Known.isNegative()) 7684 StableValue = ConstantInt::get(Ty, -1, true); 7685 else 7686 return getCouldNotCompute(); 7687 7688 break; 7689 } 7690 case Instruction::LShr: 7691 case Instruction::Shl: 7692 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7693 // stabilize to 0 in at most bitwidth(K) iterations. 7694 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7695 break; 7696 } 7697 7698 auto *Result = 7699 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7700 assert(Result->getType()->isIntegerTy(1) && 7701 "Otherwise cannot be an operand to a branch instruction"); 7702 7703 if (Result->isZeroValue()) { 7704 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7705 const SCEV *UpperBound = 7706 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7707 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7708 } 7709 7710 return getCouldNotCompute(); 7711 } 7712 7713 /// Return true if we can constant fold an instruction of the specified type, 7714 /// assuming that all operands were constants. 7715 static bool CanConstantFold(const Instruction *I) { 7716 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7717 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7718 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7719 return true; 7720 7721 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7722 if (const Function *F = CI->getCalledFunction()) 7723 return canConstantFoldCallTo(CI, F); 7724 return false; 7725 } 7726 7727 /// Determine whether this instruction can constant evolve within this loop 7728 /// assuming its operands can all constant evolve. 7729 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7730 // An instruction outside of the loop can't be derived from a loop PHI. 7731 if (!L->contains(I)) return false; 7732 7733 if (isa<PHINode>(I)) { 7734 // We don't currently keep track of the control flow needed to evaluate 7735 // PHIs, so we cannot handle PHIs inside of loops. 7736 return L->getHeader() == I->getParent(); 7737 } 7738 7739 // If we won't be able to constant fold this expression even if the operands 7740 // are constants, bail early. 7741 return CanConstantFold(I); 7742 } 7743 7744 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7745 /// recursing through each instruction operand until reaching a loop header phi. 7746 static PHINode * 7747 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7748 DenseMap<Instruction *, PHINode *> &PHIMap, 7749 unsigned Depth) { 7750 if (Depth > MaxConstantEvolvingDepth) 7751 return nullptr; 7752 7753 // Otherwise, we can evaluate this instruction if all of its operands are 7754 // constant or derived from a PHI node themselves. 7755 PHINode *PHI = nullptr; 7756 for (Value *Op : UseInst->operands()) { 7757 if (isa<Constant>(Op)) continue; 7758 7759 Instruction *OpInst = dyn_cast<Instruction>(Op); 7760 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7761 7762 PHINode *P = dyn_cast<PHINode>(OpInst); 7763 if (!P) 7764 // If this operand is already visited, reuse the prior result. 7765 // We may have P != PHI if this is the deepest point at which the 7766 // inconsistent paths meet. 7767 P = PHIMap.lookup(OpInst); 7768 if (!P) { 7769 // Recurse and memoize the results, whether a phi is found or not. 7770 // This recursive call invalidates pointers into PHIMap. 7771 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7772 PHIMap[OpInst] = P; 7773 } 7774 if (!P) 7775 return nullptr; // Not evolving from PHI 7776 if (PHI && PHI != P) 7777 return nullptr; // Evolving from multiple different PHIs. 7778 PHI = P; 7779 } 7780 // This is a expression evolving from a constant PHI! 7781 return PHI; 7782 } 7783 7784 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7785 /// in the loop that V is derived from. We allow arbitrary operations along the 7786 /// way, but the operands of an operation must either be constants or a value 7787 /// derived from a constant PHI. If this expression does not fit with these 7788 /// constraints, return null. 7789 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7790 Instruction *I = dyn_cast<Instruction>(V); 7791 if (!I || !canConstantEvolve(I, L)) return nullptr; 7792 7793 if (PHINode *PN = dyn_cast<PHINode>(I)) 7794 return PN; 7795 7796 // Record non-constant instructions contained by the loop. 7797 DenseMap<Instruction *, PHINode *> PHIMap; 7798 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7799 } 7800 7801 /// EvaluateExpression - Given an expression that passes the 7802 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7803 /// in the loop has the value PHIVal. If we can't fold this expression for some 7804 /// reason, return null. 7805 static Constant *EvaluateExpression(Value *V, const Loop *L, 7806 DenseMap<Instruction *, Constant *> &Vals, 7807 const DataLayout &DL, 7808 const TargetLibraryInfo *TLI) { 7809 // Convenient constant check, but redundant for recursive calls. 7810 if (Constant *C = dyn_cast<Constant>(V)) return C; 7811 Instruction *I = dyn_cast<Instruction>(V); 7812 if (!I) return nullptr; 7813 7814 if (Constant *C = Vals.lookup(I)) return C; 7815 7816 // An instruction inside the loop depends on a value outside the loop that we 7817 // weren't given a mapping for, or a value such as a call inside the loop. 7818 if (!canConstantEvolve(I, L)) return nullptr; 7819 7820 // An unmapped PHI can be due to a branch or another loop inside this loop, 7821 // or due to this not being the initial iteration through a loop where we 7822 // couldn't compute the evolution of this particular PHI last time. 7823 if (isa<PHINode>(I)) return nullptr; 7824 7825 std::vector<Constant*> Operands(I->getNumOperands()); 7826 7827 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7828 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7829 if (!Operand) { 7830 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7831 if (!Operands[i]) return nullptr; 7832 continue; 7833 } 7834 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7835 Vals[Operand] = C; 7836 if (!C) return nullptr; 7837 Operands[i] = C; 7838 } 7839 7840 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7841 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7842 Operands[1], DL, TLI); 7843 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7844 if (!LI->isVolatile()) 7845 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7846 } 7847 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7848 } 7849 7850 7851 // If every incoming value to PN except the one for BB is a specific Constant, 7852 // return that, else return nullptr. 7853 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7854 Constant *IncomingVal = nullptr; 7855 7856 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7857 if (PN->getIncomingBlock(i) == BB) 7858 continue; 7859 7860 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7861 if (!CurrentVal) 7862 return nullptr; 7863 7864 if (IncomingVal != CurrentVal) { 7865 if (IncomingVal) 7866 return nullptr; 7867 IncomingVal = CurrentVal; 7868 } 7869 } 7870 7871 return IncomingVal; 7872 } 7873 7874 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7875 /// in the header of its containing loop, we know the loop executes a 7876 /// constant number of times, and the PHI node is just a recurrence 7877 /// involving constants, fold it. 7878 Constant * 7879 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7880 const APInt &BEs, 7881 const Loop *L) { 7882 auto I = ConstantEvolutionLoopExitValue.find(PN); 7883 if (I != ConstantEvolutionLoopExitValue.end()) 7884 return I->second; 7885 7886 if (BEs.ugt(MaxBruteForceIterations)) 7887 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7888 7889 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7890 7891 DenseMap<Instruction *, Constant *> CurrentIterVals; 7892 BasicBlock *Header = L->getHeader(); 7893 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7894 7895 BasicBlock *Latch = L->getLoopLatch(); 7896 if (!Latch) 7897 return nullptr; 7898 7899 for (PHINode &PHI : Header->phis()) { 7900 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7901 CurrentIterVals[&PHI] = StartCST; 7902 } 7903 if (!CurrentIterVals.count(PN)) 7904 return RetVal = nullptr; 7905 7906 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7907 7908 // Execute the loop symbolically to determine the exit value. 7909 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7910 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7911 7912 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7913 unsigned IterationNum = 0; 7914 const DataLayout &DL = getDataLayout(); 7915 for (; ; ++IterationNum) { 7916 if (IterationNum == NumIterations) 7917 return RetVal = CurrentIterVals[PN]; // Got exit value! 7918 7919 // Compute the value of the PHIs for the next iteration. 7920 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7921 DenseMap<Instruction *, Constant *> NextIterVals; 7922 Constant *NextPHI = 7923 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7924 if (!NextPHI) 7925 return nullptr; // Couldn't evaluate! 7926 NextIterVals[PN] = NextPHI; 7927 7928 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7929 7930 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7931 // cease to be able to evaluate one of them or if they stop evolving, 7932 // because that doesn't necessarily prevent us from computing PN. 7933 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7934 for (const auto &I : CurrentIterVals) { 7935 PHINode *PHI = dyn_cast<PHINode>(I.first); 7936 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7937 PHIsToCompute.emplace_back(PHI, I.second); 7938 } 7939 // We use two distinct loops because EvaluateExpression may invalidate any 7940 // iterators into CurrentIterVals. 7941 for (const auto &I : PHIsToCompute) { 7942 PHINode *PHI = I.first; 7943 Constant *&NextPHI = NextIterVals[PHI]; 7944 if (!NextPHI) { // Not already computed. 7945 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7946 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7947 } 7948 if (NextPHI != I.second) 7949 StoppedEvolving = false; 7950 } 7951 7952 // If all entries in CurrentIterVals == NextIterVals then we can stop 7953 // iterating, the loop can't continue to change. 7954 if (StoppedEvolving) 7955 return RetVal = CurrentIterVals[PN]; 7956 7957 CurrentIterVals.swap(NextIterVals); 7958 } 7959 } 7960 7961 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7962 Value *Cond, 7963 bool ExitWhen) { 7964 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7965 if (!PN) return getCouldNotCompute(); 7966 7967 // If the loop is canonicalized, the PHI will have exactly two entries. 7968 // That's the only form we support here. 7969 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7970 7971 DenseMap<Instruction *, Constant *> CurrentIterVals; 7972 BasicBlock *Header = L->getHeader(); 7973 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7974 7975 BasicBlock *Latch = L->getLoopLatch(); 7976 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7977 7978 for (PHINode &PHI : Header->phis()) { 7979 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7980 CurrentIterVals[&PHI] = StartCST; 7981 } 7982 if (!CurrentIterVals.count(PN)) 7983 return getCouldNotCompute(); 7984 7985 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7986 // the loop symbolically to determine when the condition gets a value of 7987 // "ExitWhen". 7988 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7989 const DataLayout &DL = getDataLayout(); 7990 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7991 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7992 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7993 7994 // Couldn't symbolically evaluate. 7995 if (!CondVal) return getCouldNotCompute(); 7996 7997 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7998 ++NumBruteForceTripCountsComputed; 7999 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8000 } 8001 8002 // Update all the PHI nodes for the next iteration. 8003 DenseMap<Instruction *, Constant *> NextIterVals; 8004 8005 // Create a list of which PHIs we need to compute. We want to do this before 8006 // calling EvaluateExpression on them because that may invalidate iterators 8007 // into CurrentIterVals. 8008 SmallVector<PHINode *, 8> PHIsToCompute; 8009 for (const auto &I : CurrentIterVals) { 8010 PHINode *PHI = dyn_cast<PHINode>(I.first); 8011 if (!PHI || PHI->getParent() != Header) continue; 8012 PHIsToCompute.push_back(PHI); 8013 } 8014 for (PHINode *PHI : PHIsToCompute) { 8015 Constant *&NextPHI = NextIterVals[PHI]; 8016 if (NextPHI) continue; // Already computed! 8017 8018 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8019 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8020 } 8021 CurrentIterVals.swap(NextIterVals); 8022 } 8023 8024 // Too many iterations were needed to evaluate. 8025 return getCouldNotCompute(); 8026 } 8027 8028 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8029 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8030 ValuesAtScopes[V]; 8031 // Check to see if we've folded this expression at this loop before. 8032 for (auto &LS : Values) 8033 if (LS.first == L) 8034 return LS.second ? LS.second : V; 8035 8036 Values.emplace_back(L, nullptr); 8037 8038 // Otherwise compute it. 8039 const SCEV *C = computeSCEVAtScope(V, L); 8040 for (auto &LS : reverse(ValuesAtScopes[V])) 8041 if (LS.first == L) { 8042 LS.second = C; 8043 break; 8044 } 8045 return C; 8046 } 8047 8048 /// This builds up a Constant using the ConstantExpr interface. That way, we 8049 /// will return Constants for objects which aren't represented by a 8050 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8051 /// Returns NULL if the SCEV isn't representable as a Constant. 8052 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8053 switch (V->getSCEVType()) { 8054 case scCouldNotCompute: 8055 case scAddRecExpr: 8056 return nullptr; 8057 case scConstant: 8058 return cast<SCEVConstant>(V)->getValue(); 8059 case scUnknown: 8060 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8061 case scSignExtend: { 8062 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8063 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8064 return ConstantExpr::getSExt(CastOp, SS->getType()); 8065 return nullptr; 8066 } 8067 case scZeroExtend: { 8068 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8069 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8070 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8071 return nullptr; 8072 } 8073 case scTruncate: { 8074 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8075 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8076 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8077 return nullptr; 8078 } 8079 case scAddExpr: { 8080 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8081 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8082 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8083 unsigned AS = PTy->getAddressSpace(); 8084 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8085 C = ConstantExpr::getBitCast(C, DestPtrTy); 8086 } 8087 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8088 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8089 if (!C2) 8090 return nullptr; 8091 8092 // First pointer! 8093 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8094 unsigned AS = C2->getType()->getPointerAddressSpace(); 8095 std::swap(C, C2); 8096 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8097 // The offsets have been converted to bytes. We can add bytes to an 8098 // i8* by GEP with the byte count in the first index. 8099 C = ConstantExpr::getBitCast(C, DestPtrTy); 8100 } 8101 8102 // Don't bother trying to sum two pointers. We probably can't 8103 // statically compute a load that results from it anyway. 8104 if (C2->getType()->isPointerTy()) 8105 return nullptr; 8106 8107 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8108 if (PTy->getElementType()->isStructTy()) 8109 C2 = ConstantExpr::getIntegerCast( 8110 C2, Type::getInt32Ty(C->getContext()), true); 8111 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8112 } else 8113 C = ConstantExpr::getAdd(C, C2); 8114 } 8115 return C; 8116 } 8117 return nullptr; 8118 } 8119 case scMulExpr: { 8120 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8121 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8122 // Don't bother with pointers at all. 8123 if (C->getType()->isPointerTy()) 8124 return nullptr; 8125 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8126 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8127 if (!C2 || C2->getType()->isPointerTy()) 8128 return nullptr; 8129 C = ConstantExpr::getMul(C, C2); 8130 } 8131 return C; 8132 } 8133 return nullptr; 8134 } 8135 case scUDivExpr: { 8136 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8137 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8138 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8139 if (LHS->getType() == RHS->getType()) 8140 return ConstantExpr::getUDiv(LHS, RHS); 8141 return nullptr; 8142 } 8143 case scSMaxExpr: 8144 case scUMaxExpr: 8145 case scSMinExpr: 8146 case scUMinExpr: 8147 return nullptr; // TODO: smax, umax, smin, umax. 8148 } 8149 llvm_unreachable("Unknown SCEV kind!"); 8150 } 8151 8152 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8153 if (isa<SCEVConstant>(V)) return V; 8154 8155 // If this instruction is evolved from a constant-evolving PHI, compute the 8156 // exit value from the loop without using SCEVs. 8157 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8158 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8159 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8160 const Loop *CurrLoop = this->LI[I->getParent()]; 8161 // Looking for loop exit value. 8162 if (CurrLoop && CurrLoop->getParentLoop() == L && 8163 PN->getParent() == CurrLoop->getHeader()) { 8164 // Okay, there is no closed form solution for the PHI node. Check 8165 // to see if the loop that contains it has a known backedge-taken 8166 // count. If so, we may be able to force computation of the exit 8167 // value. 8168 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8169 // This trivial case can show up in some degenerate cases where 8170 // the incoming IR has not yet been fully simplified. 8171 if (BackedgeTakenCount->isZero()) { 8172 Value *InitValue = nullptr; 8173 bool MultipleInitValues = false; 8174 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8175 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8176 if (!InitValue) 8177 InitValue = PN->getIncomingValue(i); 8178 else if (InitValue != PN->getIncomingValue(i)) { 8179 MultipleInitValues = true; 8180 break; 8181 } 8182 } 8183 } 8184 if (!MultipleInitValues && InitValue) 8185 return getSCEV(InitValue); 8186 } 8187 // Do we have a loop invariant value flowing around the backedge 8188 // for a loop which must execute the backedge? 8189 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8190 isKnownPositive(BackedgeTakenCount) && 8191 PN->getNumIncomingValues() == 2) { 8192 8193 unsigned InLoopPred = 8194 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8195 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8196 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8197 return getSCEV(BackedgeVal); 8198 } 8199 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8200 // Okay, we know how many times the containing loop executes. If 8201 // this is a constant evolving PHI node, get the final value at 8202 // the specified iteration number. 8203 Constant *RV = getConstantEvolutionLoopExitValue( 8204 PN, BTCC->getAPInt(), CurrLoop); 8205 if (RV) return getSCEV(RV); 8206 } 8207 } 8208 8209 // If there is a single-input Phi, evaluate it at our scope. If we can 8210 // prove that this replacement does not break LCSSA form, use new value. 8211 if (PN->getNumOperands() == 1) { 8212 const SCEV *Input = getSCEV(PN->getOperand(0)); 8213 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8214 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8215 // for the simplest case just support constants. 8216 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8217 } 8218 } 8219 8220 // Okay, this is an expression that we cannot symbolically evaluate 8221 // into a SCEV. Check to see if it's possible to symbolically evaluate 8222 // the arguments into constants, and if so, try to constant propagate the 8223 // result. This is particularly useful for computing loop exit values. 8224 if (CanConstantFold(I)) { 8225 SmallVector<Constant *, 4> Operands; 8226 bool MadeImprovement = false; 8227 for (Value *Op : I->operands()) { 8228 if (Constant *C = dyn_cast<Constant>(Op)) { 8229 Operands.push_back(C); 8230 continue; 8231 } 8232 8233 // If any of the operands is non-constant and if they are 8234 // non-integer and non-pointer, don't even try to analyze them 8235 // with scev techniques. 8236 if (!isSCEVable(Op->getType())) 8237 return V; 8238 8239 const SCEV *OrigV = getSCEV(Op); 8240 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8241 MadeImprovement |= OrigV != OpV; 8242 8243 Constant *C = BuildConstantFromSCEV(OpV); 8244 if (!C) return V; 8245 if (C->getType() != Op->getType()) 8246 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8247 Op->getType(), 8248 false), 8249 C, Op->getType()); 8250 Operands.push_back(C); 8251 } 8252 8253 // Check to see if getSCEVAtScope actually made an improvement. 8254 if (MadeImprovement) { 8255 Constant *C = nullptr; 8256 const DataLayout &DL = getDataLayout(); 8257 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8258 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8259 Operands[1], DL, &TLI); 8260 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8261 if (!Load->isVolatile()) 8262 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8263 DL); 8264 } else 8265 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8266 if (!C) return V; 8267 return getSCEV(C); 8268 } 8269 } 8270 } 8271 8272 // This is some other type of SCEVUnknown, just return it. 8273 return V; 8274 } 8275 8276 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8277 // Avoid performing the look-up in the common case where the specified 8278 // expression has no loop-variant portions. 8279 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8280 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8281 if (OpAtScope != Comm->getOperand(i)) { 8282 // Okay, at least one of these operands is loop variant but might be 8283 // foldable. Build a new instance of the folded commutative expression. 8284 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8285 Comm->op_begin()+i); 8286 NewOps.push_back(OpAtScope); 8287 8288 for (++i; i != e; ++i) { 8289 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8290 NewOps.push_back(OpAtScope); 8291 } 8292 if (isa<SCEVAddExpr>(Comm)) 8293 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8294 if (isa<SCEVMulExpr>(Comm)) 8295 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8296 if (isa<SCEVMinMaxExpr>(Comm)) 8297 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8298 llvm_unreachable("Unknown commutative SCEV type!"); 8299 } 8300 } 8301 // If we got here, all operands are loop invariant. 8302 return Comm; 8303 } 8304 8305 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8306 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8307 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8308 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8309 return Div; // must be loop invariant 8310 return getUDivExpr(LHS, RHS); 8311 } 8312 8313 // If this is a loop recurrence for a loop that does not contain L, then we 8314 // are dealing with the final value computed by the loop. 8315 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8316 // First, attempt to evaluate each operand. 8317 // Avoid performing the look-up in the common case where the specified 8318 // expression has no loop-variant portions. 8319 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8320 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8321 if (OpAtScope == AddRec->getOperand(i)) 8322 continue; 8323 8324 // Okay, at least one of these operands is loop variant but might be 8325 // foldable. Build a new instance of the folded commutative expression. 8326 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8327 AddRec->op_begin()+i); 8328 NewOps.push_back(OpAtScope); 8329 for (++i; i != e; ++i) 8330 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8331 8332 const SCEV *FoldedRec = 8333 getAddRecExpr(NewOps, AddRec->getLoop(), 8334 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8335 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8336 // The addrec may be folded to a nonrecurrence, for example, if the 8337 // induction variable is multiplied by zero after constant folding. Go 8338 // ahead and return the folded value. 8339 if (!AddRec) 8340 return FoldedRec; 8341 break; 8342 } 8343 8344 // If the scope is outside the addrec's loop, evaluate it by using the 8345 // loop exit value of the addrec. 8346 if (!AddRec->getLoop()->contains(L)) { 8347 // To evaluate this recurrence, we need to know how many times the AddRec 8348 // loop iterates. Compute this now. 8349 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8350 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8351 8352 // Then, evaluate the AddRec. 8353 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8354 } 8355 8356 return AddRec; 8357 } 8358 8359 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8360 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8361 if (Op == Cast->getOperand()) 8362 return Cast; // must be loop invariant 8363 return getZeroExtendExpr(Op, Cast->getType()); 8364 } 8365 8366 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8367 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8368 if (Op == Cast->getOperand()) 8369 return Cast; // must be loop invariant 8370 return getSignExtendExpr(Op, Cast->getType()); 8371 } 8372 8373 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8374 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8375 if (Op == Cast->getOperand()) 8376 return Cast; // must be loop invariant 8377 return getTruncateExpr(Op, Cast->getType()); 8378 } 8379 8380 llvm_unreachable("Unknown SCEV type!"); 8381 } 8382 8383 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8384 return getSCEVAtScope(getSCEV(V), L); 8385 } 8386 8387 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8388 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8389 return stripInjectiveFunctions(ZExt->getOperand()); 8390 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8391 return stripInjectiveFunctions(SExt->getOperand()); 8392 return S; 8393 } 8394 8395 /// Finds the minimum unsigned root of the following equation: 8396 /// 8397 /// A * X = B (mod N) 8398 /// 8399 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8400 /// A and B isn't important. 8401 /// 8402 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8403 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8404 ScalarEvolution &SE) { 8405 uint32_t BW = A.getBitWidth(); 8406 assert(BW == SE.getTypeSizeInBits(B->getType())); 8407 assert(A != 0 && "A must be non-zero."); 8408 8409 // 1. D = gcd(A, N) 8410 // 8411 // The gcd of A and N may have only one prime factor: 2. The number of 8412 // trailing zeros in A is its multiplicity 8413 uint32_t Mult2 = A.countTrailingZeros(); 8414 // D = 2^Mult2 8415 8416 // 2. Check if B is divisible by D. 8417 // 8418 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8419 // is not less than multiplicity of this prime factor for D. 8420 if (SE.GetMinTrailingZeros(B) < Mult2) 8421 return SE.getCouldNotCompute(); 8422 8423 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8424 // modulo (N / D). 8425 // 8426 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8427 // (N / D) in general. The inverse itself always fits into BW bits, though, 8428 // so we immediately truncate it. 8429 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8430 APInt Mod(BW + 1, 0); 8431 Mod.setBit(BW - Mult2); // Mod = N / D 8432 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8433 8434 // 4. Compute the minimum unsigned root of the equation: 8435 // I * (B / D) mod (N / D) 8436 // To simplify the computation, we factor out the divide by D: 8437 // (I * B mod N) / D 8438 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8439 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8440 } 8441 8442 /// For a given quadratic addrec, generate coefficients of the corresponding 8443 /// quadratic equation, multiplied by a common value to ensure that they are 8444 /// integers. 8445 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8446 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8447 /// were multiplied by, and BitWidth is the bit width of the original addrec 8448 /// coefficients. 8449 /// This function returns None if the addrec coefficients are not compile- 8450 /// time constants. 8451 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8452 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8453 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8454 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8455 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8456 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8457 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8458 << *AddRec << '\n'); 8459 8460 // We currently can only solve this if the coefficients are constants. 8461 if (!LC || !MC || !NC) { 8462 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8463 return None; 8464 } 8465 8466 APInt L = LC->getAPInt(); 8467 APInt M = MC->getAPInt(); 8468 APInt N = NC->getAPInt(); 8469 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8470 8471 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8472 unsigned NewWidth = BitWidth + 1; 8473 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8474 << BitWidth << '\n'); 8475 // The sign-extension (as opposed to a zero-extension) here matches the 8476 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8477 N = N.sext(NewWidth); 8478 M = M.sext(NewWidth); 8479 L = L.sext(NewWidth); 8480 8481 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8482 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8483 // L+M, L+2M+N, L+3M+3N, ... 8484 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8485 // 8486 // The equation Acc = 0 is then 8487 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8488 // In a quadratic form it becomes: 8489 // N n^2 + (2M-N) n + 2L = 0. 8490 8491 APInt A = N; 8492 APInt B = 2 * M - A; 8493 APInt C = 2 * L; 8494 APInt T = APInt(NewWidth, 2); 8495 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8496 << "x + " << C << ", coeff bw: " << NewWidth 8497 << ", multiplied by " << T << '\n'); 8498 return std::make_tuple(A, B, C, T, BitWidth); 8499 } 8500 8501 /// Helper function to compare optional APInts: 8502 /// (a) if X and Y both exist, return min(X, Y), 8503 /// (b) if neither X nor Y exist, return None, 8504 /// (c) if exactly one of X and Y exists, return that value. 8505 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8506 if (X.hasValue() && Y.hasValue()) { 8507 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8508 APInt XW = X->sextOrSelf(W); 8509 APInt YW = Y->sextOrSelf(W); 8510 return XW.slt(YW) ? *X : *Y; 8511 } 8512 if (!X.hasValue() && !Y.hasValue()) 8513 return None; 8514 return X.hasValue() ? *X : *Y; 8515 } 8516 8517 /// Helper function to truncate an optional APInt to a given BitWidth. 8518 /// When solving addrec-related equations, it is preferable to return a value 8519 /// that has the same bit width as the original addrec's coefficients. If the 8520 /// solution fits in the original bit width, truncate it (except for i1). 8521 /// Returning a value of a different bit width may inhibit some optimizations. 8522 /// 8523 /// In general, a solution to a quadratic equation generated from an addrec 8524 /// may require BW+1 bits, where BW is the bit width of the addrec's 8525 /// coefficients. The reason is that the coefficients of the quadratic 8526 /// equation are BW+1 bits wide (to avoid truncation when converting from 8527 /// the addrec to the equation). 8528 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8529 if (!X.hasValue()) 8530 return None; 8531 unsigned W = X->getBitWidth(); 8532 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8533 return X->trunc(BitWidth); 8534 return X; 8535 } 8536 8537 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8538 /// iterations. The values L, M, N are assumed to be signed, and they 8539 /// should all have the same bit widths. 8540 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8541 /// where BW is the bit width of the addrec's coefficients. 8542 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8543 /// returned as such, otherwise the bit width of the returned value may 8544 /// be greater than BW. 8545 /// 8546 /// This function returns None if 8547 /// (a) the addrec coefficients are not constant, or 8548 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8549 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8550 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8551 static Optional<APInt> 8552 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8553 APInt A, B, C, M; 8554 unsigned BitWidth; 8555 auto T = GetQuadraticEquation(AddRec); 8556 if (!T.hasValue()) 8557 return None; 8558 8559 std::tie(A, B, C, M, BitWidth) = *T; 8560 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8561 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8562 if (!X.hasValue()) 8563 return None; 8564 8565 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8566 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8567 if (!V->isZero()) 8568 return None; 8569 8570 return TruncIfPossible(X, BitWidth); 8571 } 8572 8573 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8574 /// iterations. The values M, N are assumed to be signed, and they 8575 /// should all have the same bit widths. 8576 /// Find the least n such that c(n) does not belong to the given range, 8577 /// while c(n-1) does. 8578 /// 8579 /// This function returns None if 8580 /// (a) the addrec coefficients are not constant, or 8581 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8582 /// bounds of the range. 8583 static Optional<APInt> 8584 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8585 const ConstantRange &Range, ScalarEvolution &SE) { 8586 assert(AddRec->getOperand(0)->isZero() && 8587 "Starting value of addrec should be 0"); 8588 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8589 << Range << ", addrec " << *AddRec << '\n'); 8590 // This case is handled in getNumIterationsInRange. Here we can assume that 8591 // we start in the range. 8592 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8593 "Addrec's initial value should be in range"); 8594 8595 APInt A, B, C, M; 8596 unsigned BitWidth; 8597 auto T = GetQuadraticEquation(AddRec); 8598 if (!T.hasValue()) 8599 return None; 8600 8601 // Be careful about the return value: there can be two reasons for not 8602 // returning an actual number. First, if no solutions to the equations 8603 // were found, and second, if the solutions don't leave the given range. 8604 // The first case means that the actual solution is "unknown", the second 8605 // means that it's known, but not valid. If the solution is unknown, we 8606 // cannot make any conclusions. 8607 // Return a pair: the optional solution and a flag indicating if the 8608 // solution was found. 8609 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8610 // Solve for signed overflow and unsigned overflow, pick the lower 8611 // solution. 8612 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8613 << Bound << " (before multiplying by " << M << ")\n"); 8614 Bound *= M; // The quadratic equation multiplier. 8615 8616 Optional<APInt> SO = None; 8617 if (BitWidth > 1) { 8618 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8619 "signed overflow\n"); 8620 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8621 } 8622 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8623 "unsigned overflow\n"); 8624 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8625 BitWidth+1); 8626 8627 auto LeavesRange = [&] (const APInt &X) { 8628 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8629 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8630 if (Range.contains(V0->getValue())) 8631 return false; 8632 // X should be at least 1, so X-1 is non-negative. 8633 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8634 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8635 if (Range.contains(V1->getValue())) 8636 return true; 8637 return false; 8638 }; 8639 8640 // If SolveQuadraticEquationWrap returns None, it means that there can 8641 // be a solution, but the function failed to find it. We cannot treat it 8642 // as "no solution". 8643 if (!SO.hasValue() || !UO.hasValue()) 8644 return { None, false }; 8645 8646 // Check the smaller value first to see if it leaves the range. 8647 // At this point, both SO and UO must have values. 8648 Optional<APInt> Min = MinOptional(SO, UO); 8649 if (LeavesRange(*Min)) 8650 return { Min, true }; 8651 Optional<APInt> Max = Min == SO ? UO : SO; 8652 if (LeavesRange(*Max)) 8653 return { Max, true }; 8654 8655 // Solutions were found, but were eliminated, hence the "true". 8656 return { None, true }; 8657 }; 8658 8659 std::tie(A, B, C, M, BitWidth) = *T; 8660 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8661 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8662 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8663 auto SL = SolveForBoundary(Lower); 8664 auto SU = SolveForBoundary(Upper); 8665 // If any of the solutions was unknown, no meaninigful conclusions can 8666 // be made. 8667 if (!SL.second || !SU.second) 8668 return None; 8669 8670 // Claim: The correct solution is not some value between Min and Max. 8671 // 8672 // Justification: Assuming that Min and Max are different values, one of 8673 // them is when the first signed overflow happens, the other is when the 8674 // first unsigned overflow happens. Crossing the range boundary is only 8675 // possible via an overflow (treating 0 as a special case of it, modeling 8676 // an overflow as crossing k*2^W for some k). 8677 // 8678 // The interesting case here is when Min was eliminated as an invalid 8679 // solution, but Max was not. The argument is that if there was another 8680 // overflow between Min and Max, it would also have been eliminated if 8681 // it was considered. 8682 // 8683 // For a given boundary, it is possible to have two overflows of the same 8684 // type (signed/unsigned) without having the other type in between: this 8685 // can happen when the vertex of the parabola is between the iterations 8686 // corresponding to the overflows. This is only possible when the two 8687 // overflows cross k*2^W for the same k. In such case, if the second one 8688 // left the range (and was the first one to do so), the first overflow 8689 // would have to enter the range, which would mean that either we had left 8690 // the range before or that we started outside of it. Both of these cases 8691 // are contradictions. 8692 // 8693 // Claim: In the case where SolveForBoundary returns None, the correct 8694 // solution is not some value between the Max for this boundary and the 8695 // Min of the other boundary. 8696 // 8697 // Justification: Assume that we had such Max_A and Min_B corresponding 8698 // to range boundaries A and B and such that Max_A < Min_B. If there was 8699 // a solution between Max_A and Min_B, it would have to be caused by an 8700 // overflow corresponding to either A or B. It cannot correspond to B, 8701 // since Min_B is the first occurrence of such an overflow. If it 8702 // corresponded to A, it would have to be either a signed or an unsigned 8703 // overflow that is larger than both eliminated overflows for A. But 8704 // between the eliminated overflows and this overflow, the values would 8705 // cover the entire value space, thus crossing the other boundary, which 8706 // is a contradiction. 8707 8708 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8709 } 8710 8711 ScalarEvolution::ExitLimit 8712 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8713 bool AllowPredicates) { 8714 8715 // This is only used for loops with a "x != y" exit test. The exit condition 8716 // is now expressed as a single expression, V = x-y. So the exit test is 8717 // effectively V != 0. We know and take advantage of the fact that this 8718 // expression only being used in a comparison by zero context. 8719 8720 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8721 // If the value is a constant 8722 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8723 // If the value is already zero, the branch will execute zero times. 8724 if (C->getValue()->isZero()) return C; 8725 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8726 } 8727 8728 const SCEVAddRecExpr *AddRec = 8729 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8730 8731 if (!AddRec && AllowPredicates) 8732 // Try to make this an AddRec using runtime tests, in the first X 8733 // iterations of this loop, where X is the SCEV expression found by the 8734 // algorithm below. 8735 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8736 8737 if (!AddRec || AddRec->getLoop() != L) 8738 return getCouldNotCompute(); 8739 8740 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8741 // the quadratic equation to solve it. 8742 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8743 // We can only use this value if the chrec ends up with an exact zero 8744 // value at this index. When solving for "X*X != 5", for example, we 8745 // should not accept a root of 2. 8746 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8747 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8748 return ExitLimit(R, R, false, Predicates); 8749 } 8750 return getCouldNotCompute(); 8751 } 8752 8753 // Otherwise we can only handle this if it is affine. 8754 if (!AddRec->isAffine()) 8755 return getCouldNotCompute(); 8756 8757 // If this is an affine expression, the execution count of this branch is 8758 // the minimum unsigned root of the following equation: 8759 // 8760 // Start + Step*N = 0 (mod 2^BW) 8761 // 8762 // equivalent to: 8763 // 8764 // Step*N = -Start (mod 2^BW) 8765 // 8766 // where BW is the common bit width of Start and Step. 8767 8768 // Get the initial value for the loop. 8769 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8770 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8771 8772 // For now we handle only constant steps. 8773 // 8774 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8775 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8776 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8777 // We have not yet seen any such cases. 8778 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8779 if (!StepC || StepC->getValue()->isZero()) 8780 return getCouldNotCompute(); 8781 8782 // For positive steps (counting up until unsigned overflow): 8783 // N = -Start/Step (as unsigned) 8784 // For negative steps (counting down to zero): 8785 // N = Start/-Step 8786 // First compute the unsigned distance from zero in the direction of Step. 8787 bool CountDown = StepC->getAPInt().isNegative(); 8788 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8789 8790 // Handle unitary steps, which cannot wraparound. 8791 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8792 // N = Distance (as unsigned) 8793 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8794 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 8795 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 8796 if (MaxBECountBase.ult(MaxBECount)) 8797 MaxBECount = MaxBECountBase; 8798 8799 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8800 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8801 // case, and see if we can improve the bound. 8802 // 8803 // Explicitly handling this here is necessary because getUnsignedRange 8804 // isn't context-sensitive; it doesn't know that we only care about the 8805 // range inside the loop. 8806 const SCEV *Zero = getZero(Distance->getType()); 8807 const SCEV *One = getOne(Distance->getType()); 8808 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8809 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8810 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8811 // as "unsigned_max(Distance + 1) - 1". 8812 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8813 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8814 } 8815 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8816 } 8817 8818 // If the condition controls loop exit (the loop exits only if the expression 8819 // is true) and the addition is no-wrap we can use unsigned divide to 8820 // compute the backedge count. In this case, the step may not divide the 8821 // distance, but we don't care because if the condition is "missed" the loop 8822 // will have undefined behavior due to wrapping. 8823 if (ControlsExit && AddRec->hasNoSelfWrap() && 8824 loopHasNoAbnormalExits(AddRec->getLoop())) { 8825 const SCEV *Exact = 8826 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8827 const SCEV *Max = 8828 Exact == getCouldNotCompute() 8829 ? Exact 8830 : getConstant(getUnsignedRangeMax(Exact)); 8831 return ExitLimit(Exact, Max, false, Predicates); 8832 } 8833 8834 // Solve the general equation. 8835 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8836 getNegativeSCEV(Start), *this); 8837 const SCEV *M = E == getCouldNotCompute() 8838 ? E 8839 : getConstant(getUnsignedRangeMax(E)); 8840 return ExitLimit(E, M, false, Predicates); 8841 } 8842 8843 ScalarEvolution::ExitLimit 8844 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8845 // Loops that look like: while (X == 0) are very strange indeed. We don't 8846 // handle them yet except for the trivial case. This could be expanded in the 8847 // future as needed. 8848 8849 // If the value is a constant, check to see if it is known to be non-zero 8850 // already. If so, the backedge will execute zero times. 8851 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8852 if (!C->getValue()->isZero()) 8853 return getZero(C->getType()); 8854 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8855 } 8856 8857 // We could implement others, but I really doubt anyone writes loops like 8858 // this, and if they did, they would already be constant folded. 8859 return getCouldNotCompute(); 8860 } 8861 8862 std::pair<const BasicBlock *, const BasicBlock *> 8863 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 8864 const { 8865 // If the block has a unique predecessor, then there is no path from the 8866 // predecessor to the block that does not go through the direct edge 8867 // from the predecessor to the block. 8868 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 8869 return {Pred, BB}; 8870 8871 // A loop's header is defined to be a block that dominates the loop. 8872 // If the header has a unique predecessor outside the loop, it must be 8873 // a block that has exactly one successor that can reach the loop. 8874 if (const Loop *L = LI.getLoopFor(BB)) 8875 return {L->getLoopPredecessor(), L->getHeader()}; 8876 8877 return {nullptr, nullptr}; 8878 } 8879 8880 /// SCEV structural equivalence is usually sufficient for testing whether two 8881 /// expressions are equal, however for the purposes of looking for a condition 8882 /// guarding a loop, it can be useful to be a little more general, since a 8883 /// front-end may have replicated the controlling expression. 8884 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8885 // Quick check to see if they are the same SCEV. 8886 if (A == B) return true; 8887 8888 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8889 // Not all instructions that are "identical" compute the same value. For 8890 // instance, two distinct alloca instructions allocating the same type are 8891 // identical and do not read memory; but compute distinct values. 8892 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8893 }; 8894 8895 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8896 // two different instructions with the same value. Check for this case. 8897 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8898 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8899 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8900 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8901 if (ComputesEqualValues(AI, BI)) 8902 return true; 8903 8904 // Otherwise assume they may have a different value. 8905 return false; 8906 } 8907 8908 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8909 const SCEV *&LHS, const SCEV *&RHS, 8910 unsigned Depth) { 8911 bool Changed = false; 8912 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8913 // '0 != 0'. 8914 auto TrivialCase = [&](bool TriviallyTrue) { 8915 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8916 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8917 return true; 8918 }; 8919 // If we hit the max recursion limit bail out. 8920 if (Depth >= 3) 8921 return false; 8922 8923 // Canonicalize a constant to the right side. 8924 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8925 // Check for both operands constant. 8926 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8927 if (ConstantExpr::getICmp(Pred, 8928 LHSC->getValue(), 8929 RHSC->getValue())->isNullValue()) 8930 return TrivialCase(false); 8931 else 8932 return TrivialCase(true); 8933 } 8934 // Otherwise swap the operands to put the constant on the right. 8935 std::swap(LHS, RHS); 8936 Pred = ICmpInst::getSwappedPredicate(Pred); 8937 Changed = true; 8938 } 8939 8940 // If we're comparing an addrec with a value which is loop-invariant in the 8941 // addrec's loop, put the addrec on the left. Also make a dominance check, 8942 // as both operands could be addrecs loop-invariant in each other's loop. 8943 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8944 const Loop *L = AR->getLoop(); 8945 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8946 std::swap(LHS, RHS); 8947 Pred = ICmpInst::getSwappedPredicate(Pred); 8948 Changed = true; 8949 } 8950 } 8951 8952 // If there's a constant operand, canonicalize comparisons with boundary 8953 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8954 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8955 const APInt &RA = RC->getAPInt(); 8956 8957 bool SimplifiedByConstantRange = false; 8958 8959 if (!ICmpInst::isEquality(Pred)) { 8960 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8961 if (ExactCR.isFullSet()) 8962 return TrivialCase(true); 8963 else if (ExactCR.isEmptySet()) 8964 return TrivialCase(false); 8965 8966 APInt NewRHS; 8967 CmpInst::Predicate NewPred; 8968 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8969 ICmpInst::isEquality(NewPred)) { 8970 // We were able to convert an inequality to an equality. 8971 Pred = NewPred; 8972 RHS = getConstant(NewRHS); 8973 Changed = SimplifiedByConstantRange = true; 8974 } 8975 } 8976 8977 if (!SimplifiedByConstantRange) { 8978 switch (Pred) { 8979 default: 8980 break; 8981 case ICmpInst::ICMP_EQ: 8982 case ICmpInst::ICMP_NE: 8983 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8984 if (!RA) 8985 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8986 if (const SCEVMulExpr *ME = 8987 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8988 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8989 ME->getOperand(0)->isAllOnesValue()) { 8990 RHS = AE->getOperand(1); 8991 LHS = ME->getOperand(1); 8992 Changed = true; 8993 } 8994 break; 8995 8996 8997 // The "Should have been caught earlier!" messages refer to the fact 8998 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8999 // should have fired on the corresponding cases, and canonicalized the 9000 // check to trivial case. 9001 9002 case ICmpInst::ICMP_UGE: 9003 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9004 Pred = ICmpInst::ICMP_UGT; 9005 RHS = getConstant(RA - 1); 9006 Changed = true; 9007 break; 9008 case ICmpInst::ICMP_ULE: 9009 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9010 Pred = ICmpInst::ICMP_ULT; 9011 RHS = getConstant(RA + 1); 9012 Changed = true; 9013 break; 9014 case ICmpInst::ICMP_SGE: 9015 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9016 Pred = ICmpInst::ICMP_SGT; 9017 RHS = getConstant(RA - 1); 9018 Changed = true; 9019 break; 9020 case ICmpInst::ICMP_SLE: 9021 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9022 Pred = ICmpInst::ICMP_SLT; 9023 RHS = getConstant(RA + 1); 9024 Changed = true; 9025 break; 9026 } 9027 } 9028 } 9029 9030 // Check for obvious equality. 9031 if (HasSameValue(LHS, RHS)) { 9032 if (ICmpInst::isTrueWhenEqual(Pred)) 9033 return TrivialCase(true); 9034 if (ICmpInst::isFalseWhenEqual(Pred)) 9035 return TrivialCase(false); 9036 } 9037 9038 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9039 // adding or subtracting 1 from one of the operands. 9040 switch (Pred) { 9041 case ICmpInst::ICMP_SLE: 9042 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9043 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9044 SCEV::FlagNSW); 9045 Pred = ICmpInst::ICMP_SLT; 9046 Changed = true; 9047 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9048 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9049 SCEV::FlagNSW); 9050 Pred = ICmpInst::ICMP_SLT; 9051 Changed = true; 9052 } 9053 break; 9054 case ICmpInst::ICMP_SGE: 9055 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9056 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9057 SCEV::FlagNSW); 9058 Pred = ICmpInst::ICMP_SGT; 9059 Changed = true; 9060 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9061 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9062 SCEV::FlagNSW); 9063 Pred = ICmpInst::ICMP_SGT; 9064 Changed = true; 9065 } 9066 break; 9067 case ICmpInst::ICMP_ULE: 9068 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9069 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9070 SCEV::FlagNUW); 9071 Pred = ICmpInst::ICMP_ULT; 9072 Changed = true; 9073 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9074 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9075 Pred = ICmpInst::ICMP_ULT; 9076 Changed = true; 9077 } 9078 break; 9079 case ICmpInst::ICMP_UGE: 9080 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9081 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9082 Pred = ICmpInst::ICMP_UGT; 9083 Changed = true; 9084 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9085 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9086 SCEV::FlagNUW); 9087 Pred = ICmpInst::ICMP_UGT; 9088 Changed = true; 9089 } 9090 break; 9091 default: 9092 break; 9093 } 9094 9095 // TODO: More simplifications are possible here. 9096 9097 // Recursively simplify until we either hit a recursion limit or nothing 9098 // changes. 9099 if (Changed) 9100 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9101 9102 return Changed; 9103 } 9104 9105 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9106 return getSignedRangeMax(S).isNegative(); 9107 } 9108 9109 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9110 return getSignedRangeMin(S).isStrictlyPositive(); 9111 } 9112 9113 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9114 return !getSignedRangeMin(S).isNegative(); 9115 } 9116 9117 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9118 return !getSignedRangeMax(S).isStrictlyPositive(); 9119 } 9120 9121 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9122 return isKnownNegative(S) || isKnownPositive(S); 9123 } 9124 9125 std::pair<const SCEV *, const SCEV *> 9126 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9127 // Compute SCEV on entry of loop L. 9128 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9129 if (Start == getCouldNotCompute()) 9130 return { Start, Start }; 9131 // Compute post increment SCEV for loop L. 9132 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9133 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9134 return { Start, PostInc }; 9135 } 9136 9137 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9138 const SCEV *LHS, const SCEV *RHS) { 9139 // First collect all loops. 9140 SmallPtrSet<const Loop *, 8> LoopsUsed; 9141 getUsedLoops(LHS, LoopsUsed); 9142 getUsedLoops(RHS, LoopsUsed); 9143 9144 if (LoopsUsed.empty()) 9145 return false; 9146 9147 // Domination relationship must be a linear order on collected loops. 9148 #ifndef NDEBUG 9149 for (auto *L1 : LoopsUsed) 9150 for (auto *L2 : LoopsUsed) 9151 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9152 DT.dominates(L2->getHeader(), L1->getHeader())) && 9153 "Domination relationship is not a linear order"); 9154 #endif 9155 9156 const Loop *MDL = 9157 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9158 [&](const Loop *L1, const Loop *L2) { 9159 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9160 }); 9161 9162 // Get init and post increment value for LHS. 9163 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9164 // if LHS contains unknown non-invariant SCEV then bail out. 9165 if (SplitLHS.first == getCouldNotCompute()) 9166 return false; 9167 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9168 // Get init and post increment value for RHS. 9169 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9170 // if RHS contains unknown non-invariant SCEV then bail out. 9171 if (SplitRHS.first == getCouldNotCompute()) 9172 return false; 9173 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9174 // It is possible that init SCEV contains an invariant load but it does 9175 // not dominate MDL and is not available at MDL loop entry, so we should 9176 // check it here. 9177 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9178 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9179 return false; 9180 9181 // It seems backedge guard check is faster than entry one so in some cases 9182 // it can speed up whole estimation by short circuit 9183 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9184 SplitRHS.second) && 9185 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9186 } 9187 9188 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9189 const SCEV *LHS, const SCEV *RHS) { 9190 // Canonicalize the inputs first. 9191 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9192 9193 if (isKnownViaInduction(Pred, LHS, RHS)) 9194 return true; 9195 9196 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9197 return true; 9198 9199 // Otherwise see what can be done with some simple reasoning. 9200 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9201 } 9202 9203 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9204 const SCEV *LHS, const SCEV *RHS, 9205 const Instruction *Context) { 9206 // TODO: Analyze guards and assumes from Context's block. 9207 return isKnownPredicate(Pred, LHS, RHS) || 9208 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9209 } 9210 9211 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9212 const SCEVAddRecExpr *LHS, 9213 const SCEV *RHS) { 9214 const Loop *L = LHS->getLoop(); 9215 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9216 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9217 } 9218 9219 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9220 ICmpInst::Predicate Pred, 9221 bool &Increasing) { 9222 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9223 9224 #ifndef NDEBUG 9225 // Verify an invariant: inverting the predicate should turn a monotonically 9226 // increasing change to a monotonically decreasing one, and vice versa. 9227 bool IncreasingSwapped; 9228 bool ResultSwapped = isMonotonicPredicateImpl( 9229 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9230 9231 assert(Result == ResultSwapped && "should be able to analyze both!"); 9232 if (ResultSwapped) 9233 assert(Increasing == !IncreasingSwapped && 9234 "monotonicity should flip as we flip the predicate"); 9235 #endif 9236 9237 return Result; 9238 } 9239 9240 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9241 ICmpInst::Predicate Pred, 9242 bool &Increasing) { 9243 9244 // A zero step value for LHS means the induction variable is essentially a 9245 // loop invariant value. We don't really depend on the predicate actually 9246 // flipping from false to true (for increasing predicates, and the other way 9247 // around for decreasing predicates), all we care about is that *if* the 9248 // predicate changes then it only changes from false to true. 9249 // 9250 // A zero step value in itself is not very useful, but there may be places 9251 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9252 // as general as possible. 9253 9254 switch (Pred) { 9255 default: 9256 return false; // Conservative answer 9257 9258 case ICmpInst::ICMP_UGT: 9259 case ICmpInst::ICMP_UGE: 9260 case ICmpInst::ICMP_ULT: 9261 case ICmpInst::ICMP_ULE: 9262 if (!LHS->hasNoUnsignedWrap()) 9263 return false; 9264 9265 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9266 return true; 9267 9268 case ICmpInst::ICMP_SGT: 9269 case ICmpInst::ICMP_SGE: 9270 case ICmpInst::ICMP_SLT: 9271 case ICmpInst::ICMP_SLE: { 9272 if (!LHS->hasNoSignedWrap()) 9273 return false; 9274 9275 const SCEV *Step = LHS->getStepRecurrence(*this); 9276 9277 if (isKnownNonNegative(Step)) { 9278 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9279 return true; 9280 } 9281 9282 if (isKnownNonPositive(Step)) { 9283 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9284 return true; 9285 } 9286 9287 return false; 9288 } 9289 9290 } 9291 9292 llvm_unreachable("switch has default clause!"); 9293 } 9294 9295 bool ScalarEvolution::isLoopInvariantPredicate( 9296 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9297 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9298 const SCEV *&InvariantRHS) { 9299 9300 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9301 if (!isLoopInvariant(RHS, L)) { 9302 if (!isLoopInvariant(LHS, L)) 9303 return false; 9304 9305 std::swap(LHS, RHS); 9306 Pred = ICmpInst::getSwappedPredicate(Pred); 9307 } 9308 9309 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9310 if (!ArLHS || ArLHS->getLoop() != L) 9311 return false; 9312 9313 bool Increasing; 9314 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9315 return false; 9316 9317 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9318 // true as the loop iterates, and the backedge is control dependent on 9319 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9320 // 9321 // * if the predicate was false in the first iteration then the predicate 9322 // is never evaluated again, since the loop exits without taking the 9323 // backedge. 9324 // * if the predicate was true in the first iteration then it will 9325 // continue to be true for all future iterations since it is 9326 // monotonically increasing. 9327 // 9328 // For both the above possibilities, we can replace the loop varying 9329 // predicate with its value on the first iteration of the loop (which is 9330 // loop invariant). 9331 // 9332 // A similar reasoning applies for a monotonically decreasing predicate, by 9333 // replacing true with false and false with true in the above two bullets. 9334 9335 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9336 9337 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9338 return false; 9339 9340 InvariantPred = Pred; 9341 InvariantLHS = ArLHS->getStart(); 9342 InvariantRHS = RHS; 9343 return true; 9344 } 9345 9346 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9347 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9348 if (HasSameValue(LHS, RHS)) 9349 return ICmpInst::isTrueWhenEqual(Pred); 9350 9351 // This code is split out from isKnownPredicate because it is called from 9352 // within isLoopEntryGuardedByCond. 9353 9354 auto CheckRanges = 9355 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9356 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9357 .contains(RangeLHS); 9358 }; 9359 9360 // The check at the top of the function catches the case where the values are 9361 // known to be equal. 9362 if (Pred == CmpInst::ICMP_EQ) 9363 return false; 9364 9365 if (Pred == CmpInst::ICMP_NE) 9366 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9367 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9368 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9369 9370 if (CmpInst::isSigned(Pred)) 9371 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9372 9373 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9374 } 9375 9376 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9377 const SCEV *LHS, 9378 const SCEV *RHS) { 9379 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9380 // Return Y via OutY. 9381 auto MatchBinaryAddToConst = 9382 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9383 SCEV::NoWrapFlags ExpectedFlags) { 9384 const SCEV *NonConstOp, *ConstOp; 9385 SCEV::NoWrapFlags FlagsPresent; 9386 9387 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9388 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9389 return false; 9390 9391 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9392 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9393 }; 9394 9395 APInt C; 9396 9397 switch (Pred) { 9398 default: 9399 break; 9400 9401 case ICmpInst::ICMP_SGE: 9402 std::swap(LHS, RHS); 9403 LLVM_FALLTHROUGH; 9404 case ICmpInst::ICMP_SLE: 9405 // X s<= (X + C)<nsw> if C >= 0 9406 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9407 return true; 9408 9409 // (X + C)<nsw> s<= X if C <= 0 9410 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9411 !C.isStrictlyPositive()) 9412 return true; 9413 break; 9414 9415 case ICmpInst::ICMP_SGT: 9416 std::swap(LHS, RHS); 9417 LLVM_FALLTHROUGH; 9418 case ICmpInst::ICMP_SLT: 9419 // X s< (X + C)<nsw> if C > 0 9420 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9421 C.isStrictlyPositive()) 9422 return true; 9423 9424 // (X + C)<nsw> s< X if C < 0 9425 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9426 return true; 9427 break; 9428 9429 case ICmpInst::ICMP_UGE: 9430 std::swap(LHS, RHS); 9431 LLVM_FALLTHROUGH; 9432 case ICmpInst::ICMP_ULE: 9433 // X u<= (X + C)<nuw> for any C 9434 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9435 return true; 9436 break; 9437 9438 case ICmpInst::ICMP_UGT: 9439 std::swap(LHS, RHS); 9440 LLVM_FALLTHROUGH; 9441 case ICmpInst::ICMP_ULT: 9442 // X u< (X + C)<nuw> if C != 0 9443 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9444 return true; 9445 break; 9446 } 9447 9448 return false; 9449 } 9450 9451 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9452 const SCEV *LHS, 9453 const SCEV *RHS) { 9454 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9455 return false; 9456 9457 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9458 // the stack can result in exponential time complexity. 9459 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9460 9461 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9462 // 9463 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9464 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9465 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9466 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9467 // use isKnownPredicate later if needed. 9468 return isKnownNonNegative(RHS) && 9469 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9470 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9471 } 9472 9473 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9474 ICmpInst::Predicate Pred, 9475 const SCEV *LHS, const SCEV *RHS) { 9476 // No need to even try if we know the module has no guards. 9477 if (!HasGuards) 9478 return false; 9479 9480 return any_of(*BB, [&](const Instruction &I) { 9481 using namespace llvm::PatternMatch; 9482 9483 Value *Condition; 9484 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9485 m_Value(Condition))) && 9486 isImpliedCond(Pred, LHS, RHS, Condition, false); 9487 }); 9488 } 9489 9490 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9491 /// protected by a conditional between LHS and RHS. This is used to 9492 /// to eliminate casts. 9493 bool 9494 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9495 ICmpInst::Predicate Pred, 9496 const SCEV *LHS, const SCEV *RHS) { 9497 // Interpret a null as meaning no loop, where there is obviously no guard 9498 // (interprocedural conditions notwithstanding). 9499 if (!L) return true; 9500 9501 if (VerifyIR) 9502 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9503 "This cannot be done on broken IR!"); 9504 9505 9506 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9507 return true; 9508 9509 BasicBlock *Latch = L->getLoopLatch(); 9510 if (!Latch) 9511 return false; 9512 9513 BranchInst *LoopContinuePredicate = 9514 dyn_cast<BranchInst>(Latch->getTerminator()); 9515 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9516 isImpliedCond(Pred, LHS, RHS, 9517 LoopContinuePredicate->getCondition(), 9518 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9519 return true; 9520 9521 // We don't want more than one activation of the following loops on the stack 9522 // -- that can lead to O(n!) time complexity. 9523 if (WalkingBEDominatingConds) 9524 return false; 9525 9526 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9527 9528 // See if we can exploit a trip count to prove the predicate. 9529 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9530 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9531 if (LatchBECount != getCouldNotCompute()) { 9532 // We know that Latch branches back to the loop header exactly 9533 // LatchBECount times. This means the backdege condition at Latch is 9534 // equivalent to "{0,+,1} u< LatchBECount". 9535 Type *Ty = LatchBECount->getType(); 9536 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9537 const SCEV *LoopCounter = 9538 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9539 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9540 LatchBECount)) 9541 return true; 9542 } 9543 9544 // Check conditions due to any @llvm.assume intrinsics. 9545 for (auto &AssumeVH : AC.assumptions()) { 9546 if (!AssumeVH) 9547 continue; 9548 auto *CI = cast<CallInst>(AssumeVH); 9549 if (!DT.dominates(CI, Latch->getTerminator())) 9550 continue; 9551 9552 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9553 return true; 9554 } 9555 9556 // If the loop is not reachable from the entry block, we risk running into an 9557 // infinite loop as we walk up into the dom tree. These loops do not matter 9558 // anyway, so we just return a conservative answer when we see them. 9559 if (!DT.isReachableFromEntry(L->getHeader())) 9560 return false; 9561 9562 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9563 return true; 9564 9565 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9566 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9567 assert(DTN && "should reach the loop header before reaching the root!"); 9568 9569 BasicBlock *BB = DTN->getBlock(); 9570 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9571 return true; 9572 9573 BasicBlock *PBB = BB->getSinglePredecessor(); 9574 if (!PBB) 9575 continue; 9576 9577 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9578 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9579 continue; 9580 9581 Value *Condition = ContinuePredicate->getCondition(); 9582 9583 // If we have an edge `E` within the loop body that dominates the only 9584 // latch, the condition guarding `E` also guards the backedge. This 9585 // reasoning works only for loops with a single latch. 9586 9587 BasicBlockEdge DominatingEdge(PBB, BB); 9588 if (DominatingEdge.isSingleEdge()) { 9589 // We're constructively (and conservatively) enumerating edges within the 9590 // loop body that dominate the latch. The dominator tree better agree 9591 // with us on this: 9592 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9593 9594 if (isImpliedCond(Pred, LHS, RHS, Condition, 9595 BB != ContinuePredicate->getSuccessor(0))) 9596 return true; 9597 } 9598 } 9599 9600 return false; 9601 } 9602 9603 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9604 ICmpInst::Predicate Pred, 9605 const SCEV *LHS, 9606 const SCEV *RHS) { 9607 if (VerifyIR) 9608 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9609 "This cannot be done on broken IR!"); 9610 9611 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9612 return true; 9613 9614 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9615 // the facts (a >= b && a != b) separately. A typical situation is when the 9616 // non-strict comparison is known from ranges and non-equality is known from 9617 // dominating predicates. If we are proving strict comparison, we always try 9618 // to prove non-equality and non-strict comparison separately. 9619 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9620 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9621 bool ProvedNonStrictComparison = false; 9622 bool ProvedNonEquality = false; 9623 9624 if (ProvingStrictComparison) { 9625 ProvedNonStrictComparison = 9626 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9627 ProvedNonEquality = 9628 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9629 if (ProvedNonStrictComparison && ProvedNonEquality) 9630 return true; 9631 } 9632 9633 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9634 auto ProveViaGuard = [&](const BasicBlock *Block) { 9635 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9636 return true; 9637 if (ProvingStrictComparison) { 9638 if (!ProvedNonStrictComparison) 9639 ProvedNonStrictComparison = 9640 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9641 if (!ProvedNonEquality) 9642 ProvedNonEquality = 9643 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9644 if (ProvedNonStrictComparison && ProvedNonEquality) 9645 return true; 9646 } 9647 return false; 9648 }; 9649 9650 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9651 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9652 const Instruction *Context = &BB->front(); 9653 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9654 return true; 9655 if (ProvingStrictComparison) { 9656 if (!ProvedNonStrictComparison) 9657 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 9658 Condition, Inverse, Context); 9659 if (!ProvedNonEquality) 9660 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 9661 Condition, Inverse, Context); 9662 if (ProvedNonStrictComparison && ProvedNonEquality) 9663 return true; 9664 } 9665 return false; 9666 }; 9667 9668 // Starting at the block's predecessor, climb up the predecessor chain, as long 9669 // as there are predecessors that can be found that have unique successors 9670 // leading to the original block. 9671 const Loop *ContainingLoop = LI.getLoopFor(BB); 9672 const BasicBlock *PredBB; 9673 if (ContainingLoop && ContainingLoop->getHeader() == BB) 9674 PredBB = ContainingLoop->getLoopPredecessor(); 9675 else 9676 PredBB = BB->getSinglePredecessor(); 9677 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 9678 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9679 if (ProveViaGuard(Pair.first)) 9680 return true; 9681 9682 const BranchInst *LoopEntryPredicate = 9683 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9684 if (!LoopEntryPredicate || 9685 LoopEntryPredicate->isUnconditional()) 9686 continue; 9687 9688 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9689 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9690 return true; 9691 } 9692 9693 // Check conditions due to any @llvm.assume intrinsics. 9694 for (auto &AssumeVH : AC.assumptions()) { 9695 if (!AssumeVH) 9696 continue; 9697 auto *CI = cast<CallInst>(AssumeVH); 9698 if (!DT.dominates(CI, BB)) 9699 continue; 9700 9701 if (ProveViaCond(CI->getArgOperand(0), false)) 9702 return true; 9703 } 9704 9705 return false; 9706 } 9707 9708 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9709 ICmpInst::Predicate Pred, 9710 const SCEV *LHS, 9711 const SCEV *RHS) { 9712 // Interpret a null as meaning no loop, where there is obviously no guard 9713 // (interprocedural conditions notwithstanding). 9714 if (!L) 9715 return false; 9716 9717 // Both LHS and RHS must be available at loop entry. 9718 assert(isAvailableAtLoopEntry(LHS, L) && 9719 "LHS is not available at Loop Entry"); 9720 assert(isAvailableAtLoopEntry(RHS, L) && 9721 "RHS is not available at Loop Entry"); 9722 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 9723 } 9724 9725 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9726 const SCEV *RHS, 9727 const Value *FoundCondValue, bool Inverse, 9728 const Instruction *Context) { 9729 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9730 return false; 9731 9732 auto ClearOnExit = 9733 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9734 9735 // Recursively handle And and Or conditions. 9736 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9737 if (BO->getOpcode() == Instruction::And) { 9738 if (!Inverse) 9739 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9740 Context) || 9741 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9742 Context); 9743 } else if (BO->getOpcode() == Instruction::Or) { 9744 if (Inverse) 9745 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9746 Context) || 9747 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9748 Context); 9749 } 9750 } 9751 9752 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9753 if (!ICI) return false; 9754 9755 // Now that we found a conditional branch that dominates the loop or controls 9756 // the loop latch. Check to see if it is the comparison we are looking for. 9757 ICmpInst::Predicate FoundPred; 9758 if (Inverse) 9759 FoundPred = ICI->getInversePredicate(); 9760 else 9761 FoundPred = ICI->getPredicate(); 9762 9763 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9764 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9765 9766 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 9767 } 9768 9769 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9770 const SCEV *RHS, 9771 ICmpInst::Predicate FoundPred, 9772 const SCEV *FoundLHS, const SCEV *FoundRHS, 9773 const Instruction *Context) { 9774 // Balance the types. 9775 if (getTypeSizeInBits(LHS->getType()) < 9776 getTypeSizeInBits(FoundLHS->getType())) { 9777 if (CmpInst::isSigned(Pred)) { 9778 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9779 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9780 } else { 9781 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9782 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9783 } 9784 } else if (getTypeSizeInBits(LHS->getType()) > 9785 getTypeSizeInBits(FoundLHS->getType())) { 9786 if (CmpInst::isSigned(FoundPred)) { 9787 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9788 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9789 } else { 9790 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9791 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9792 } 9793 } 9794 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 9795 FoundRHS, Context); 9796 } 9797 9798 bool ScalarEvolution::isImpliedCondBalancedTypes( 9799 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9800 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 9801 const Instruction *Context) { 9802 assert(getTypeSizeInBits(LHS->getType()) == 9803 getTypeSizeInBits(FoundLHS->getType()) && 9804 "Types should be balanced!"); 9805 // Canonicalize the query to match the way instcombine will have 9806 // canonicalized the comparison. 9807 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9808 if (LHS == RHS) 9809 return CmpInst::isTrueWhenEqual(Pred); 9810 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9811 if (FoundLHS == FoundRHS) 9812 return CmpInst::isFalseWhenEqual(FoundPred); 9813 9814 // Check to see if we can make the LHS or RHS match. 9815 if (LHS == FoundRHS || RHS == FoundLHS) { 9816 if (isa<SCEVConstant>(RHS)) { 9817 std::swap(FoundLHS, FoundRHS); 9818 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9819 } else { 9820 std::swap(LHS, RHS); 9821 Pred = ICmpInst::getSwappedPredicate(Pred); 9822 } 9823 } 9824 9825 // Check whether the found predicate is the same as the desired predicate. 9826 if (FoundPred == Pred) 9827 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9828 9829 // Check whether swapping the found predicate makes it the same as the 9830 // desired predicate. 9831 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9832 if (isa<SCEVConstant>(RHS)) 9833 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 9834 else 9835 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 9836 LHS, FoundLHS, FoundRHS, Context); 9837 } 9838 9839 // Unsigned comparison is the same as signed comparison when both the operands 9840 // are non-negative. 9841 if (CmpInst::isUnsigned(FoundPred) && 9842 CmpInst::getSignedPredicate(FoundPred) == Pred && 9843 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9844 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9845 9846 // Check if we can make progress by sharpening ranges. 9847 if (FoundPred == ICmpInst::ICMP_NE && 9848 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9849 9850 const SCEVConstant *C = nullptr; 9851 const SCEV *V = nullptr; 9852 9853 if (isa<SCEVConstant>(FoundLHS)) { 9854 C = cast<SCEVConstant>(FoundLHS); 9855 V = FoundRHS; 9856 } else { 9857 C = cast<SCEVConstant>(FoundRHS); 9858 V = FoundLHS; 9859 } 9860 9861 // The guarding predicate tells us that C != V. If the known range 9862 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9863 // range we consider has to correspond to same signedness as the 9864 // predicate we're interested in folding. 9865 9866 APInt Min = ICmpInst::isSigned(Pred) ? 9867 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9868 9869 if (Min == C->getAPInt()) { 9870 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9871 // This is true even if (Min + 1) wraps around -- in case of 9872 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9873 9874 APInt SharperMin = Min + 1; 9875 9876 switch (Pred) { 9877 case ICmpInst::ICMP_SGE: 9878 case ICmpInst::ICMP_UGE: 9879 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9880 // RHS, we're done. 9881 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 9882 Context)) 9883 return true; 9884 LLVM_FALLTHROUGH; 9885 9886 case ICmpInst::ICMP_SGT: 9887 case ICmpInst::ICMP_UGT: 9888 // We know from the range information that (V `Pred` Min || 9889 // V == Min). We know from the guarding condition that !(V 9890 // == Min). This gives us 9891 // 9892 // V `Pred` Min || V == Min && !(V == Min) 9893 // => V `Pred` Min 9894 // 9895 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9896 9897 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 9898 Context)) 9899 return true; 9900 break; 9901 9902 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 9903 case ICmpInst::ICMP_SLE: 9904 case ICmpInst::ICMP_ULE: 9905 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9906 LHS, V, getConstant(SharperMin), Context)) 9907 return true; 9908 LLVM_FALLTHROUGH; 9909 9910 case ICmpInst::ICMP_SLT: 9911 case ICmpInst::ICMP_ULT: 9912 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9913 LHS, V, getConstant(Min), Context)) 9914 return true; 9915 break; 9916 9917 default: 9918 // No change 9919 break; 9920 } 9921 } 9922 } 9923 9924 // Check whether the actual condition is beyond sufficient. 9925 if (FoundPred == ICmpInst::ICMP_EQ) 9926 if (ICmpInst::isTrueWhenEqual(Pred)) 9927 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 9928 return true; 9929 if (Pred == ICmpInst::ICMP_NE) 9930 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9931 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 9932 Context)) 9933 return true; 9934 9935 // Otherwise assume the worst. 9936 return false; 9937 } 9938 9939 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9940 const SCEV *&L, const SCEV *&R, 9941 SCEV::NoWrapFlags &Flags) { 9942 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9943 if (!AE || AE->getNumOperands() != 2) 9944 return false; 9945 9946 L = AE->getOperand(0); 9947 R = AE->getOperand(1); 9948 Flags = AE->getNoWrapFlags(); 9949 return true; 9950 } 9951 9952 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9953 const SCEV *Less) { 9954 // We avoid subtracting expressions here because this function is usually 9955 // fairly deep in the call stack (i.e. is called many times). 9956 9957 // X - X = 0. 9958 if (More == Less) 9959 return APInt(getTypeSizeInBits(More->getType()), 0); 9960 9961 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9962 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9963 const auto *MAR = cast<SCEVAddRecExpr>(More); 9964 9965 if (LAR->getLoop() != MAR->getLoop()) 9966 return None; 9967 9968 // We look at affine expressions only; not for correctness but to keep 9969 // getStepRecurrence cheap. 9970 if (!LAR->isAffine() || !MAR->isAffine()) 9971 return None; 9972 9973 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9974 return None; 9975 9976 Less = LAR->getStart(); 9977 More = MAR->getStart(); 9978 9979 // fall through 9980 } 9981 9982 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9983 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9984 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9985 return M - L; 9986 } 9987 9988 SCEV::NoWrapFlags Flags; 9989 const SCEV *LLess = nullptr, *RLess = nullptr; 9990 const SCEV *LMore = nullptr, *RMore = nullptr; 9991 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9992 // Compare (X + C1) vs X. 9993 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9994 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9995 if (RLess == More) 9996 return -(C1->getAPInt()); 9997 9998 // Compare X vs (X + C2). 9999 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10000 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10001 if (RMore == Less) 10002 return C2->getAPInt(); 10003 10004 // Compare (X + C1) vs (X + C2). 10005 if (C1 && C2 && RLess == RMore) 10006 return C2->getAPInt() - C1->getAPInt(); 10007 10008 return None; 10009 } 10010 10011 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10012 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10013 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10014 // Try to recognize the following pattern: 10015 // 10016 // FoundRHS = ... 10017 // ... 10018 // loop: 10019 // FoundLHS = {Start,+,W} 10020 // context_bb: // Basic block from the same loop 10021 // known(Pred, FoundLHS, FoundRHS) 10022 // 10023 // If some predicate is known in the context of a loop, it is also known on 10024 // each iteration of this loop, including the first iteration. Therefore, in 10025 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10026 // prove the original pred using this fact. 10027 if (!Context) 10028 return false; 10029 const BasicBlock *ContextBB = Context->getParent(); 10030 // Make sure AR varies in the context block. 10031 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10032 const Loop *L = AR->getLoop(); 10033 // Make sure that context belongs to the loop and executes on 1st iteration 10034 // (if it ever executes at all). 10035 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10036 return false; 10037 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10038 return false; 10039 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10040 } 10041 10042 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10043 const Loop *L = AR->getLoop(); 10044 // Make sure that context belongs to the loop and executes on 1st iteration 10045 // (if it ever executes at all). 10046 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10047 return false; 10048 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10049 return false; 10050 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10051 } 10052 10053 return false; 10054 } 10055 10056 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10057 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10058 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10059 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10060 return false; 10061 10062 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10063 if (!AddRecLHS) 10064 return false; 10065 10066 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10067 if (!AddRecFoundLHS) 10068 return false; 10069 10070 // We'd like to let SCEV reason about control dependencies, so we constrain 10071 // both the inequalities to be about add recurrences on the same loop. This 10072 // way we can use isLoopEntryGuardedByCond later. 10073 10074 const Loop *L = AddRecFoundLHS->getLoop(); 10075 if (L != AddRecLHS->getLoop()) 10076 return false; 10077 10078 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10079 // 10080 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10081 // ... (2) 10082 // 10083 // Informal proof for (2), assuming (1) [*]: 10084 // 10085 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10086 // 10087 // Then 10088 // 10089 // FoundLHS s< FoundRHS s< INT_MIN - C 10090 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10091 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10092 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10093 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10094 // <=> FoundLHS + C s< FoundRHS + C 10095 // 10096 // [*]: (1) can be proved by ruling out overflow. 10097 // 10098 // [**]: This can be proved by analyzing all the four possibilities: 10099 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10100 // (A s>= 0, B s>= 0). 10101 // 10102 // Note: 10103 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10104 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10105 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10106 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10107 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10108 // C)". 10109 10110 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10111 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10112 if (!LDiff || !RDiff || *LDiff != *RDiff) 10113 return false; 10114 10115 if (LDiff->isMinValue()) 10116 return true; 10117 10118 APInt FoundRHSLimit; 10119 10120 if (Pred == CmpInst::ICMP_ULT) { 10121 FoundRHSLimit = -(*RDiff); 10122 } else { 10123 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10124 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10125 } 10126 10127 // Try to prove (1) or (2), as needed. 10128 return isAvailableAtLoopEntry(FoundRHS, L) && 10129 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10130 getConstant(FoundRHSLimit)); 10131 } 10132 10133 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10134 const SCEV *LHS, const SCEV *RHS, 10135 const SCEV *FoundLHS, 10136 const SCEV *FoundRHS, unsigned Depth) { 10137 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10138 10139 auto ClearOnExit = make_scope_exit([&]() { 10140 if (LPhi) { 10141 bool Erased = PendingMerges.erase(LPhi); 10142 assert(Erased && "Failed to erase LPhi!"); 10143 (void)Erased; 10144 } 10145 if (RPhi) { 10146 bool Erased = PendingMerges.erase(RPhi); 10147 assert(Erased && "Failed to erase RPhi!"); 10148 (void)Erased; 10149 } 10150 }); 10151 10152 // Find respective Phis and check that they are not being pending. 10153 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10154 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10155 if (!PendingMerges.insert(Phi).second) 10156 return false; 10157 LPhi = Phi; 10158 } 10159 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10160 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10161 // If we detect a loop of Phi nodes being processed by this method, for 10162 // example: 10163 // 10164 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10165 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10166 // 10167 // we don't want to deal with a case that complex, so return conservative 10168 // answer false. 10169 if (!PendingMerges.insert(Phi).second) 10170 return false; 10171 RPhi = Phi; 10172 } 10173 10174 // If none of LHS, RHS is a Phi, nothing to do here. 10175 if (!LPhi && !RPhi) 10176 return false; 10177 10178 // If there is a SCEVUnknown Phi we are interested in, make it left. 10179 if (!LPhi) { 10180 std::swap(LHS, RHS); 10181 std::swap(FoundLHS, FoundRHS); 10182 std::swap(LPhi, RPhi); 10183 Pred = ICmpInst::getSwappedPredicate(Pred); 10184 } 10185 10186 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10187 const BasicBlock *LBB = LPhi->getParent(); 10188 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10189 10190 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10191 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10192 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10193 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10194 }; 10195 10196 if (RPhi && RPhi->getParent() == LBB) { 10197 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10198 // If we compare two Phis from the same block, and for each entry block 10199 // the predicate is true for incoming values from this block, then the 10200 // predicate is also true for the Phis. 10201 for (const BasicBlock *IncBB : predecessors(LBB)) { 10202 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10203 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10204 if (!ProvedEasily(L, R)) 10205 return false; 10206 } 10207 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10208 // Case two: RHS is also a Phi from the same basic block, and it is an 10209 // AddRec. It means that there is a loop which has both AddRec and Unknown 10210 // PHIs, for it we can compare incoming values of AddRec from above the loop 10211 // and latch with their respective incoming values of LPhi. 10212 // TODO: Generalize to handle loops with many inputs in a header. 10213 if (LPhi->getNumIncomingValues() != 2) return false; 10214 10215 auto *RLoop = RAR->getLoop(); 10216 auto *Predecessor = RLoop->getLoopPredecessor(); 10217 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10218 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10219 if (!ProvedEasily(L1, RAR->getStart())) 10220 return false; 10221 auto *Latch = RLoop->getLoopLatch(); 10222 assert(Latch && "Loop with AddRec with no latch?"); 10223 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10224 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10225 return false; 10226 } else { 10227 // In all other cases go over inputs of LHS and compare each of them to RHS, 10228 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10229 // At this point RHS is either a non-Phi, or it is a Phi from some block 10230 // different from LBB. 10231 for (const BasicBlock *IncBB : predecessors(LBB)) { 10232 // Check that RHS is available in this block. 10233 if (!dominates(RHS, IncBB)) 10234 return false; 10235 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10236 if (!ProvedEasily(L, RHS)) 10237 return false; 10238 } 10239 } 10240 return true; 10241 } 10242 10243 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10244 const SCEV *LHS, const SCEV *RHS, 10245 const SCEV *FoundLHS, 10246 const SCEV *FoundRHS, 10247 const Instruction *Context) { 10248 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10249 return true; 10250 10251 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10252 return true; 10253 10254 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10255 Context)) 10256 return true; 10257 10258 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10259 FoundLHS, FoundRHS) || 10260 // ~x < ~y --> x > y 10261 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10262 getNotSCEV(FoundRHS), 10263 getNotSCEV(FoundLHS)); 10264 } 10265 10266 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10267 template <typename MinMaxExprType> 10268 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10269 const SCEV *Candidate) { 10270 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10271 if (!MinMaxExpr) 10272 return false; 10273 10274 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10275 } 10276 10277 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10278 ICmpInst::Predicate Pred, 10279 const SCEV *LHS, const SCEV *RHS) { 10280 // If both sides are affine addrecs for the same loop, with equal 10281 // steps, and we know the recurrences don't wrap, then we only 10282 // need to check the predicate on the starting values. 10283 10284 if (!ICmpInst::isRelational(Pred)) 10285 return false; 10286 10287 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10288 if (!LAR) 10289 return false; 10290 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10291 if (!RAR) 10292 return false; 10293 if (LAR->getLoop() != RAR->getLoop()) 10294 return false; 10295 if (!LAR->isAffine() || !RAR->isAffine()) 10296 return false; 10297 10298 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10299 return false; 10300 10301 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10302 SCEV::FlagNSW : SCEV::FlagNUW; 10303 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10304 return false; 10305 10306 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10307 } 10308 10309 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10310 /// expression? 10311 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10312 ICmpInst::Predicate Pred, 10313 const SCEV *LHS, const SCEV *RHS) { 10314 switch (Pred) { 10315 default: 10316 return false; 10317 10318 case ICmpInst::ICMP_SGE: 10319 std::swap(LHS, RHS); 10320 LLVM_FALLTHROUGH; 10321 case ICmpInst::ICMP_SLE: 10322 return 10323 // min(A, ...) <= A 10324 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10325 // A <= max(A, ...) 10326 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10327 10328 case ICmpInst::ICMP_UGE: 10329 std::swap(LHS, RHS); 10330 LLVM_FALLTHROUGH; 10331 case ICmpInst::ICMP_ULE: 10332 return 10333 // min(A, ...) <= A 10334 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10335 // A <= max(A, ...) 10336 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10337 } 10338 10339 llvm_unreachable("covered switch fell through?!"); 10340 } 10341 10342 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10343 const SCEV *LHS, const SCEV *RHS, 10344 const SCEV *FoundLHS, 10345 const SCEV *FoundRHS, 10346 unsigned Depth) { 10347 assert(getTypeSizeInBits(LHS->getType()) == 10348 getTypeSizeInBits(RHS->getType()) && 10349 "LHS and RHS have different sizes?"); 10350 assert(getTypeSizeInBits(FoundLHS->getType()) == 10351 getTypeSizeInBits(FoundRHS->getType()) && 10352 "FoundLHS and FoundRHS have different sizes?"); 10353 // We want to avoid hurting the compile time with analysis of too big trees. 10354 if (Depth > MaxSCEVOperationsImplicationDepth) 10355 return false; 10356 10357 // We only want to work with GT comparison so far. 10358 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10359 Pred = CmpInst::getSwappedPredicate(Pred); 10360 std::swap(LHS, RHS); 10361 std::swap(FoundLHS, FoundRHS); 10362 } 10363 10364 // For unsigned, try to reduce it to corresponding signed comparison. 10365 if (Pred == ICmpInst::ICMP_UGT) 10366 // We can replace unsigned predicate with its signed counterpart if all 10367 // involved values are non-negative. 10368 // TODO: We could have better support for unsigned. 10369 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10370 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10371 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10372 // use this fact to prove that LHS and RHS are non-negative. 10373 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10374 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10375 FoundRHS) && 10376 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10377 FoundRHS)) 10378 Pred = ICmpInst::ICMP_SGT; 10379 } 10380 10381 if (Pred != ICmpInst::ICMP_SGT) 10382 return false; 10383 10384 auto GetOpFromSExt = [&](const SCEV *S) { 10385 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10386 return Ext->getOperand(); 10387 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10388 // the constant in some cases. 10389 return S; 10390 }; 10391 10392 // Acquire values from extensions. 10393 auto *OrigLHS = LHS; 10394 auto *OrigFoundLHS = FoundLHS; 10395 LHS = GetOpFromSExt(LHS); 10396 FoundLHS = GetOpFromSExt(FoundLHS); 10397 10398 // Is the SGT predicate can be proved trivially or using the found context. 10399 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10400 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10401 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10402 FoundRHS, Depth + 1); 10403 }; 10404 10405 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10406 // We want to avoid creation of any new non-constant SCEV. Since we are 10407 // going to compare the operands to RHS, we should be certain that we don't 10408 // need any size extensions for this. So let's decline all cases when the 10409 // sizes of types of LHS and RHS do not match. 10410 // TODO: Maybe try to get RHS from sext to catch more cases? 10411 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10412 return false; 10413 10414 // Should not overflow. 10415 if (!LHSAddExpr->hasNoSignedWrap()) 10416 return false; 10417 10418 auto *LL = LHSAddExpr->getOperand(0); 10419 auto *LR = LHSAddExpr->getOperand(1); 10420 auto *MinusOne = getMinusOne(RHS->getType()); 10421 10422 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10423 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10424 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10425 }; 10426 // Try to prove the following rule: 10427 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10428 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10429 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10430 return true; 10431 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10432 Value *LL, *LR; 10433 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10434 10435 using namespace llvm::PatternMatch; 10436 10437 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10438 // Rules for division. 10439 // We are going to perform some comparisons with Denominator and its 10440 // derivative expressions. In general case, creating a SCEV for it may 10441 // lead to a complex analysis of the entire graph, and in particular it 10442 // can request trip count recalculation for the same loop. This would 10443 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10444 // this, we only want to create SCEVs that are constants in this section. 10445 // So we bail if Denominator is not a constant. 10446 if (!isa<ConstantInt>(LR)) 10447 return false; 10448 10449 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10450 10451 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10452 // then a SCEV for the numerator already exists and matches with FoundLHS. 10453 auto *Numerator = getExistingSCEV(LL); 10454 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10455 return false; 10456 10457 // Make sure that the numerator matches with FoundLHS and the denominator 10458 // is positive. 10459 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10460 return false; 10461 10462 auto *DTy = Denominator->getType(); 10463 auto *FRHSTy = FoundRHS->getType(); 10464 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10465 // One of types is a pointer and another one is not. We cannot extend 10466 // them properly to a wider type, so let us just reject this case. 10467 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10468 // to avoid this check. 10469 return false; 10470 10471 // Given that: 10472 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10473 auto *WTy = getWiderType(DTy, FRHSTy); 10474 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10475 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10476 10477 // Try to prove the following rule: 10478 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10479 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10480 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10481 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10482 if (isKnownNonPositive(RHS) && 10483 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10484 return true; 10485 10486 // Try to prove the following rule: 10487 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10488 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10489 // If we divide it by Denominator > 2, then: 10490 // 1. If FoundLHS is negative, then the result is 0. 10491 // 2. If FoundLHS is non-negative, then the result is non-negative. 10492 // Anyways, the result is non-negative. 10493 auto *MinusOne = getMinusOne(WTy); 10494 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10495 if (isKnownNegative(RHS) && 10496 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10497 return true; 10498 } 10499 } 10500 10501 // If our expression contained SCEVUnknown Phis, and we split it down and now 10502 // need to prove something for them, try to prove the predicate for every 10503 // possible incoming values of those Phis. 10504 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10505 return true; 10506 10507 return false; 10508 } 10509 10510 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10511 const SCEV *LHS, const SCEV *RHS) { 10512 // zext x u<= sext x, sext x s<= zext x 10513 switch (Pred) { 10514 case ICmpInst::ICMP_SGE: 10515 std::swap(LHS, RHS); 10516 LLVM_FALLTHROUGH; 10517 case ICmpInst::ICMP_SLE: { 10518 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10519 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10520 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10521 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10522 return true; 10523 break; 10524 } 10525 case ICmpInst::ICMP_UGE: 10526 std::swap(LHS, RHS); 10527 LLVM_FALLTHROUGH; 10528 case ICmpInst::ICMP_ULE: { 10529 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10530 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10531 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10532 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10533 return true; 10534 break; 10535 } 10536 default: 10537 break; 10538 }; 10539 return false; 10540 } 10541 10542 bool 10543 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10544 const SCEV *LHS, const SCEV *RHS) { 10545 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10546 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10547 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10548 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10549 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10550 } 10551 10552 bool 10553 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10554 const SCEV *LHS, const SCEV *RHS, 10555 const SCEV *FoundLHS, 10556 const SCEV *FoundRHS) { 10557 switch (Pred) { 10558 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10559 case ICmpInst::ICMP_EQ: 10560 case ICmpInst::ICMP_NE: 10561 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10562 return true; 10563 break; 10564 case ICmpInst::ICMP_SLT: 10565 case ICmpInst::ICMP_SLE: 10566 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10567 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10568 return true; 10569 break; 10570 case ICmpInst::ICMP_SGT: 10571 case ICmpInst::ICMP_SGE: 10572 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10573 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10574 return true; 10575 break; 10576 case ICmpInst::ICMP_ULT: 10577 case ICmpInst::ICMP_ULE: 10578 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10579 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10580 return true; 10581 break; 10582 case ICmpInst::ICMP_UGT: 10583 case ICmpInst::ICMP_UGE: 10584 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10585 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10586 return true; 10587 break; 10588 } 10589 10590 // Maybe it can be proved via operations? 10591 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10592 return true; 10593 10594 return false; 10595 } 10596 10597 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10598 const SCEV *LHS, 10599 const SCEV *RHS, 10600 const SCEV *FoundLHS, 10601 const SCEV *FoundRHS) { 10602 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10603 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10604 // reduce the compile time impact of this optimization. 10605 return false; 10606 10607 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10608 if (!Addend) 10609 return false; 10610 10611 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10612 10613 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10614 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10615 ConstantRange FoundLHSRange = 10616 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10617 10618 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10619 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10620 10621 // We can also compute the range of values for `LHS` that satisfy the 10622 // consequent, "`LHS` `Pred` `RHS`": 10623 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10624 ConstantRange SatisfyingLHSRange = 10625 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10626 10627 // The antecedent implies the consequent if every value of `LHS` that 10628 // satisfies the antecedent also satisfies the consequent. 10629 return SatisfyingLHSRange.contains(LHSRange); 10630 } 10631 10632 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10633 bool IsSigned, bool NoWrap) { 10634 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10635 10636 if (NoWrap) return false; 10637 10638 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10639 const SCEV *One = getOne(Stride->getType()); 10640 10641 if (IsSigned) { 10642 APInt MaxRHS = getSignedRangeMax(RHS); 10643 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10644 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10645 10646 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10647 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10648 } 10649 10650 APInt MaxRHS = getUnsignedRangeMax(RHS); 10651 APInt MaxValue = APInt::getMaxValue(BitWidth); 10652 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10653 10654 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10655 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10656 } 10657 10658 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10659 bool IsSigned, bool NoWrap) { 10660 if (NoWrap) return false; 10661 10662 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10663 const SCEV *One = getOne(Stride->getType()); 10664 10665 if (IsSigned) { 10666 APInt MinRHS = getSignedRangeMin(RHS); 10667 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10668 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10669 10670 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10671 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10672 } 10673 10674 APInt MinRHS = getUnsignedRangeMin(RHS); 10675 APInt MinValue = APInt::getMinValue(BitWidth); 10676 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10677 10678 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10679 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10680 } 10681 10682 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10683 bool Equality) { 10684 const SCEV *One = getOne(Step->getType()); 10685 Delta = Equality ? getAddExpr(Delta, Step) 10686 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10687 return getUDivExpr(Delta, Step); 10688 } 10689 10690 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10691 const SCEV *Stride, 10692 const SCEV *End, 10693 unsigned BitWidth, 10694 bool IsSigned) { 10695 10696 assert(!isKnownNonPositive(Stride) && 10697 "Stride is expected strictly positive!"); 10698 // Calculate the maximum backedge count based on the range of values 10699 // permitted by Start, End, and Stride. 10700 const SCEV *MaxBECount; 10701 APInt MinStart = 10702 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10703 10704 APInt StrideForMaxBECount = 10705 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10706 10707 // We already know that the stride is positive, so we paper over conservatism 10708 // in our range computation by forcing StrideForMaxBECount to be at least one. 10709 // In theory this is unnecessary, but we expect MaxBECount to be a 10710 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10711 // is nothing to constant fold it to). 10712 APInt One(BitWidth, 1, IsSigned); 10713 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10714 10715 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10716 : APInt::getMaxValue(BitWidth); 10717 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10718 10719 // Although End can be a MAX expression we estimate MaxEnd considering only 10720 // the case End = RHS of the loop termination condition. This is safe because 10721 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10722 // taken count. 10723 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10724 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10725 10726 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10727 getConstant(StrideForMaxBECount) /* Step */, 10728 false /* Equality */); 10729 10730 return MaxBECount; 10731 } 10732 10733 ScalarEvolution::ExitLimit 10734 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10735 const Loop *L, bool IsSigned, 10736 bool ControlsExit, bool AllowPredicates) { 10737 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10738 10739 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10740 bool PredicatedIV = false; 10741 10742 if (!IV && AllowPredicates) { 10743 // Try to make this an AddRec using runtime tests, in the first X 10744 // iterations of this loop, where X is the SCEV expression found by the 10745 // algorithm below. 10746 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10747 PredicatedIV = true; 10748 } 10749 10750 // Avoid weird loops 10751 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10752 return getCouldNotCompute(); 10753 10754 bool NoWrap = ControlsExit && 10755 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10756 10757 const SCEV *Stride = IV->getStepRecurrence(*this); 10758 10759 bool PositiveStride = isKnownPositive(Stride); 10760 10761 // Avoid negative or zero stride values. 10762 if (!PositiveStride) { 10763 // We can compute the correct backedge taken count for loops with unknown 10764 // strides if we can prove that the loop is not an infinite loop with side 10765 // effects. Here's the loop structure we are trying to handle - 10766 // 10767 // i = start 10768 // do { 10769 // A[i] = i; 10770 // i += s; 10771 // } while (i < end); 10772 // 10773 // The backedge taken count for such loops is evaluated as - 10774 // (max(end, start + stride) - start - 1) /u stride 10775 // 10776 // The additional preconditions that we need to check to prove correctness 10777 // of the above formula is as follows - 10778 // 10779 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10780 // NoWrap flag). 10781 // b) loop is single exit with no side effects. 10782 // 10783 // 10784 // Precondition a) implies that if the stride is negative, this is a single 10785 // trip loop. The backedge taken count formula reduces to zero in this case. 10786 // 10787 // Precondition b) implies that the unknown stride cannot be zero otherwise 10788 // we have UB. 10789 // 10790 // The positive stride case is the same as isKnownPositive(Stride) returning 10791 // true (original behavior of the function). 10792 // 10793 // We want to make sure that the stride is truly unknown as there are edge 10794 // cases where ScalarEvolution propagates no wrap flags to the 10795 // post-increment/decrement IV even though the increment/decrement operation 10796 // itself is wrapping. The computed backedge taken count may be wrong in 10797 // such cases. This is prevented by checking that the stride is not known to 10798 // be either positive or non-positive. For example, no wrap flags are 10799 // propagated to the post-increment IV of this loop with a trip count of 2 - 10800 // 10801 // unsigned char i; 10802 // for(i=127; i<128; i+=129) 10803 // A[i] = i; 10804 // 10805 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10806 !loopHasNoSideEffects(L)) 10807 return getCouldNotCompute(); 10808 } else if (!Stride->isOne() && 10809 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10810 // Avoid proven overflow cases: this will ensure that the backedge taken 10811 // count will not generate any unsigned overflow. Relaxed no-overflow 10812 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10813 // undefined behaviors like the case of C language. 10814 return getCouldNotCompute(); 10815 10816 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10817 : ICmpInst::ICMP_ULT; 10818 const SCEV *Start = IV->getStart(); 10819 const SCEV *End = RHS; 10820 // When the RHS is not invariant, we do not know the end bound of the loop and 10821 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10822 // calculate the MaxBECount, given the start, stride and max value for the end 10823 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10824 // checked above). 10825 if (!isLoopInvariant(RHS, L)) { 10826 const SCEV *MaxBECount = computeMaxBECountForLT( 10827 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10828 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10829 false /*MaxOrZero*/, Predicates); 10830 } 10831 // If the backedge is taken at least once, then it will be taken 10832 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10833 // is the LHS value of the less-than comparison the first time it is evaluated 10834 // and End is the RHS. 10835 const SCEV *BECountIfBackedgeTaken = 10836 computeBECount(getMinusSCEV(End, Start), Stride, false); 10837 // If the loop entry is guarded by the result of the backedge test of the 10838 // first loop iteration, then we know the backedge will be taken at least 10839 // once and so the backedge taken count is as above. If not then we use the 10840 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10841 // as if the backedge is taken at least once max(End,Start) is End and so the 10842 // result is as above, and if not max(End,Start) is Start so we get a backedge 10843 // count of zero. 10844 const SCEV *BECount; 10845 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10846 BECount = BECountIfBackedgeTaken; 10847 else { 10848 // If we know that RHS >= Start in the context of loop, then we know that 10849 // max(RHS, Start) = RHS at this point. 10850 if (isLoopEntryGuardedByCond( 10851 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 10852 End = RHS; 10853 else 10854 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10855 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10856 } 10857 10858 const SCEV *MaxBECount; 10859 bool MaxOrZero = false; 10860 if (isa<SCEVConstant>(BECount)) 10861 MaxBECount = BECount; 10862 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10863 // If we know exactly how many times the backedge will be taken if it's 10864 // taken at least once, then the backedge count will either be that or 10865 // zero. 10866 MaxBECount = BECountIfBackedgeTaken; 10867 MaxOrZero = true; 10868 } else { 10869 MaxBECount = computeMaxBECountForLT( 10870 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10871 } 10872 10873 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10874 !isa<SCEVCouldNotCompute>(BECount)) 10875 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10876 10877 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10878 } 10879 10880 ScalarEvolution::ExitLimit 10881 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10882 const Loop *L, bool IsSigned, 10883 bool ControlsExit, bool AllowPredicates) { 10884 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10885 // We handle only IV > Invariant 10886 if (!isLoopInvariant(RHS, L)) 10887 return getCouldNotCompute(); 10888 10889 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10890 if (!IV && AllowPredicates) 10891 // Try to make this an AddRec using runtime tests, in the first X 10892 // iterations of this loop, where X is the SCEV expression found by the 10893 // algorithm below. 10894 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10895 10896 // Avoid weird loops 10897 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10898 return getCouldNotCompute(); 10899 10900 bool NoWrap = ControlsExit && 10901 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10902 10903 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10904 10905 // Avoid negative or zero stride values 10906 if (!isKnownPositive(Stride)) 10907 return getCouldNotCompute(); 10908 10909 // Avoid proven overflow cases: this will ensure that the backedge taken count 10910 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10911 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10912 // behaviors like the case of C language. 10913 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10914 return getCouldNotCompute(); 10915 10916 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10917 : ICmpInst::ICMP_UGT; 10918 10919 const SCEV *Start = IV->getStart(); 10920 const SCEV *End = RHS; 10921 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 10922 // If we know that Start >= RHS in the context of loop, then we know that 10923 // min(RHS, Start) = RHS at this point. 10924 if (isLoopEntryGuardedByCond( 10925 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 10926 End = RHS; 10927 else 10928 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10929 } 10930 10931 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10932 10933 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10934 : getUnsignedRangeMax(Start); 10935 10936 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10937 : getUnsignedRangeMin(Stride); 10938 10939 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10940 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10941 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10942 10943 // Although End can be a MIN expression we estimate MinEnd considering only 10944 // the case End = RHS. This is safe because in the other case (Start - End) 10945 // is zero, leading to a zero maximum backedge taken count. 10946 APInt MinEnd = 10947 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10948 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10949 10950 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10951 ? BECount 10952 : computeBECount(getConstant(MaxStart - MinEnd), 10953 getConstant(MinStride), false); 10954 10955 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10956 MaxBECount = BECount; 10957 10958 return ExitLimit(BECount, MaxBECount, false, Predicates); 10959 } 10960 10961 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10962 ScalarEvolution &SE) const { 10963 if (Range.isFullSet()) // Infinite loop. 10964 return SE.getCouldNotCompute(); 10965 10966 // If the start is a non-zero constant, shift the range to simplify things. 10967 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10968 if (!SC->getValue()->isZero()) { 10969 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10970 Operands[0] = SE.getZero(SC->getType()); 10971 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10972 getNoWrapFlags(FlagNW)); 10973 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10974 return ShiftedAddRec->getNumIterationsInRange( 10975 Range.subtract(SC->getAPInt()), SE); 10976 // This is strange and shouldn't happen. 10977 return SE.getCouldNotCompute(); 10978 } 10979 10980 // The only time we can solve this is when we have all constant indices. 10981 // Otherwise, we cannot determine the overflow conditions. 10982 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10983 return SE.getCouldNotCompute(); 10984 10985 // Okay at this point we know that all elements of the chrec are constants and 10986 // that the start element is zero. 10987 10988 // First check to see if the range contains zero. If not, the first 10989 // iteration exits. 10990 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10991 if (!Range.contains(APInt(BitWidth, 0))) 10992 return SE.getZero(getType()); 10993 10994 if (isAffine()) { 10995 // If this is an affine expression then we have this situation: 10996 // Solve {0,+,A} in Range === Ax in Range 10997 10998 // We know that zero is in the range. If A is positive then we know that 10999 // the upper value of the range must be the first possible exit value. 11000 // If A is negative then the lower of the range is the last possible loop 11001 // value. Also note that we already checked for a full range. 11002 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11003 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11004 11005 // The exit value should be (End+A)/A. 11006 APInt ExitVal = (End + A).udiv(A); 11007 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11008 11009 // Evaluate at the exit value. If we really did fall out of the valid 11010 // range, then we computed our trip count, otherwise wrap around or other 11011 // things must have happened. 11012 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11013 if (Range.contains(Val->getValue())) 11014 return SE.getCouldNotCompute(); // Something strange happened 11015 11016 // Ensure that the previous value is in the range. This is a sanity check. 11017 assert(Range.contains( 11018 EvaluateConstantChrecAtConstant(this, 11019 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11020 "Linear scev computation is off in a bad way!"); 11021 return SE.getConstant(ExitValue); 11022 } 11023 11024 if (isQuadratic()) { 11025 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11026 return SE.getConstant(S.getValue()); 11027 } 11028 11029 return SE.getCouldNotCompute(); 11030 } 11031 11032 const SCEVAddRecExpr * 11033 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11034 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11035 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11036 // but in this case we cannot guarantee that the value returned will be an 11037 // AddRec because SCEV does not have a fixed point where it stops 11038 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11039 // may happen if we reach arithmetic depth limit while simplifying. So we 11040 // construct the returned value explicitly. 11041 SmallVector<const SCEV *, 3> Ops; 11042 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11043 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11044 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11045 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11046 // We know that the last operand is not a constant zero (otherwise it would 11047 // have been popped out earlier). This guarantees us that if the result has 11048 // the same last operand, then it will also not be popped out, meaning that 11049 // the returned value will be an AddRec. 11050 const SCEV *Last = getOperand(getNumOperands() - 1); 11051 assert(!Last->isZero() && "Recurrency with zero step?"); 11052 Ops.push_back(Last); 11053 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11054 SCEV::FlagAnyWrap)); 11055 } 11056 11057 // Return true when S contains at least an undef value. 11058 static inline bool containsUndefs(const SCEV *S) { 11059 return SCEVExprContains(S, [](const SCEV *S) { 11060 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11061 return isa<UndefValue>(SU->getValue()); 11062 return false; 11063 }); 11064 } 11065 11066 namespace { 11067 11068 // Collect all steps of SCEV expressions. 11069 struct SCEVCollectStrides { 11070 ScalarEvolution &SE; 11071 SmallVectorImpl<const SCEV *> &Strides; 11072 11073 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11074 : SE(SE), Strides(S) {} 11075 11076 bool follow(const SCEV *S) { 11077 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11078 Strides.push_back(AR->getStepRecurrence(SE)); 11079 return true; 11080 } 11081 11082 bool isDone() const { return false; } 11083 }; 11084 11085 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11086 struct SCEVCollectTerms { 11087 SmallVectorImpl<const SCEV *> &Terms; 11088 11089 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11090 11091 bool follow(const SCEV *S) { 11092 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11093 isa<SCEVSignExtendExpr>(S)) { 11094 if (!containsUndefs(S)) 11095 Terms.push_back(S); 11096 11097 // Stop recursion: once we collected a term, do not walk its operands. 11098 return false; 11099 } 11100 11101 // Keep looking. 11102 return true; 11103 } 11104 11105 bool isDone() const { return false; } 11106 }; 11107 11108 // Check if a SCEV contains an AddRecExpr. 11109 struct SCEVHasAddRec { 11110 bool &ContainsAddRec; 11111 11112 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11113 ContainsAddRec = false; 11114 } 11115 11116 bool follow(const SCEV *S) { 11117 if (isa<SCEVAddRecExpr>(S)) { 11118 ContainsAddRec = true; 11119 11120 // Stop recursion: once we collected a term, do not walk its operands. 11121 return false; 11122 } 11123 11124 // Keep looking. 11125 return true; 11126 } 11127 11128 bool isDone() const { return false; } 11129 }; 11130 11131 // Find factors that are multiplied with an expression that (possibly as a 11132 // subexpression) contains an AddRecExpr. In the expression: 11133 // 11134 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11135 // 11136 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11137 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11138 // parameters as they form a product with an induction variable. 11139 // 11140 // This collector expects all array size parameters to be in the same MulExpr. 11141 // It might be necessary to later add support for collecting parameters that are 11142 // spread over different nested MulExpr. 11143 struct SCEVCollectAddRecMultiplies { 11144 SmallVectorImpl<const SCEV *> &Terms; 11145 ScalarEvolution &SE; 11146 11147 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11148 : Terms(T), SE(SE) {} 11149 11150 bool follow(const SCEV *S) { 11151 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11152 bool HasAddRec = false; 11153 SmallVector<const SCEV *, 0> Operands; 11154 for (auto Op : Mul->operands()) { 11155 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11156 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11157 Operands.push_back(Op); 11158 } else if (Unknown) { 11159 HasAddRec = true; 11160 } else { 11161 bool ContainsAddRec = false; 11162 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11163 visitAll(Op, ContiansAddRec); 11164 HasAddRec |= ContainsAddRec; 11165 } 11166 } 11167 if (Operands.size() == 0) 11168 return true; 11169 11170 if (!HasAddRec) 11171 return false; 11172 11173 Terms.push_back(SE.getMulExpr(Operands)); 11174 // Stop recursion: once we collected a term, do not walk its operands. 11175 return false; 11176 } 11177 11178 // Keep looking. 11179 return true; 11180 } 11181 11182 bool isDone() const { return false; } 11183 }; 11184 11185 } // end anonymous namespace 11186 11187 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11188 /// two places: 11189 /// 1) The strides of AddRec expressions. 11190 /// 2) Unknowns that are multiplied with AddRec expressions. 11191 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11192 SmallVectorImpl<const SCEV *> &Terms) { 11193 SmallVector<const SCEV *, 4> Strides; 11194 SCEVCollectStrides StrideCollector(*this, Strides); 11195 visitAll(Expr, StrideCollector); 11196 11197 LLVM_DEBUG({ 11198 dbgs() << "Strides:\n"; 11199 for (const SCEV *S : Strides) 11200 dbgs() << *S << "\n"; 11201 }); 11202 11203 for (const SCEV *S : Strides) { 11204 SCEVCollectTerms TermCollector(Terms); 11205 visitAll(S, TermCollector); 11206 } 11207 11208 LLVM_DEBUG({ 11209 dbgs() << "Terms:\n"; 11210 for (const SCEV *T : Terms) 11211 dbgs() << *T << "\n"; 11212 }); 11213 11214 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11215 visitAll(Expr, MulCollector); 11216 } 11217 11218 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11219 SmallVectorImpl<const SCEV *> &Terms, 11220 SmallVectorImpl<const SCEV *> &Sizes) { 11221 int Last = Terms.size() - 1; 11222 const SCEV *Step = Terms[Last]; 11223 11224 // End of recursion. 11225 if (Last == 0) { 11226 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11227 SmallVector<const SCEV *, 2> Qs; 11228 for (const SCEV *Op : M->operands()) 11229 if (!isa<SCEVConstant>(Op)) 11230 Qs.push_back(Op); 11231 11232 Step = SE.getMulExpr(Qs); 11233 } 11234 11235 Sizes.push_back(Step); 11236 return true; 11237 } 11238 11239 for (const SCEV *&Term : Terms) { 11240 // Normalize the terms before the next call to findArrayDimensionsRec. 11241 const SCEV *Q, *R; 11242 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11243 11244 // Bail out when GCD does not evenly divide one of the terms. 11245 if (!R->isZero()) 11246 return false; 11247 11248 Term = Q; 11249 } 11250 11251 // Remove all SCEVConstants. 11252 Terms.erase( 11253 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11254 Terms.end()); 11255 11256 if (Terms.size() > 0) 11257 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11258 return false; 11259 11260 Sizes.push_back(Step); 11261 return true; 11262 } 11263 11264 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11265 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11266 for (const SCEV *T : Terms) 11267 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11268 return true; 11269 11270 return false; 11271 } 11272 11273 // Return the number of product terms in S. 11274 static inline int numberOfTerms(const SCEV *S) { 11275 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11276 return Expr->getNumOperands(); 11277 return 1; 11278 } 11279 11280 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11281 if (isa<SCEVConstant>(T)) 11282 return nullptr; 11283 11284 if (isa<SCEVUnknown>(T)) 11285 return T; 11286 11287 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11288 SmallVector<const SCEV *, 2> Factors; 11289 for (const SCEV *Op : M->operands()) 11290 if (!isa<SCEVConstant>(Op)) 11291 Factors.push_back(Op); 11292 11293 return SE.getMulExpr(Factors); 11294 } 11295 11296 return T; 11297 } 11298 11299 /// Return the size of an element read or written by Inst. 11300 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11301 Type *Ty; 11302 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11303 Ty = Store->getValueOperand()->getType(); 11304 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11305 Ty = Load->getType(); 11306 else 11307 return nullptr; 11308 11309 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11310 return getSizeOfExpr(ETy, Ty); 11311 } 11312 11313 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11314 SmallVectorImpl<const SCEV *> &Sizes, 11315 const SCEV *ElementSize) { 11316 if (Terms.size() < 1 || !ElementSize) 11317 return; 11318 11319 // Early return when Terms do not contain parameters: we do not delinearize 11320 // non parametric SCEVs. 11321 if (!containsParameters(Terms)) 11322 return; 11323 11324 LLVM_DEBUG({ 11325 dbgs() << "Terms:\n"; 11326 for (const SCEV *T : Terms) 11327 dbgs() << *T << "\n"; 11328 }); 11329 11330 // Remove duplicates. 11331 array_pod_sort(Terms.begin(), Terms.end()); 11332 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11333 11334 // Put larger terms first. 11335 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11336 return numberOfTerms(LHS) > numberOfTerms(RHS); 11337 }); 11338 11339 // Try to divide all terms by the element size. If term is not divisible by 11340 // element size, proceed with the original term. 11341 for (const SCEV *&Term : Terms) { 11342 const SCEV *Q, *R; 11343 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11344 if (!Q->isZero()) 11345 Term = Q; 11346 } 11347 11348 SmallVector<const SCEV *, 4> NewTerms; 11349 11350 // Remove constant factors. 11351 for (const SCEV *T : Terms) 11352 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11353 NewTerms.push_back(NewT); 11354 11355 LLVM_DEBUG({ 11356 dbgs() << "Terms after sorting:\n"; 11357 for (const SCEV *T : NewTerms) 11358 dbgs() << *T << "\n"; 11359 }); 11360 11361 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11362 Sizes.clear(); 11363 return; 11364 } 11365 11366 // The last element to be pushed into Sizes is the size of an element. 11367 Sizes.push_back(ElementSize); 11368 11369 LLVM_DEBUG({ 11370 dbgs() << "Sizes:\n"; 11371 for (const SCEV *S : Sizes) 11372 dbgs() << *S << "\n"; 11373 }); 11374 } 11375 11376 void ScalarEvolution::computeAccessFunctions( 11377 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11378 SmallVectorImpl<const SCEV *> &Sizes) { 11379 // Early exit in case this SCEV is not an affine multivariate function. 11380 if (Sizes.empty()) 11381 return; 11382 11383 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11384 if (!AR->isAffine()) 11385 return; 11386 11387 const SCEV *Res = Expr; 11388 int Last = Sizes.size() - 1; 11389 for (int i = Last; i >= 0; i--) { 11390 const SCEV *Q, *R; 11391 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11392 11393 LLVM_DEBUG({ 11394 dbgs() << "Res: " << *Res << "\n"; 11395 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11396 dbgs() << "Res divided by Sizes[i]:\n"; 11397 dbgs() << "Quotient: " << *Q << "\n"; 11398 dbgs() << "Remainder: " << *R << "\n"; 11399 }); 11400 11401 Res = Q; 11402 11403 // Do not record the last subscript corresponding to the size of elements in 11404 // the array. 11405 if (i == Last) { 11406 11407 // Bail out if the remainder is too complex. 11408 if (isa<SCEVAddRecExpr>(R)) { 11409 Subscripts.clear(); 11410 Sizes.clear(); 11411 return; 11412 } 11413 11414 continue; 11415 } 11416 11417 // Record the access function for the current subscript. 11418 Subscripts.push_back(R); 11419 } 11420 11421 // Also push in last position the remainder of the last division: it will be 11422 // the access function of the innermost dimension. 11423 Subscripts.push_back(Res); 11424 11425 std::reverse(Subscripts.begin(), Subscripts.end()); 11426 11427 LLVM_DEBUG({ 11428 dbgs() << "Subscripts:\n"; 11429 for (const SCEV *S : Subscripts) 11430 dbgs() << *S << "\n"; 11431 }); 11432 } 11433 11434 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11435 /// sizes of an array access. Returns the remainder of the delinearization that 11436 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11437 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11438 /// expressions in the stride and base of a SCEV corresponding to the 11439 /// computation of a GCD (greatest common divisor) of base and stride. When 11440 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11441 /// 11442 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11443 /// 11444 /// void foo(long n, long m, long o, double A[n][m][o]) { 11445 /// 11446 /// for (long i = 0; i < n; i++) 11447 /// for (long j = 0; j < m; j++) 11448 /// for (long k = 0; k < o; k++) 11449 /// A[i][j][k] = 1.0; 11450 /// } 11451 /// 11452 /// the delinearization input is the following AddRec SCEV: 11453 /// 11454 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11455 /// 11456 /// From this SCEV, we are able to say that the base offset of the access is %A 11457 /// because it appears as an offset that does not divide any of the strides in 11458 /// the loops: 11459 /// 11460 /// CHECK: Base offset: %A 11461 /// 11462 /// and then SCEV->delinearize determines the size of some of the dimensions of 11463 /// the array as these are the multiples by which the strides are happening: 11464 /// 11465 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11466 /// 11467 /// Note that the outermost dimension remains of UnknownSize because there are 11468 /// no strides that would help identifying the size of the last dimension: when 11469 /// the array has been statically allocated, one could compute the size of that 11470 /// dimension by dividing the overall size of the array by the size of the known 11471 /// dimensions: %m * %o * 8. 11472 /// 11473 /// Finally delinearize provides the access functions for the array reference 11474 /// that does correspond to A[i][j][k] of the above C testcase: 11475 /// 11476 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11477 /// 11478 /// The testcases are checking the output of a function pass: 11479 /// DelinearizationPass that walks through all loads and stores of a function 11480 /// asking for the SCEV of the memory access with respect to all enclosing 11481 /// loops, calling SCEV->delinearize on that and printing the results. 11482 void ScalarEvolution::delinearize(const SCEV *Expr, 11483 SmallVectorImpl<const SCEV *> &Subscripts, 11484 SmallVectorImpl<const SCEV *> &Sizes, 11485 const SCEV *ElementSize) { 11486 // First step: collect parametric terms. 11487 SmallVector<const SCEV *, 4> Terms; 11488 collectParametricTerms(Expr, Terms); 11489 11490 if (Terms.empty()) 11491 return; 11492 11493 // Second step: find subscript sizes. 11494 findArrayDimensions(Terms, Sizes, ElementSize); 11495 11496 if (Sizes.empty()) 11497 return; 11498 11499 // Third step: compute the access functions for each subscript. 11500 computeAccessFunctions(Expr, Subscripts, Sizes); 11501 11502 if (Subscripts.empty()) 11503 return; 11504 11505 LLVM_DEBUG({ 11506 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11507 dbgs() << "ArrayDecl[UnknownSize]"; 11508 for (const SCEV *S : Sizes) 11509 dbgs() << "[" << *S << "]"; 11510 11511 dbgs() << "\nArrayRef"; 11512 for (const SCEV *S : Subscripts) 11513 dbgs() << "[" << *S << "]"; 11514 dbgs() << "\n"; 11515 }); 11516 } 11517 11518 bool ScalarEvolution::getIndexExpressionsFromGEP( 11519 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11520 SmallVectorImpl<int> &Sizes) { 11521 assert(Subscripts.empty() && Sizes.empty() && 11522 "Expected output lists to be empty on entry to this function."); 11523 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11524 Type *Ty = GEP->getPointerOperandType(); 11525 bool DroppedFirstDim = false; 11526 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11527 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11528 if (i == 1) { 11529 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11530 Ty = PtrTy->getElementType(); 11531 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11532 Ty = ArrayTy->getElementType(); 11533 } else { 11534 Subscripts.clear(); 11535 Sizes.clear(); 11536 return false; 11537 } 11538 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11539 if (Const->getValue()->isZero()) { 11540 DroppedFirstDim = true; 11541 continue; 11542 } 11543 Subscripts.push_back(Expr); 11544 continue; 11545 } 11546 11547 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11548 if (!ArrayTy) { 11549 Subscripts.clear(); 11550 Sizes.clear(); 11551 return false; 11552 } 11553 11554 Subscripts.push_back(Expr); 11555 if (!(DroppedFirstDim && i == 2)) 11556 Sizes.push_back(ArrayTy->getNumElements()); 11557 11558 Ty = ArrayTy->getElementType(); 11559 } 11560 return !Subscripts.empty(); 11561 } 11562 11563 //===----------------------------------------------------------------------===// 11564 // SCEVCallbackVH Class Implementation 11565 //===----------------------------------------------------------------------===// 11566 11567 void ScalarEvolution::SCEVCallbackVH::deleted() { 11568 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11569 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11570 SE->ConstantEvolutionLoopExitValue.erase(PN); 11571 SE->eraseValueFromMap(getValPtr()); 11572 // this now dangles! 11573 } 11574 11575 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11576 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11577 11578 // Forget all the expressions associated with users of the old value, 11579 // so that future queries will recompute the expressions using the new 11580 // value. 11581 Value *Old = getValPtr(); 11582 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11583 SmallPtrSet<User *, 8> Visited; 11584 while (!Worklist.empty()) { 11585 User *U = Worklist.pop_back_val(); 11586 // Deleting the Old value will cause this to dangle. Postpone 11587 // that until everything else is done. 11588 if (U == Old) 11589 continue; 11590 if (!Visited.insert(U).second) 11591 continue; 11592 if (PHINode *PN = dyn_cast<PHINode>(U)) 11593 SE->ConstantEvolutionLoopExitValue.erase(PN); 11594 SE->eraseValueFromMap(U); 11595 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11596 } 11597 // Delete the Old value. 11598 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11599 SE->ConstantEvolutionLoopExitValue.erase(PN); 11600 SE->eraseValueFromMap(Old); 11601 // this now dangles! 11602 } 11603 11604 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11605 : CallbackVH(V), SE(se) {} 11606 11607 //===----------------------------------------------------------------------===// 11608 // ScalarEvolution Class Implementation 11609 //===----------------------------------------------------------------------===// 11610 11611 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11612 AssumptionCache &AC, DominatorTree &DT, 11613 LoopInfo &LI) 11614 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11615 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11616 LoopDispositions(64), BlockDispositions(64) { 11617 // To use guards for proving predicates, we need to scan every instruction in 11618 // relevant basic blocks, and not just terminators. Doing this is a waste of 11619 // time if the IR does not actually contain any calls to 11620 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11621 // 11622 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11623 // to _add_ guards to the module when there weren't any before, and wants 11624 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11625 // efficient in lieu of being smart in that rather obscure case. 11626 11627 auto *GuardDecl = F.getParent()->getFunction( 11628 Intrinsic::getName(Intrinsic::experimental_guard)); 11629 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11630 } 11631 11632 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11633 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11634 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11635 ValueExprMap(std::move(Arg.ValueExprMap)), 11636 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11637 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11638 PendingMerges(std::move(Arg.PendingMerges)), 11639 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11640 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11641 PredicatedBackedgeTakenCounts( 11642 std::move(Arg.PredicatedBackedgeTakenCounts)), 11643 ConstantEvolutionLoopExitValue( 11644 std::move(Arg.ConstantEvolutionLoopExitValue)), 11645 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11646 LoopDispositions(std::move(Arg.LoopDispositions)), 11647 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11648 BlockDispositions(std::move(Arg.BlockDispositions)), 11649 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11650 SignedRanges(std::move(Arg.SignedRanges)), 11651 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11652 UniquePreds(std::move(Arg.UniquePreds)), 11653 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11654 LoopUsers(std::move(Arg.LoopUsers)), 11655 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11656 FirstUnknown(Arg.FirstUnknown) { 11657 Arg.FirstUnknown = nullptr; 11658 } 11659 11660 ScalarEvolution::~ScalarEvolution() { 11661 // Iterate through all the SCEVUnknown instances and call their 11662 // destructors, so that they release their references to their values. 11663 for (SCEVUnknown *U = FirstUnknown; U;) { 11664 SCEVUnknown *Tmp = U; 11665 U = U->Next; 11666 Tmp->~SCEVUnknown(); 11667 } 11668 FirstUnknown = nullptr; 11669 11670 ExprValueMap.clear(); 11671 ValueExprMap.clear(); 11672 HasRecMap.clear(); 11673 11674 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11675 // that a loop had multiple computable exits. 11676 for (auto &BTCI : BackedgeTakenCounts) 11677 BTCI.second.clear(); 11678 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11679 BTCI.second.clear(); 11680 11681 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11682 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11683 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11684 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11685 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11686 } 11687 11688 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11689 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11690 } 11691 11692 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11693 const Loop *L) { 11694 // Print all inner loops first 11695 for (Loop *I : *L) 11696 PrintLoopInfo(OS, SE, I); 11697 11698 OS << "Loop "; 11699 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11700 OS << ": "; 11701 11702 SmallVector<BasicBlock *, 8> ExitingBlocks; 11703 L->getExitingBlocks(ExitingBlocks); 11704 if (ExitingBlocks.size() != 1) 11705 OS << "<multiple exits> "; 11706 11707 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11708 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11709 else 11710 OS << "Unpredictable backedge-taken count.\n"; 11711 11712 if (ExitingBlocks.size() > 1) 11713 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11714 OS << " exit count for " << ExitingBlock->getName() << ": " 11715 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11716 } 11717 11718 OS << "Loop "; 11719 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11720 OS << ": "; 11721 11722 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11723 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11724 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11725 OS << ", actual taken count either this or zero."; 11726 } else { 11727 OS << "Unpredictable max backedge-taken count. "; 11728 } 11729 11730 OS << "\n" 11731 "Loop "; 11732 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11733 OS << ": "; 11734 11735 SCEVUnionPredicate Pred; 11736 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11737 if (!isa<SCEVCouldNotCompute>(PBT)) { 11738 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11739 OS << " Predicates:\n"; 11740 Pred.print(OS, 4); 11741 } else { 11742 OS << "Unpredictable predicated backedge-taken count. "; 11743 } 11744 OS << "\n"; 11745 11746 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11747 OS << "Loop "; 11748 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11749 OS << ": "; 11750 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11751 } 11752 } 11753 11754 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11755 switch (LD) { 11756 case ScalarEvolution::LoopVariant: 11757 return "Variant"; 11758 case ScalarEvolution::LoopInvariant: 11759 return "Invariant"; 11760 case ScalarEvolution::LoopComputable: 11761 return "Computable"; 11762 } 11763 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11764 } 11765 11766 void ScalarEvolution::print(raw_ostream &OS) const { 11767 // ScalarEvolution's implementation of the print method is to print 11768 // out SCEV values of all instructions that are interesting. Doing 11769 // this potentially causes it to create new SCEV objects though, 11770 // which technically conflicts with the const qualifier. This isn't 11771 // observable from outside the class though, so casting away the 11772 // const isn't dangerous. 11773 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11774 11775 if (ClassifyExpressions) { 11776 OS << "Classifying expressions for: "; 11777 F.printAsOperand(OS, /*PrintType=*/false); 11778 OS << "\n"; 11779 for (Instruction &I : instructions(F)) 11780 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11781 OS << I << '\n'; 11782 OS << " --> "; 11783 const SCEV *SV = SE.getSCEV(&I); 11784 SV->print(OS); 11785 if (!isa<SCEVCouldNotCompute>(SV)) { 11786 OS << " U: "; 11787 SE.getUnsignedRange(SV).print(OS); 11788 OS << " S: "; 11789 SE.getSignedRange(SV).print(OS); 11790 } 11791 11792 const Loop *L = LI.getLoopFor(I.getParent()); 11793 11794 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11795 if (AtUse != SV) { 11796 OS << " --> "; 11797 AtUse->print(OS); 11798 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11799 OS << " U: "; 11800 SE.getUnsignedRange(AtUse).print(OS); 11801 OS << " S: "; 11802 SE.getSignedRange(AtUse).print(OS); 11803 } 11804 } 11805 11806 if (L) { 11807 OS << "\t\t" "Exits: "; 11808 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11809 if (!SE.isLoopInvariant(ExitValue, L)) { 11810 OS << "<<Unknown>>"; 11811 } else { 11812 OS << *ExitValue; 11813 } 11814 11815 bool First = true; 11816 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11817 if (First) { 11818 OS << "\t\t" "LoopDispositions: { "; 11819 First = false; 11820 } else { 11821 OS << ", "; 11822 } 11823 11824 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11825 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11826 } 11827 11828 for (auto *InnerL : depth_first(L)) { 11829 if (InnerL == L) 11830 continue; 11831 if (First) { 11832 OS << "\t\t" "LoopDispositions: { "; 11833 First = false; 11834 } else { 11835 OS << ", "; 11836 } 11837 11838 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11839 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11840 } 11841 11842 OS << " }"; 11843 } 11844 11845 OS << "\n"; 11846 } 11847 } 11848 11849 OS << "Determining loop execution counts for: "; 11850 F.printAsOperand(OS, /*PrintType=*/false); 11851 OS << "\n"; 11852 for (Loop *I : LI) 11853 PrintLoopInfo(OS, &SE, I); 11854 } 11855 11856 ScalarEvolution::LoopDisposition 11857 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11858 auto &Values = LoopDispositions[S]; 11859 for (auto &V : Values) { 11860 if (V.getPointer() == L) 11861 return V.getInt(); 11862 } 11863 Values.emplace_back(L, LoopVariant); 11864 LoopDisposition D = computeLoopDisposition(S, L); 11865 auto &Values2 = LoopDispositions[S]; 11866 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11867 if (V.getPointer() == L) { 11868 V.setInt(D); 11869 break; 11870 } 11871 } 11872 return D; 11873 } 11874 11875 ScalarEvolution::LoopDisposition 11876 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11877 switch (S->getSCEVType()) { 11878 case scConstant: 11879 return LoopInvariant; 11880 case scTruncate: 11881 case scZeroExtend: 11882 case scSignExtend: 11883 return getLoopDisposition(cast<SCEVIntegralCastExpr>(S)->getOperand(), L); 11884 case scAddRecExpr: { 11885 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11886 11887 // If L is the addrec's loop, it's computable. 11888 if (AR->getLoop() == L) 11889 return LoopComputable; 11890 11891 // Add recurrences are never invariant in the function-body (null loop). 11892 if (!L) 11893 return LoopVariant; 11894 11895 // Everything that is not defined at loop entry is variant. 11896 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11897 return LoopVariant; 11898 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11899 " dominate the contained loop's header?"); 11900 11901 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11902 if (AR->getLoop()->contains(L)) 11903 return LoopInvariant; 11904 11905 // This recurrence is variant w.r.t. L if any of its operands 11906 // are variant. 11907 for (auto *Op : AR->operands()) 11908 if (!isLoopInvariant(Op, L)) 11909 return LoopVariant; 11910 11911 // Otherwise it's loop-invariant. 11912 return LoopInvariant; 11913 } 11914 case scAddExpr: 11915 case scMulExpr: 11916 case scUMaxExpr: 11917 case scSMaxExpr: 11918 case scUMinExpr: 11919 case scSMinExpr: { 11920 bool HasVarying = false; 11921 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11922 LoopDisposition D = getLoopDisposition(Op, L); 11923 if (D == LoopVariant) 11924 return LoopVariant; 11925 if (D == LoopComputable) 11926 HasVarying = true; 11927 } 11928 return HasVarying ? LoopComputable : LoopInvariant; 11929 } 11930 case scUDivExpr: { 11931 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11932 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11933 if (LD == LoopVariant) 11934 return LoopVariant; 11935 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11936 if (RD == LoopVariant) 11937 return LoopVariant; 11938 return (LD == LoopInvariant && RD == LoopInvariant) ? 11939 LoopInvariant : LoopComputable; 11940 } 11941 case scUnknown: 11942 // All non-instruction values are loop invariant. All instructions are loop 11943 // invariant if they are not contained in the specified loop. 11944 // Instructions are never considered invariant in the function body 11945 // (null loop) because they are defined within the "loop". 11946 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11947 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11948 return LoopInvariant; 11949 case scCouldNotCompute: 11950 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11951 } 11952 llvm_unreachable("Unknown SCEV kind!"); 11953 } 11954 11955 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11956 return getLoopDisposition(S, L) == LoopInvariant; 11957 } 11958 11959 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11960 return getLoopDisposition(S, L) == LoopComputable; 11961 } 11962 11963 ScalarEvolution::BlockDisposition 11964 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11965 auto &Values = BlockDispositions[S]; 11966 for (auto &V : Values) { 11967 if (V.getPointer() == BB) 11968 return V.getInt(); 11969 } 11970 Values.emplace_back(BB, DoesNotDominateBlock); 11971 BlockDisposition D = computeBlockDisposition(S, BB); 11972 auto &Values2 = BlockDispositions[S]; 11973 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11974 if (V.getPointer() == BB) { 11975 V.setInt(D); 11976 break; 11977 } 11978 } 11979 return D; 11980 } 11981 11982 ScalarEvolution::BlockDisposition 11983 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11984 switch (S->getSCEVType()) { 11985 case scConstant: 11986 return ProperlyDominatesBlock; 11987 case scTruncate: 11988 case scZeroExtend: 11989 case scSignExtend: 11990 return getBlockDisposition(cast<SCEVIntegralCastExpr>(S)->getOperand(), BB); 11991 case scAddRecExpr: { 11992 // This uses a "dominates" query instead of "properly dominates" query 11993 // to test for proper dominance too, because the instruction which 11994 // produces the addrec's value is a PHI, and a PHI effectively properly 11995 // dominates its entire containing block. 11996 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11997 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11998 return DoesNotDominateBlock; 11999 12000 // Fall through into SCEVNAryExpr handling. 12001 LLVM_FALLTHROUGH; 12002 } 12003 case scAddExpr: 12004 case scMulExpr: 12005 case scUMaxExpr: 12006 case scSMaxExpr: 12007 case scUMinExpr: 12008 case scSMinExpr: { 12009 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12010 bool Proper = true; 12011 for (const SCEV *NAryOp : NAry->operands()) { 12012 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12013 if (D == DoesNotDominateBlock) 12014 return DoesNotDominateBlock; 12015 if (D == DominatesBlock) 12016 Proper = false; 12017 } 12018 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12019 } 12020 case scUDivExpr: { 12021 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12022 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12023 BlockDisposition LD = getBlockDisposition(LHS, BB); 12024 if (LD == DoesNotDominateBlock) 12025 return DoesNotDominateBlock; 12026 BlockDisposition RD = getBlockDisposition(RHS, BB); 12027 if (RD == DoesNotDominateBlock) 12028 return DoesNotDominateBlock; 12029 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12030 ProperlyDominatesBlock : DominatesBlock; 12031 } 12032 case scUnknown: 12033 if (Instruction *I = 12034 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12035 if (I->getParent() == BB) 12036 return DominatesBlock; 12037 if (DT.properlyDominates(I->getParent(), BB)) 12038 return ProperlyDominatesBlock; 12039 return DoesNotDominateBlock; 12040 } 12041 return ProperlyDominatesBlock; 12042 case scCouldNotCompute: 12043 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12044 } 12045 llvm_unreachable("Unknown SCEV kind!"); 12046 } 12047 12048 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12049 return getBlockDisposition(S, BB) >= DominatesBlock; 12050 } 12051 12052 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12053 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12054 } 12055 12056 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12057 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12058 } 12059 12060 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 12061 auto IsS = [&](const SCEV *X) { return S == X; }; 12062 auto ContainsS = [&](const SCEV *X) { 12063 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12064 }; 12065 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12066 } 12067 12068 void 12069 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12070 ValuesAtScopes.erase(S); 12071 LoopDispositions.erase(S); 12072 BlockDispositions.erase(S); 12073 UnsignedRanges.erase(S); 12074 SignedRanges.erase(S); 12075 ExprValueMap.erase(S); 12076 HasRecMap.erase(S); 12077 MinTrailingZerosCache.erase(S); 12078 12079 for (auto I = PredicatedSCEVRewrites.begin(); 12080 I != PredicatedSCEVRewrites.end();) { 12081 std::pair<const SCEV *, const Loop *> Entry = I->first; 12082 if (Entry.first == S) 12083 PredicatedSCEVRewrites.erase(I++); 12084 else 12085 ++I; 12086 } 12087 12088 auto RemoveSCEVFromBackedgeMap = 12089 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12090 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12091 BackedgeTakenInfo &BEInfo = I->second; 12092 if (BEInfo.hasOperand(S, this)) { 12093 BEInfo.clear(); 12094 Map.erase(I++); 12095 } else 12096 ++I; 12097 } 12098 }; 12099 12100 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12101 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12102 } 12103 12104 void 12105 ScalarEvolution::getUsedLoops(const SCEV *S, 12106 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12107 struct FindUsedLoops { 12108 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12109 : LoopsUsed(LoopsUsed) {} 12110 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12111 bool follow(const SCEV *S) { 12112 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12113 LoopsUsed.insert(AR->getLoop()); 12114 return true; 12115 } 12116 12117 bool isDone() const { return false; } 12118 }; 12119 12120 FindUsedLoops F(LoopsUsed); 12121 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12122 } 12123 12124 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12125 SmallPtrSet<const Loop *, 8> LoopsUsed; 12126 getUsedLoops(S, LoopsUsed); 12127 for (auto *L : LoopsUsed) 12128 LoopUsers[L].push_back(S); 12129 } 12130 12131 void ScalarEvolution::verify() const { 12132 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12133 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12134 12135 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12136 12137 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12138 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12139 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12140 12141 const SCEV *visitConstant(const SCEVConstant *Constant) { 12142 return SE.getConstant(Constant->getAPInt()); 12143 } 12144 12145 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12146 return SE.getUnknown(Expr->getValue()); 12147 } 12148 12149 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12150 return SE.getCouldNotCompute(); 12151 } 12152 }; 12153 12154 SCEVMapper SCM(SE2); 12155 12156 while (!LoopStack.empty()) { 12157 auto *L = LoopStack.pop_back_val(); 12158 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12159 12160 auto *CurBECount = SCM.visit( 12161 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12162 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12163 12164 if (CurBECount == SE2.getCouldNotCompute() || 12165 NewBECount == SE2.getCouldNotCompute()) { 12166 // NB! This situation is legal, but is very suspicious -- whatever pass 12167 // change the loop to make a trip count go from could not compute to 12168 // computable or vice-versa *should have* invalidated SCEV. However, we 12169 // choose not to assert here (for now) since we don't want false 12170 // positives. 12171 continue; 12172 } 12173 12174 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12175 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12176 // not propagate undef aggressively). This means we can (and do) fail 12177 // verification in cases where a transform makes the trip count of a loop 12178 // go from "undef" to "undef+1" (say). The transform is fine, since in 12179 // both cases the loop iterates "undef" times, but SCEV thinks we 12180 // increased the trip count of the loop by 1 incorrectly. 12181 continue; 12182 } 12183 12184 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12185 SE.getTypeSizeInBits(NewBECount->getType())) 12186 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12187 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12188 SE.getTypeSizeInBits(NewBECount->getType())) 12189 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12190 12191 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12192 12193 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12194 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12195 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12196 dbgs() << "Old: " << *CurBECount << "\n"; 12197 dbgs() << "New: " << *NewBECount << "\n"; 12198 dbgs() << "Delta: " << *Delta << "\n"; 12199 std::abort(); 12200 } 12201 } 12202 12203 // Collect all valid loops currently in LoopInfo. 12204 SmallPtrSet<Loop *, 32> ValidLoops; 12205 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12206 while (!Worklist.empty()) { 12207 Loop *L = Worklist.pop_back_val(); 12208 if (ValidLoops.contains(L)) 12209 continue; 12210 ValidLoops.insert(L); 12211 Worklist.append(L->begin(), L->end()); 12212 } 12213 // Check for SCEV expressions referencing invalid/deleted loops. 12214 for (auto &KV : ValueExprMap) { 12215 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12216 if (!AR) 12217 continue; 12218 assert(ValidLoops.contains(AR->getLoop()) && 12219 "AddRec references invalid loop"); 12220 } 12221 } 12222 12223 bool ScalarEvolution::invalidate( 12224 Function &F, const PreservedAnalyses &PA, 12225 FunctionAnalysisManager::Invalidator &Inv) { 12226 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12227 // of its dependencies is invalidated. 12228 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12229 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12230 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12231 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12232 Inv.invalidate<LoopAnalysis>(F, PA); 12233 } 12234 12235 AnalysisKey ScalarEvolutionAnalysis::Key; 12236 12237 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12238 FunctionAnalysisManager &AM) { 12239 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12240 AM.getResult<AssumptionAnalysis>(F), 12241 AM.getResult<DominatorTreeAnalysis>(F), 12242 AM.getResult<LoopAnalysis>(F)); 12243 } 12244 12245 PreservedAnalyses 12246 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12247 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12248 return PreservedAnalyses::all(); 12249 } 12250 12251 PreservedAnalyses 12252 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12253 // For compatibility with opt's -analyze feature under legacy pass manager 12254 // which was not ported to NPM. This keeps tests using 12255 // update_analyze_test_checks.py working. 12256 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12257 << F.getName() << "':\n"; 12258 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12259 return PreservedAnalyses::all(); 12260 } 12261 12262 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12263 "Scalar Evolution Analysis", false, true) 12264 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12265 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12266 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12267 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12268 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12269 "Scalar Evolution Analysis", false, true) 12270 12271 char ScalarEvolutionWrapperPass::ID = 0; 12272 12273 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12274 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12275 } 12276 12277 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12278 SE.reset(new ScalarEvolution( 12279 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12280 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12281 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12282 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12283 return false; 12284 } 12285 12286 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12287 12288 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12289 SE->print(OS); 12290 } 12291 12292 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12293 if (!VerifySCEV) 12294 return; 12295 12296 SE->verify(); 12297 } 12298 12299 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12300 AU.setPreservesAll(); 12301 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12302 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12303 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12304 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12305 } 12306 12307 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12308 const SCEV *RHS) { 12309 FoldingSetNodeID ID; 12310 assert(LHS->getType() == RHS->getType() && 12311 "Type mismatch between LHS and RHS"); 12312 // Unique this node based on the arguments 12313 ID.AddInteger(SCEVPredicate::P_Equal); 12314 ID.AddPointer(LHS); 12315 ID.AddPointer(RHS); 12316 void *IP = nullptr; 12317 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12318 return S; 12319 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12320 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12321 UniquePreds.InsertNode(Eq, IP); 12322 return Eq; 12323 } 12324 12325 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12326 const SCEVAddRecExpr *AR, 12327 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12328 FoldingSetNodeID ID; 12329 // Unique this node based on the arguments 12330 ID.AddInteger(SCEVPredicate::P_Wrap); 12331 ID.AddPointer(AR); 12332 ID.AddInteger(AddedFlags); 12333 void *IP = nullptr; 12334 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12335 return S; 12336 auto *OF = new (SCEVAllocator) 12337 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12338 UniquePreds.InsertNode(OF, IP); 12339 return OF; 12340 } 12341 12342 namespace { 12343 12344 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12345 public: 12346 12347 /// Rewrites \p S in the context of a loop L and the SCEV predication 12348 /// infrastructure. 12349 /// 12350 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12351 /// equivalences present in \p Pred. 12352 /// 12353 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12354 /// \p NewPreds such that the result will be an AddRecExpr. 12355 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12356 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12357 SCEVUnionPredicate *Pred) { 12358 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12359 return Rewriter.visit(S); 12360 } 12361 12362 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12363 if (Pred) { 12364 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12365 for (auto *Pred : ExprPreds) 12366 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12367 if (IPred->getLHS() == Expr) 12368 return IPred->getRHS(); 12369 } 12370 return convertToAddRecWithPreds(Expr); 12371 } 12372 12373 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12374 const SCEV *Operand = visit(Expr->getOperand()); 12375 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12376 if (AR && AR->getLoop() == L && AR->isAffine()) { 12377 // This couldn't be folded because the operand didn't have the nuw 12378 // flag. Add the nusw flag as an assumption that we could make. 12379 const SCEV *Step = AR->getStepRecurrence(SE); 12380 Type *Ty = Expr->getType(); 12381 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12382 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12383 SE.getSignExtendExpr(Step, Ty), L, 12384 AR->getNoWrapFlags()); 12385 } 12386 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12387 } 12388 12389 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12390 const SCEV *Operand = visit(Expr->getOperand()); 12391 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12392 if (AR && AR->getLoop() == L && AR->isAffine()) { 12393 // This couldn't be folded because the operand didn't have the nsw 12394 // flag. Add the nssw flag as an assumption that we could make. 12395 const SCEV *Step = AR->getStepRecurrence(SE); 12396 Type *Ty = Expr->getType(); 12397 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12398 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12399 SE.getSignExtendExpr(Step, Ty), L, 12400 AR->getNoWrapFlags()); 12401 } 12402 return SE.getSignExtendExpr(Operand, Expr->getType()); 12403 } 12404 12405 private: 12406 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12407 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12408 SCEVUnionPredicate *Pred) 12409 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12410 12411 bool addOverflowAssumption(const SCEVPredicate *P) { 12412 if (!NewPreds) { 12413 // Check if we've already made this assumption. 12414 return Pred && Pred->implies(P); 12415 } 12416 NewPreds->insert(P); 12417 return true; 12418 } 12419 12420 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12421 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12422 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12423 return addOverflowAssumption(A); 12424 } 12425 12426 // If \p Expr represents a PHINode, we try to see if it can be represented 12427 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12428 // to add this predicate as a runtime overflow check, we return the AddRec. 12429 // If \p Expr does not meet these conditions (is not a PHI node, or we 12430 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12431 // return \p Expr. 12432 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12433 if (!isa<PHINode>(Expr->getValue())) 12434 return Expr; 12435 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12436 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12437 if (!PredicatedRewrite) 12438 return Expr; 12439 for (auto *P : PredicatedRewrite->second){ 12440 // Wrap predicates from outer loops are not supported. 12441 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12442 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12443 if (L != AR->getLoop()) 12444 return Expr; 12445 } 12446 if (!addOverflowAssumption(P)) 12447 return Expr; 12448 } 12449 return PredicatedRewrite->first; 12450 } 12451 12452 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12453 SCEVUnionPredicate *Pred; 12454 const Loop *L; 12455 }; 12456 12457 } // end anonymous namespace 12458 12459 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12460 SCEVUnionPredicate &Preds) { 12461 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12462 } 12463 12464 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12465 const SCEV *S, const Loop *L, 12466 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12467 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12468 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12469 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12470 12471 if (!AddRec) 12472 return nullptr; 12473 12474 // Since the transformation was successful, we can now transfer the SCEV 12475 // predicates. 12476 for (auto *P : TransformPreds) 12477 Preds.insert(P); 12478 12479 return AddRec; 12480 } 12481 12482 /// SCEV predicates 12483 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12484 SCEVPredicateKind Kind) 12485 : FastID(ID), Kind(Kind) {} 12486 12487 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12488 const SCEV *LHS, const SCEV *RHS) 12489 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12490 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12491 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12492 } 12493 12494 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12495 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12496 12497 if (!Op) 12498 return false; 12499 12500 return Op->LHS == LHS && Op->RHS == RHS; 12501 } 12502 12503 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12504 12505 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12506 12507 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12508 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12509 } 12510 12511 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12512 const SCEVAddRecExpr *AR, 12513 IncrementWrapFlags Flags) 12514 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12515 12516 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12517 12518 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12519 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12520 12521 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12522 } 12523 12524 bool SCEVWrapPredicate::isAlwaysTrue() const { 12525 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12526 IncrementWrapFlags IFlags = Flags; 12527 12528 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12529 IFlags = clearFlags(IFlags, IncrementNSSW); 12530 12531 return IFlags == IncrementAnyWrap; 12532 } 12533 12534 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12535 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12536 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12537 OS << "<nusw>"; 12538 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12539 OS << "<nssw>"; 12540 OS << "\n"; 12541 } 12542 12543 SCEVWrapPredicate::IncrementWrapFlags 12544 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12545 ScalarEvolution &SE) { 12546 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12547 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12548 12549 // We can safely transfer the NSW flag as NSSW. 12550 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12551 ImpliedFlags = IncrementNSSW; 12552 12553 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12554 // If the increment is positive, the SCEV NUW flag will also imply the 12555 // WrapPredicate NUSW flag. 12556 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12557 if (Step->getValue()->getValue().isNonNegative()) 12558 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12559 } 12560 12561 return ImpliedFlags; 12562 } 12563 12564 /// Union predicates don't get cached so create a dummy set ID for it. 12565 SCEVUnionPredicate::SCEVUnionPredicate() 12566 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12567 12568 bool SCEVUnionPredicate::isAlwaysTrue() const { 12569 return all_of(Preds, 12570 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12571 } 12572 12573 ArrayRef<const SCEVPredicate *> 12574 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12575 auto I = SCEVToPreds.find(Expr); 12576 if (I == SCEVToPreds.end()) 12577 return ArrayRef<const SCEVPredicate *>(); 12578 return I->second; 12579 } 12580 12581 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12582 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12583 return all_of(Set->Preds, 12584 [this](const SCEVPredicate *I) { return this->implies(I); }); 12585 12586 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12587 if (ScevPredsIt == SCEVToPreds.end()) 12588 return false; 12589 auto &SCEVPreds = ScevPredsIt->second; 12590 12591 return any_of(SCEVPreds, 12592 [N](const SCEVPredicate *I) { return I->implies(N); }); 12593 } 12594 12595 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12596 12597 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12598 for (auto Pred : Preds) 12599 Pred->print(OS, Depth); 12600 } 12601 12602 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12603 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12604 for (auto Pred : Set->Preds) 12605 add(Pred); 12606 return; 12607 } 12608 12609 if (implies(N)) 12610 return; 12611 12612 const SCEV *Key = N->getExpr(); 12613 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12614 " associated expression!"); 12615 12616 SCEVToPreds[Key].push_back(N); 12617 Preds.push_back(N); 12618 } 12619 12620 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12621 Loop &L) 12622 : SE(SE), L(L) {} 12623 12624 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12625 const SCEV *Expr = SE.getSCEV(V); 12626 RewriteEntry &Entry = RewriteMap[Expr]; 12627 12628 // If we already have an entry and the version matches, return it. 12629 if (Entry.second && Generation == Entry.first) 12630 return Entry.second; 12631 12632 // We found an entry but it's stale. Rewrite the stale entry 12633 // according to the current predicate. 12634 if (Entry.second) 12635 Expr = Entry.second; 12636 12637 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12638 Entry = {Generation, NewSCEV}; 12639 12640 return NewSCEV; 12641 } 12642 12643 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12644 if (!BackedgeCount) { 12645 SCEVUnionPredicate BackedgePred; 12646 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12647 addPredicate(BackedgePred); 12648 } 12649 return BackedgeCount; 12650 } 12651 12652 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12653 if (Preds.implies(&Pred)) 12654 return; 12655 Preds.add(&Pred); 12656 updateGeneration(); 12657 } 12658 12659 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12660 return Preds; 12661 } 12662 12663 void PredicatedScalarEvolution::updateGeneration() { 12664 // If the generation number wrapped recompute everything. 12665 if (++Generation == 0) { 12666 for (auto &II : RewriteMap) { 12667 const SCEV *Rewritten = II.second.second; 12668 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12669 } 12670 } 12671 } 12672 12673 void PredicatedScalarEvolution::setNoOverflow( 12674 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12675 const SCEV *Expr = getSCEV(V); 12676 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12677 12678 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12679 12680 // Clear the statically implied flags. 12681 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12682 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12683 12684 auto II = FlagsMap.insert({V, Flags}); 12685 if (!II.second) 12686 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12687 } 12688 12689 bool PredicatedScalarEvolution::hasNoOverflow( 12690 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12691 const SCEV *Expr = getSCEV(V); 12692 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12693 12694 Flags = SCEVWrapPredicate::clearFlags( 12695 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12696 12697 auto II = FlagsMap.find(V); 12698 12699 if (II != FlagsMap.end()) 12700 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12701 12702 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12703 } 12704 12705 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12706 const SCEV *Expr = this->getSCEV(V); 12707 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12708 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12709 12710 if (!New) 12711 return nullptr; 12712 12713 for (auto *P : NewPreds) 12714 Preds.add(P); 12715 12716 updateGeneration(); 12717 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12718 return New; 12719 } 12720 12721 PredicatedScalarEvolution::PredicatedScalarEvolution( 12722 const PredicatedScalarEvolution &Init) 12723 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12724 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12725 for (auto I : Init.FlagsMap) 12726 FlagsMap.insert(I); 12727 } 12728 12729 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12730 // For each block. 12731 for (auto *BB : L.getBlocks()) 12732 for (auto &I : *BB) { 12733 if (!SE.isSCEVable(I.getType())) 12734 continue; 12735 12736 auto *Expr = SE.getSCEV(&I); 12737 auto II = RewriteMap.find(Expr); 12738 12739 if (II == RewriteMap.end()) 12740 continue; 12741 12742 // Don't print things that are not interesting. 12743 if (II->second.second == Expr) 12744 continue; 12745 12746 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12747 OS.indent(Depth + 2) << *Expr << "\n"; 12748 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12749 } 12750 } 12751 12752 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12753 // arbitrary expressions. 12754 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12755 // 4, A / B becomes X / 8). 12756 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12757 const SCEV *&RHS) { 12758 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12759 if (Add == nullptr || Add->getNumOperands() != 2) 12760 return false; 12761 12762 const SCEV *A = Add->getOperand(1); 12763 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12764 12765 if (Mul == nullptr) 12766 return false; 12767 12768 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12769 // (SomeExpr + (-(SomeExpr / B) * B)). 12770 if (Expr == getURemExpr(A, B)) { 12771 LHS = A; 12772 RHS = B; 12773 return true; 12774 } 12775 return false; 12776 }; 12777 12778 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12779 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12780 return MatchURemWithDivisor(Mul->getOperand(1)) || 12781 MatchURemWithDivisor(Mul->getOperand(2)); 12782 12783 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12784 if (Mul->getNumOperands() == 2) 12785 return MatchURemWithDivisor(Mul->getOperand(1)) || 12786 MatchURemWithDivisor(Mul->getOperand(0)) || 12787 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12788 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12789 return false; 12790 } 12791 12792 const SCEV* ScalarEvolution::computeMaxBackedgeTakenCount(const Loop *L) { 12793 SmallVector<BasicBlock*, 16> ExitingBlocks; 12794 L->getExitingBlocks(ExitingBlocks); 12795 12796 // Form an expression for the maximum exit count possible for this loop. We 12797 // merge the max and exact information to approximate a version of 12798 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 12799 SmallVector<const SCEV*, 4> ExitCounts; 12800 for (BasicBlock *ExitingBB : ExitingBlocks) { 12801 const SCEV *ExitCount = getExitCount(L, ExitingBB); 12802 if (isa<SCEVCouldNotCompute>(ExitCount)) 12803 ExitCount = getExitCount(L, ExitingBB, 12804 ScalarEvolution::ConstantMaximum); 12805 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 12806 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 12807 "We should only have known counts for exiting blocks that " 12808 "dominate latch!"); 12809 ExitCounts.push_back(ExitCount); 12810 } 12811 } 12812 if (ExitCounts.empty()) 12813 return getCouldNotCompute(); 12814 return getUMinFromMismatchedTypes(ExitCounts); 12815 } 12816 12817 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 12818 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 12819 /// we cannot guarantee that the replacement is loop invariant in the loop of 12820 /// the AddRec. 12821 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 12822 ValueToSCEVMapTy ⤅ 12823 12824 public: 12825 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 12826 : SCEVRewriteVisitor(SE), Map(M) {} 12827 12828 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 12829 12830 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12831 auto I = Map.find(Expr->getValue()); 12832 if (I == Map.end()) 12833 return Expr; 12834 return I->second; 12835 } 12836 }; 12837 12838 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 12839 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 12840 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 12841 if (!isa<SCEVUnknown>(LHS)) { 12842 std::swap(LHS, RHS); 12843 Predicate = CmpInst::getSwappedPredicate(Predicate); 12844 } 12845 12846 // For now, limit to conditions that provide information about unknown 12847 // expressions. 12848 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 12849 if (!LHSUnknown) 12850 return; 12851 12852 // TODO: use information from more predicates. 12853 switch (Predicate) { 12854 case CmpInst::ICMP_ULT: { 12855 if (!containsAddRecurrence(RHS)) { 12856 const SCEV *Base = LHS; 12857 auto I = RewriteMap.find(LHSUnknown->getValue()); 12858 if (I != RewriteMap.end()) 12859 Base = I->second; 12860 12861 RewriteMap[LHSUnknown->getValue()] = 12862 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 12863 } 12864 break; 12865 } 12866 case CmpInst::ICMP_ULE: { 12867 if (!containsAddRecurrence(RHS)) { 12868 const SCEV *Base = LHS; 12869 auto I = RewriteMap.find(LHSUnknown->getValue()); 12870 if (I != RewriteMap.end()) 12871 Base = I->second; 12872 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 12873 } 12874 break; 12875 } 12876 case CmpInst::ICMP_EQ: 12877 if (isa<SCEVConstant>(RHS)) 12878 RewriteMap[LHSUnknown->getValue()] = RHS; 12879 break; 12880 case CmpInst::ICMP_NE: 12881 if (isa<SCEVConstant>(RHS) && 12882 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 12883 RewriteMap[LHSUnknown->getValue()] = 12884 getUMaxExpr(LHS, getOne(RHS->getType())); 12885 break; 12886 default: 12887 break; 12888 } 12889 }; 12890 // Starting at the loop predecessor, climb up the predecessor chain, as long 12891 // as there are predecessors that can be found that have unique successors 12892 // leading to the original header. 12893 // TODO: share this logic with isLoopEntryGuardedByCond. 12894 ValueToSCEVMapTy RewriteMap; 12895 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 12896 L->getLoopPredecessor(), L->getHeader()); 12897 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 12898 12899 const BranchInst *LoopEntryPredicate = 12900 dyn_cast<BranchInst>(Pair.first->getTerminator()); 12901 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 12902 continue; 12903 12904 // TODO: use information from more complex conditions, e.g. AND expressions. 12905 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 12906 if (!Cmp) 12907 continue; 12908 12909 auto Predicate = Cmp->getPredicate(); 12910 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 12911 Predicate = CmpInst::getInversePredicate(Predicate); 12912 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 12913 getSCEV(Cmp->getOperand(1)), RewriteMap); 12914 } 12915 12916 // Also collect information from assumptions dominating the loop. 12917 for (auto &AssumeVH : AC.assumptions()) { 12918 if (!AssumeVH) 12919 continue; 12920 auto *AssumeI = cast<CallInst>(AssumeVH); 12921 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 12922 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 12923 continue; 12924 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 12925 getSCEV(Cmp->getOperand(1)), RewriteMap); 12926 } 12927 12928 if (RewriteMap.empty()) 12929 return Expr; 12930 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 12931 return Rewriter.visit(Expr); 12932 } 12933