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 5532 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5533 } 5534 5535 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5536 // Check if the IR explicitly contains !range metadata. 5537 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5538 if (MDRange.hasValue()) 5539 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5540 RangeType); 5541 5542 // Split here to avoid paying the compile-time cost of calling both 5543 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5544 // if needed. 5545 const DataLayout &DL = getDataLayout(); 5546 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5547 // For a SCEVUnknown, ask ValueTracking. 5548 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5549 if (Known.getBitWidth() != BitWidth) 5550 Known = Known.zextOrTrunc(BitWidth); 5551 // If Known does not result in full-set, intersect with it. 5552 if (Known.getMinValue() != Known.getMaxValue() + 1) 5553 ConservativeResult = ConservativeResult.intersectWith( 5554 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5555 RangeType); 5556 } else { 5557 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5558 "generalize as needed!"); 5559 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5560 // If the pointer size is larger than the index size type, this can cause 5561 // NS to be larger than BitWidth. So compensate for this. 5562 if (U->getType()->isPointerTy()) { 5563 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5564 int ptrIdxDiff = ptrSize - BitWidth; 5565 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5566 NS -= ptrIdxDiff; 5567 } 5568 5569 if (NS > 1) 5570 ConservativeResult = ConservativeResult.intersectWith( 5571 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5572 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5573 RangeType); 5574 } 5575 5576 // A range of Phi is a subset of union of all ranges of its input. 5577 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5578 // Make sure that we do not run over cycled Phis. 5579 if (PendingPhiRanges.insert(Phi).second) { 5580 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5581 for (auto &Op : Phi->operands()) { 5582 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5583 RangeFromOps = RangeFromOps.unionWith(OpRange); 5584 // No point to continue if we already have a full set. 5585 if (RangeFromOps.isFullSet()) 5586 break; 5587 } 5588 ConservativeResult = 5589 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5590 bool Erased = PendingPhiRanges.erase(Phi); 5591 assert(Erased && "Failed to erase Phi properly?"); 5592 (void) Erased; 5593 } 5594 } 5595 5596 return setRange(U, SignHint, std::move(ConservativeResult)); 5597 } 5598 5599 return setRange(S, SignHint, std::move(ConservativeResult)); 5600 } 5601 5602 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5603 // values that the expression can take. Initially, the expression has a value 5604 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5605 // argument defines if we treat Step as signed or unsigned. 5606 static ConstantRange getRangeForAffineARHelper(APInt Step, 5607 const ConstantRange &StartRange, 5608 const APInt &MaxBECount, 5609 unsigned BitWidth, bool Signed) { 5610 // If either Step or MaxBECount is 0, then the expression won't change, and we 5611 // just need to return the initial range. 5612 if (Step == 0 || MaxBECount == 0) 5613 return StartRange; 5614 5615 // If we don't know anything about the initial value (i.e. StartRange is 5616 // FullRange), then we don't know anything about the final range either. 5617 // Return FullRange. 5618 if (StartRange.isFullSet()) 5619 return ConstantRange::getFull(BitWidth); 5620 5621 // If Step is signed and negative, then we use its absolute value, but we also 5622 // note that we're moving in the opposite direction. 5623 bool Descending = Signed && Step.isNegative(); 5624 5625 if (Signed) 5626 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5627 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5628 // This equations hold true due to the well-defined wrap-around behavior of 5629 // APInt. 5630 Step = Step.abs(); 5631 5632 // Check if Offset is more than full span of BitWidth. If it is, the 5633 // expression is guaranteed to overflow. 5634 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5635 return ConstantRange::getFull(BitWidth); 5636 5637 // Offset is by how much the expression can change. Checks above guarantee no 5638 // overflow here. 5639 APInt Offset = Step * MaxBECount; 5640 5641 // Minimum value of the final range will match the minimal value of StartRange 5642 // if the expression is increasing and will be decreased by Offset otherwise. 5643 // Maximum value of the final range will match the maximal value of StartRange 5644 // if the expression is decreasing and will be increased by Offset otherwise. 5645 APInt StartLower = StartRange.getLower(); 5646 APInt StartUpper = StartRange.getUpper() - 1; 5647 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5648 : (StartUpper + std::move(Offset)); 5649 5650 // It's possible that the new minimum/maximum value will fall into the initial 5651 // range (due to wrap around). This means that the expression can take any 5652 // value in this bitwidth, and we have to return full range. 5653 if (StartRange.contains(MovedBoundary)) 5654 return ConstantRange::getFull(BitWidth); 5655 5656 APInt NewLower = 5657 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5658 APInt NewUpper = 5659 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5660 NewUpper += 1; 5661 5662 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5663 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5664 } 5665 5666 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5667 const SCEV *Step, 5668 const SCEV *MaxBECount, 5669 unsigned BitWidth) { 5670 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5671 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5672 "Precondition!"); 5673 5674 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5675 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5676 5677 // First, consider step signed. 5678 ConstantRange StartSRange = getSignedRange(Start); 5679 ConstantRange StepSRange = getSignedRange(Step); 5680 5681 // If Step can be both positive and negative, we need to find ranges for the 5682 // maximum absolute step values in both directions and union them. 5683 ConstantRange SR = 5684 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5685 MaxBECountValue, BitWidth, /* Signed = */ true); 5686 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5687 StartSRange, MaxBECountValue, 5688 BitWidth, /* Signed = */ true)); 5689 5690 // Next, consider step unsigned. 5691 ConstantRange UR = getRangeForAffineARHelper( 5692 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5693 MaxBECountValue, BitWidth, /* Signed = */ false); 5694 5695 // Finally, intersect signed and unsigned ranges. 5696 return SR.intersectWith(UR, ConstantRange::Smallest); 5697 } 5698 5699 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5700 const SCEV *Step, 5701 const SCEV *MaxBECount, 5702 unsigned BitWidth) { 5703 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5704 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5705 5706 struct SelectPattern { 5707 Value *Condition = nullptr; 5708 APInt TrueValue; 5709 APInt FalseValue; 5710 5711 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5712 const SCEV *S) { 5713 Optional<unsigned> CastOp; 5714 APInt Offset(BitWidth, 0); 5715 5716 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5717 "Should be!"); 5718 5719 // Peel off a constant offset: 5720 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5721 // In the future we could consider being smarter here and handle 5722 // {Start+Step,+,Step} too. 5723 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5724 return; 5725 5726 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5727 S = SA->getOperand(1); 5728 } 5729 5730 // Peel off a cast operation 5731 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 5732 CastOp = SCast->getSCEVType(); 5733 S = SCast->getOperand(); 5734 } 5735 5736 using namespace llvm::PatternMatch; 5737 5738 auto *SU = dyn_cast<SCEVUnknown>(S); 5739 const APInt *TrueVal, *FalseVal; 5740 if (!SU || 5741 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5742 m_APInt(FalseVal)))) { 5743 Condition = nullptr; 5744 return; 5745 } 5746 5747 TrueValue = *TrueVal; 5748 FalseValue = *FalseVal; 5749 5750 // Re-apply the cast we peeled off earlier 5751 if (CastOp.hasValue()) 5752 switch (*CastOp) { 5753 default: 5754 llvm_unreachable("Unknown SCEV cast type!"); 5755 5756 case scTruncate: 5757 TrueValue = TrueValue.trunc(BitWidth); 5758 FalseValue = FalseValue.trunc(BitWidth); 5759 break; 5760 case scZeroExtend: 5761 TrueValue = TrueValue.zext(BitWidth); 5762 FalseValue = FalseValue.zext(BitWidth); 5763 break; 5764 case scSignExtend: 5765 TrueValue = TrueValue.sext(BitWidth); 5766 FalseValue = FalseValue.sext(BitWidth); 5767 break; 5768 } 5769 5770 // Re-apply the constant offset we peeled off earlier 5771 TrueValue += Offset; 5772 FalseValue += Offset; 5773 } 5774 5775 bool isRecognized() { return Condition != nullptr; } 5776 }; 5777 5778 SelectPattern StartPattern(*this, BitWidth, Start); 5779 if (!StartPattern.isRecognized()) 5780 return ConstantRange::getFull(BitWidth); 5781 5782 SelectPattern StepPattern(*this, BitWidth, Step); 5783 if (!StepPattern.isRecognized()) 5784 return ConstantRange::getFull(BitWidth); 5785 5786 if (StartPattern.Condition != StepPattern.Condition) { 5787 // We don't handle this case today; but we could, by considering four 5788 // possibilities below instead of two. I'm not sure if there are cases where 5789 // that will help over what getRange already does, though. 5790 return ConstantRange::getFull(BitWidth); 5791 } 5792 5793 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5794 // construct arbitrary general SCEV expressions here. This function is called 5795 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5796 // say) can end up caching a suboptimal value. 5797 5798 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5799 // C2352 and C2512 (otherwise it isn't needed). 5800 5801 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5802 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5803 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5804 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5805 5806 ConstantRange TrueRange = 5807 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5808 ConstantRange FalseRange = 5809 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5810 5811 return TrueRange.unionWith(FalseRange); 5812 } 5813 5814 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5815 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5816 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5817 5818 // Return early if there are no flags to propagate to the SCEV. 5819 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5820 if (BinOp->hasNoUnsignedWrap()) 5821 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5822 if (BinOp->hasNoSignedWrap()) 5823 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5824 if (Flags == SCEV::FlagAnyWrap) 5825 return SCEV::FlagAnyWrap; 5826 5827 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5828 } 5829 5830 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5831 // Here we check that I is in the header of the innermost loop containing I, 5832 // since we only deal with instructions in the loop header. The actual loop we 5833 // need to check later will come from an add recurrence, but getting that 5834 // requires computing the SCEV of the operands, which can be expensive. This 5835 // check we can do cheaply to rule out some cases early. 5836 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5837 if (InnermostContainingLoop == nullptr || 5838 InnermostContainingLoop->getHeader() != I->getParent()) 5839 return false; 5840 5841 // Only proceed if we can prove that I does not yield poison. 5842 if (!programUndefinedIfPoison(I)) 5843 return false; 5844 5845 // At this point we know that if I is executed, then it does not wrap 5846 // according to at least one of NSW or NUW. If I is not executed, then we do 5847 // not know if the calculation that I represents would wrap. Multiple 5848 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5849 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5850 // derived from other instructions that map to the same SCEV. We cannot make 5851 // that guarantee for cases where I is not executed. So we need to find the 5852 // loop that I is considered in relation to and prove that I is executed for 5853 // every iteration of that loop. That implies that the value that I 5854 // calculates does not wrap anywhere in the loop, so then we can apply the 5855 // flags to the SCEV. 5856 // 5857 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5858 // from different loops, so that we know which loop to prove that I is 5859 // executed in. 5860 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5861 // I could be an extractvalue from a call to an overflow intrinsic. 5862 // TODO: We can do better here in some cases. 5863 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5864 return false; 5865 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5866 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5867 bool AllOtherOpsLoopInvariant = true; 5868 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5869 ++OtherOpIndex) { 5870 if (OtherOpIndex != OpIndex) { 5871 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5872 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5873 AllOtherOpsLoopInvariant = false; 5874 break; 5875 } 5876 } 5877 } 5878 if (AllOtherOpsLoopInvariant && 5879 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5880 return true; 5881 } 5882 } 5883 return false; 5884 } 5885 5886 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5887 // If we know that \c I can never be poison period, then that's enough. 5888 if (isSCEVExprNeverPoison(I)) 5889 return true; 5890 5891 // For an add recurrence specifically, we assume that infinite loops without 5892 // side effects are undefined behavior, and then reason as follows: 5893 // 5894 // If the add recurrence is poison in any iteration, it is poison on all 5895 // future iterations (since incrementing poison yields poison). If the result 5896 // of the add recurrence is fed into the loop latch condition and the loop 5897 // does not contain any throws or exiting blocks other than the latch, we now 5898 // have the ability to "choose" whether the backedge is taken or not (by 5899 // choosing a sufficiently evil value for the poison feeding into the branch) 5900 // for every iteration including and after the one in which \p I first became 5901 // poison. There are two possibilities (let's call the iteration in which \p 5902 // I first became poison as K): 5903 // 5904 // 1. In the set of iterations including and after K, the loop body executes 5905 // no side effects. In this case executing the backege an infinte number 5906 // of times will yield undefined behavior. 5907 // 5908 // 2. In the set of iterations including and after K, the loop body executes 5909 // at least one side effect. In this case, that specific instance of side 5910 // effect is control dependent on poison, which also yields undefined 5911 // behavior. 5912 5913 auto *ExitingBB = L->getExitingBlock(); 5914 auto *LatchBB = L->getLoopLatch(); 5915 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5916 return false; 5917 5918 SmallPtrSet<const Instruction *, 16> Pushed; 5919 SmallVector<const Instruction *, 8> PoisonStack; 5920 5921 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5922 // things that are known to be poison under that assumption go on the 5923 // PoisonStack. 5924 Pushed.insert(I); 5925 PoisonStack.push_back(I); 5926 5927 bool LatchControlDependentOnPoison = false; 5928 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5929 const Instruction *Poison = PoisonStack.pop_back_val(); 5930 5931 for (auto *PoisonUser : Poison->users()) { 5932 if (propagatesPoison(cast<Operator>(PoisonUser))) { 5933 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5934 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5935 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5936 assert(BI->isConditional() && "Only possibility!"); 5937 if (BI->getParent() == LatchBB) { 5938 LatchControlDependentOnPoison = true; 5939 break; 5940 } 5941 } 5942 } 5943 } 5944 5945 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5946 } 5947 5948 ScalarEvolution::LoopProperties 5949 ScalarEvolution::getLoopProperties(const Loop *L) { 5950 using LoopProperties = ScalarEvolution::LoopProperties; 5951 5952 auto Itr = LoopPropertiesCache.find(L); 5953 if (Itr == LoopPropertiesCache.end()) { 5954 auto HasSideEffects = [](Instruction *I) { 5955 if (auto *SI = dyn_cast<StoreInst>(I)) 5956 return !SI->isSimple(); 5957 5958 return I->mayHaveSideEffects(); 5959 }; 5960 5961 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5962 /*HasNoSideEffects*/ true}; 5963 5964 for (auto *BB : L->getBlocks()) 5965 for (auto &I : *BB) { 5966 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5967 LP.HasNoAbnormalExits = false; 5968 if (HasSideEffects(&I)) 5969 LP.HasNoSideEffects = false; 5970 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5971 break; // We're already as pessimistic as we can get. 5972 } 5973 5974 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5975 assert(InsertPair.second && "We just checked!"); 5976 Itr = InsertPair.first; 5977 } 5978 5979 return Itr->second; 5980 } 5981 5982 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5983 if (!isSCEVable(V->getType())) 5984 return getUnknown(V); 5985 5986 if (Instruction *I = dyn_cast<Instruction>(V)) { 5987 // Don't attempt to analyze instructions in blocks that aren't 5988 // reachable. Such instructions don't matter, and they aren't required 5989 // to obey basic rules for definitions dominating uses which this 5990 // analysis depends on. 5991 if (!DT.isReachableFromEntry(I->getParent())) 5992 return getUnknown(UndefValue::get(V->getType())); 5993 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5994 return getConstant(CI); 5995 else if (isa<ConstantPointerNull>(V)) 5996 return getZero(V->getType()); 5997 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5998 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5999 else if (!isa<ConstantExpr>(V)) 6000 return getUnknown(V); 6001 6002 Operator *U = cast<Operator>(V); 6003 if (auto BO = MatchBinaryOp(U, DT)) { 6004 switch (BO->Opcode) { 6005 case Instruction::Add: { 6006 // The simple thing to do would be to just call getSCEV on both operands 6007 // and call getAddExpr with the result. However if we're looking at a 6008 // bunch of things all added together, this can be quite inefficient, 6009 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6010 // Instead, gather up all the operands and make a single getAddExpr call. 6011 // LLVM IR canonical form means we need only traverse the left operands. 6012 SmallVector<const SCEV *, 4> AddOps; 6013 do { 6014 if (BO->Op) { 6015 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6016 AddOps.push_back(OpSCEV); 6017 break; 6018 } 6019 6020 // If a NUW or NSW flag can be applied to the SCEV for this 6021 // addition, then compute the SCEV for this addition by itself 6022 // with a separate call to getAddExpr. We need to do that 6023 // instead of pushing the operands of the addition onto AddOps, 6024 // since the flags are only known to apply to this particular 6025 // addition - they may not apply to other additions that can be 6026 // formed with operands from AddOps. 6027 const SCEV *RHS = getSCEV(BO->RHS); 6028 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6029 if (Flags != SCEV::FlagAnyWrap) { 6030 const SCEV *LHS = getSCEV(BO->LHS); 6031 if (BO->Opcode == Instruction::Sub) 6032 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6033 else 6034 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6035 break; 6036 } 6037 } 6038 6039 if (BO->Opcode == Instruction::Sub) 6040 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6041 else 6042 AddOps.push_back(getSCEV(BO->RHS)); 6043 6044 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6045 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6046 NewBO->Opcode != Instruction::Sub)) { 6047 AddOps.push_back(getSCEV(BO->LHS)); 6048 break; 6049 } 6050 BO = NewBO; 6051 } while (true); 6052 6053 return getAddExpr(AddOps); 6054 } 6055 6056 case Instruction::Mul: { 6057 SmallVector<const SCEV *, 4> MulOps; 6058 do { 6059 if (BO->Op) { 6060 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6061 MulOps.push_back(OpSCEV); 6062 break; 6063 } 6064 6065 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6066 if (Flags != SCEV::FlagAnyWrap) { 6067 MulOps.push_back( 6068 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6069 break; 6070 } 6071 } 6072 6073 MulOps.push_back(getSCEV(BO->RHS)); 6074 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6075 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6076 MulOps.push_back(getSCEV(BO->LHS)); 6077 break; 6078 } 6079 BO = NewBO; 6080 } while (true); 6081 6082 return getMulExpr(MulOps); 6083 } 6084 case Instruction::UDiv: 6085 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6086 case Instruction::URem: 6087 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6088 case Instruction::Sub: { 6089 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6090 if (BO->Op) 6091 Flags = getNoWrapFlagsFromUB(BO->Op); 6092 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6093 } 6094 case Instruction::And: 6095 // For an expression like x&255 that merely masks off the high bits, 6096 // use zext(trunc(x)) as the SCEV expression. 6097 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6098 if (CI->isZero()) 6099 return getSCEV(BO->RHS); 6100 if (CI->isMinusOne()) 6101 return getSCEV(BO->LHS); 6102 const APInt &A = CI->getValue(); 6103 6104 // Instcombine's ShrinkDemandedConstant may strip bits out of 6105 // constants, obscuring what would otherwise be a low-bits mask. 6106 // Use computeKnownBits to compute what ShrinkDemandedConstant 6107 // knew about to reconstruct a low-bits mask value. 6108 unsigned LZ = A.countLeadingZeros(); 6109 unsigned TZ = A.countTrailingZeros(); 6110 unsigned BitWidth = A.getBitWidth(); 6111 KnownBits Known(BitWidth); 6112 computeKnownBits(BO->LHS, Known, getDataLayout(), 6113 0, &AC, nullptr, &DT); 6114 6115 APInt EffectiveMask = 6116 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6117 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6118 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6119 const SCEV *LHS = getSCEV(BO->LHS); 6120 const SCEV *ShiftedLHS = nullptr; 6121 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6122 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6123 // For an expression like (x * 8) & 8, simplify the multiply. 6124 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6125 unsigned GCD = std::min(MulZeros, TZ); 6126 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6127 SmallVector<const SCEV*, 4> MulOps; 6128 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6129 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6130 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6131 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6132 } 6133 } 6134 if (!ShiftedLHS) 6135 ShiftedLHS = getUDivExpr(LHS, MulCount); 6136 return getMulExpr( 6137 getZeroExtendExpr( 6138 getTruncateExpr(ShiftedLHS, 6139 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6140 BO->LHS->getType()), 6141 MulCount); 6142 } 6143 } 6144 break; 6145 6146 case Instruction::Or: 6147 // If the RHS of the Or is a constant, we may have something like: 6148 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6149 // optimizations will transparently handle this case. 6150 // 6151 // In order for this transformation to be safe, the LHS must be of the 6152 // form X*(2^n) and the Or constant must be less than 2^n. 6153 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6154 const SCEV *LHS = getSCEV(BO->LHS); 6155 const APInt &CIVal = CI->getValue(); 6156 if (GetMinTrailingZeros(LHS) >= 6157 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6158 // Build a plain add SCEV. 6159 return getAddExpr(LHS, getSCEV(CI), 6160 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6161 } 6162 } 6163 break; 6164 6165 case Instruction::Xor: 6166 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6167 // If the RHS of xor is -1, then this is a not operation. 6168 if (CI->isMinusOne()) 6169 return getNotSCEV(getSCEV(BO->LHS)); 6170 6171 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6172 // This is a variant of the check for xor with -1, and it handles 6173 // the case where instcombine has trimmed non-demanded bits out 6174 // of an xor with -1. 6175 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6176 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6177 if (LBO->getOpcode() == Instruction::And && 6178 LCI->getValue() == CI->getValue()) 6179 if (const SCEVZeroExtendExpr *Z = 6180 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6181 Type *UTy = BO->LHS->getType(); 6182 const SCEV *Z0 = Z->getOperand(); 6183 Type *Z0Ty = Z0->getType(); 6184 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6185 6186 // If C is a low-bits mask, the zero extend is serving to 6187 // mask off the high bits. Complement the operand and 6188 // re-apply the zext. 6189 if (CI->getValue().isMask(Z0TySize)) 6190 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6191 6192 // If C is a single bit, it may be in the sign-bit position 6193 // before the zero-extend. In this case, represent the xor 6194 // using an add, which is equivalent, and re-apply the zext. 6195 APInt Trunc = CI->getValue().trunc(Z0TySize); 6196 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6197 Trunc.isSignMask()) 6198 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6199 UTy); 6200 } 6201 } 6202 break; 6203 6204 case Instruction::Shl: 6205 // Turn shift left of a constant amount into a multiply. 6206 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6207 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6208 6209 // If the shift count is not less than the bitwidth, the result of 6210 // the shift is undefined. Don't try to analyze it, because the 6211 // resolution chosen here may differ from the resolution chosen in 6212 // other parts of the compiler. 6213 if (SA->getValue().uge(BitWidth)) 6214 break; 6215 6216 // We can safely preserve the nuw flag in all cases. It's also safe to 6217 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6218 // requires special handling. It can be preserved as long as we're not 6219 // left shifting by bitwidth - 1. 6220 auto Flags = SCEV::FlagAnyWrap; 6221 if (BO->Op) { 6222 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6223 if ((MulFlags & SCEV::FlagNSW) && 6224 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6225 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6226 if (MulFlags & SCEV::FlagNUW) 6227 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6228 } 6229 6230 Constant *X = ConstantInt::get( 6231 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6232 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6233 } 6234 break; 6235 6236 case Instruction::AShr: { 6237 // AShr X, C, where C is a constant. 6238 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6239 if (!CI) 6240 break; 6241 6242 Type *OuterTy = BO->LHS->getType(); 6243 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6244 // If the shift count is not less than the bitwidth, the result of 6245 // the shift is undefined. Don't try to analyze it, because the 6246 // resolution chosen here may differ from the resolution chosen in 6247 // other parts of the compiler. 6248 if (CI->getValue().uge(BitWidth)) 6249 break; 6250 6251 if (CI->isZero()) 6252 return getSCEV(BO->LHS); // shift by zero --> noop 6253 6254 uint64_t AShrAmt = CI->getZExtValue(); 6255 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6256 6257 Operator *L = dyn_cast<Operator>(BO->LHS); 6258 if (L && L->getOpcode() == Instruction::Shl) { 6259 // X = Shl A, n 6260 // Y = AShr X, m 6261 // Both n and m are constant. 6262 6263 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6264 if (L->getOperand(1) == BO->RHS) 6265 // For a two-shift sext-inreg, i.e. n = m, 6266 // use sext(trunc(x)) as the SCEV expression. 6267 return getSignExtendExpr( 6268 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6269 6270 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6271 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6272 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6273 if (ShlAmt > AShrAmt) { 6274 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6275 // expression. We already checked that ShlAmt < BitWidth, so 6276 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6277 // ShlAmt - AShrAmt < Amt. 6278 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6279 ShlAmt - AShrAmt); 6280 return getSignExtendExpr( 6281 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6282 getConstant(Mul)), OuterTy); 6283 } 6284 } 6285 } 6286 if (BO->IsExact) { 6287 // Given exact arithmetic in-bounds right-shift by a constant, 6288 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6289 const SCEV *X = getSCEV(BO->LHS); 6290 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6291 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6292 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6293 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6294 } 6295 break; 6296 } 6297 } 6298 } 6299 6300 switch (U->getOpcode()) { 6301 case Instruction::Trunc: 6302 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6303 6304 case Instruction::ZExt: 6305 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6306 6307 case Instruction::SExt: 6308 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6309 // The NSW flag of a subtract does not always survive the conversion to 6310 // A + (-1)*B. By pushing sign extension onto its operands we are much 6311 // more likely to preserve NSW and allow later AddRec optimisations. 6312 // 6313 // NOTE: This is effectively duplicating this logic from getSignExtend: 6314 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6315 // but by that point the NSW information has potentially been lost. 6316 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6317 Type *Ty = U->getType(); 6318 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6319 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6320 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6321 } 6322 } 6323 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6324 6325 case Instruction::BitCast: 6326 // BitCasts are no-op casts so we just eliminate the cast. 6327 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6328 return getSCEV(U->getOperand(0)); 6329 break; 6330 6331 case Instruction::SDiv: 6332 // If both operands are non-negative, this is just an udiv. 6333 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6334 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6335 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6336 break; 6337 6338 case Instruction::SRem: 6339 // If both operands are non-negative, this is just an urem. 6340 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6341 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6342 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6343 break; 6344 6345 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6346 // lead to pointer expressions which cannot safely be expanded to GEPs, 6347 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6348 // simplifying integer expressions. 6349 6350 case Instruction::GetElementPtr: 6351 return createNodeForGEP(cast<GEPOperator>(U)); 6352 6353 case Instruction::PHI: 6354 return createNodeForPHI(cast<PHINode>(U)); 6355 6356 case Instruction::Select: 6357 // U can also be a select constant expr, which let fall through. Since 6358 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6359 // constant expressions cannot have instructions as operands, we'd have 6360 // returned getUnknown for a select constant expressions anyway. 6361 if (isa<Instruction>(U)) 6362 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6363 U->getOperand(1), U->getOperand(2)); 6364 break; 6365 6366 case Instruction::Call: 6367 case Instruction::Invoke: 6368 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6369 return getSCEV(RV); 6370 6371 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6372 switch (II->getIntrinsicID()) { 6373 case Intrinsic::abs: 6374 return getAbsExpr( 6375 getSCEV(II->getArgOperand(0)), 6376 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6377 case Intrinsic::umax: 6378 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6379 getSCEV(II->getArgOperand(1))); 6380 case Intrinsic::umin: 6381 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6382 getSCEV(II->getArgOperand(1))); 6383 case Intrinsic::smax: 6384 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6385 getSCEV(II->getArgOperand(1))); 6386 case Intrinsic::smin: 6387 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6388 getSCEV(II->getArgOperand(1))); 6389 case Intrinsic::usub_sat: { 6390 const SCEV *X = getSCEV(II->getArgOperand(0)); 6391 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6392 const SCEV *ClampedY = getUMinExpr(X, Y); 6393 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6394 } 6395 case Intrinsic::uadd_sat: { 6396 const SCEV *X = getSCEV(II->getArgOperand(0)); 6397 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6398 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6399 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6400 } 6401 default: 6402 break; 6403 } 6404 } 6405 break; 6406 } 6407 6408 return getUnknown(V); 6409 } 6410 6411 //===----------------------------------------------------------------------===// 6412 // Iteration Count Computation Code 6413 // 6414 6415 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6416 if (!ExitCount) 6417 return 0; 6418 6419 ConstantInt *ExitConst = ExitCount->getValue(); 6420 6421 // Guard against huge trip counts. 6422 if (ExitConst->getValue().getActiveBits() > 32) 6423 return 0; 6424 6425 // In case of integer overflow, this returns 0, which is correct. 6426 return ((unsigned)ExitConst->getZExtValue()) + 1; 6427 } 6428 6429 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6430 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6431 return getSmallConstantTripCount(L, ExitingBB); 6432 6433 // No trip count information for multiple exits. 6434 return 0; 6435 } 6436 6437 unsigned 6438 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6439 const BasicBlock *ExitingBlock) { 6440 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6441 assert(L->isLoopExiting(ExitingBlock) && 6442 "Exiting block must actually branch out of the loop!"); 6443 const SCEVConstant *ExitCount = 6444 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6445 return getConstantTripCount(ExitCount); 6446 } 6447 6448 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6449 const auto *MaxExitCount = 6450 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6451 return getConstantTripCount(MaxExitCount); 6452 } 6453 6454 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6455 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6456 return getSmallConstantTripMultiple(L, ExitingBB); 6457 6458 // No trip multiple information for multiple exits. 6459 return 0; 6460 } 6461 6462 /// Returns the largest constant divisor of the trip count of this loop as a 6463 /// normal unsigned value, if possible. This means that the actual trip count is 6464 /// always a multiple of the returned value (don't forget the trip count could 6465 /// very well be zero as well!). 6466 /// 6467 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6468 /// multiple of a constant (which is also the case if the trip count is simply 6469 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6470 /// if the trip count is very large (>= 2^32). 6471 /// 6472 /// As explained in the comments for getSmallConstantTripCount, this assumes 6473 /// that control exits the loop via ExitingBlock. 6474 unsigned 6475 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6476 const BasicBlock *ExitingBlock) { 6477 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6478 assert(L->isLoopExiting(ExitingBlock) && 6479 "Exiting block must actually branch out of the loop!"); 6480 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6481 if (ExitCount == getCouldNotCompute()) 6482 return 1; 6483 6484 // Get the trip count from the BE count by adding 1. 6485 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6486 6487 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6488 if (!TC) 6489 // Attempt to factor more general cases. Returns the greatest power of 6490 // two divisor. If overflow happens, the trip count expression is still 6491 // divisible by the greatest power of 2 divisor returned. 6492 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6493 6494 ConstantInt *Result = TC->getValue(); 6495 6496 // Guard against huge trip counts (this requires checking 6497 // for zero to handle the case where the trip count == -1 and the 6498 // addition wraps). 6499 if (!Result || Result->getValue().getActiveBits() > 32 || 6500 Result->getValue().getActiveBits() == 0) 6501 return 1; 6502 6503 return (unsigned)Result->getZExtValue(); 6504 } 6505 6506 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6507 const BasicBlock *ExitingBlock, 6508 ExitCountKind Kind) { 6509 switch (Kind) { 6510 case Exact: 6511 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6512 case ConstantMaximum: 6513 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6514 }; 6515 llvm_unreachable("Invalid ExitCountKind!"); 6516 } 6517 6518 const SCEV * 6519 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6520 SCEVUnionPredicate &Preds) { 6521 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6522 } 6523 6524 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6525 ExitCountKind Kind) { 6526 switch (Kind) { 6527 case Exact: 6528 return getBackedgeTakenInfo(L).getExact(L, this); 6529 case ConstantMaximum: 6530 return getBackedgeTakenInfo(L).getMax(this); 6531 }; 6532 llvm_unreachable("Invalid ExitCountKind!"); 6533 } 6534 6535 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6536 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6537 } 6538 6539 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6540 static void 6541 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6542 BasicBlock *Header = L->getHeader(); 6543 6544 // Push all Loop-header PHIs onto the Worklist stack. 6545 for (PHINode &PN : Header->phis()) 6546 Worklist.push_back(&PN); 6547 } 6548 6549 const ScalarEvolution::BackedgeTakenInfo & 6550 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6551 auto &BTI = getBackedgeTakenInfo(L); 6552 if (BTI.hasFullInfo()) 6553 return BTI; 6554 6555 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6556 6557 if (!Pair.second) 6558 return Pair.first->second; 6559 6560 BackedgeTakenInfo Result = 6561 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6562 6563 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6564 } 6565 6566 const ScalarEvolution::BackedgeTakenInfo & 6567 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6568 // Initially insert an invalid entry for this loop. If the insertion 6569 // succeeds, proceed to actually compute a backedge-taken count and 6570 // update the value. The temporary CouldNotCompute value tells SCEV 6571 // code elsewhere that it shouldn't attempt to request a new 6572 // backedge-taken count, which could result in infinite recursion. 6573 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6574 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6575 if (!Pair.second) 6576 return Pair.first->second; 6577 6578 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6579 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6580 // must be cleared in this scope. 6581 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6582 6583 // In product build, there are no usage of statistic. 6584 (void)NumTripCountsComputed; 6585 (void)NumTripCountsNotComputed; 6586 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6587 const SCEV *BEExact = Result.getExact(L, this); 6588 if (BEExact != getCouldNotCompute()) { 6589 assert(isLoopInvariant(BEExact, L) && 6590 isLoopInvariant(Result.getMax(this), L) && 6591 "Computed backedge-taken count isn't loop invariant for loop!"); 6592 ++NumTripCountsComputed; 6593 } 6594 else if (Result.getMax(this) == getCouldNotCompute() && 6595 isa<PHINode>(L->getHeader()->begin())) { 6596 // Only count loops that have phi nodes as not being computable. 6597 ++NumTripCountsNotComputed; 6598 } 6599 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6600 6601 // Now that we know more about the trip count for this loop, forget any 6602 // existing SCEV values for PHI nodes in this loop since they are only 6603 // conservative estimates made without the benefit of trip count 6604 // information. This is similar to the code in forgetLoop, except that 6605 // it handles SCEVUnknown PHI nodes specially. 6606 if (Result.hasAnyInfo()) { 6607 SmallVector<Instruction *, 16> Worklist; 6608 PushLoopPHIs(L, Worklist); 6609 6610 SmallPtrSet<Instruction *, 8> Discovered; 6611 while (!Worklist.empty()) { 6612 Instruction *I = Worklist.pop_back_val(); 6613 6614 ValueExprMapType::iterator It = 6615 ValueExprMap.find_as(static_cast<Value *>(I)); 6616 if (It != ValueExprMap.end()) { 6617 const SCEV *Old = It->second; 6618 6619 // SCEVUnknown for a PHI either means that it has an unrecognized 6620 // structure, or it's a PHI that's in the progress of being computed 6621 // by createNodeForPHI. In the former case, additional loop trip 6622 // count information isn't going to change anything. In the later 6623 // case, createNodeForPHI will perform the necessary updates on its 6624 // own when it gets to that point. 6625 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6626 eraseValueFromMap(It->first); 6627 forgetMemoizedResults(Old); 6628 } 6629 if (PHINode *PN = dyn_cast<PHINode>(I)) 6630 ConstantEvolutionLoopExitValue.erase(PN); 6631 } 6632 6633 // Since we don't need to invalidate anything for correctness and we're 6634 // only invalidating to make SCEV's results more precise, we get to stop 6635 // early to avoid invalidating too much. This is especially important in 6636 // cases like: 6637 // 6638 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6639 // loop0: 6640 // %pn0 = phi 6641 // ... 6642 // loop1: 6643 // %pn1 = phi 6644 // ... 6645 // 6646 // where both loop0 and loop1's backedge taken count uses the SCEV 6647 // expression for %v. If we don't have the early stop below then in cases 6648 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6649 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6650 // count for loop1, effectively nullifying SCEV's trip count cache. 6651 for (auto *U : I->users()) 6652 if (auto *I = dyn_cast<Instruction>(U)) { 6653 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6654 if (LoopForUser && L->contains(LoopForUser) && 6655 Discovered.insert(I).second) 6656 Worklist.push_back(I); 6657 } 6658 } 6659 } 6660 6661 // Re-lookup the insert position, since the call to 6662 // computeBackedgeTakenCount above could result in a 6663 // recusive call to getBackedgeTakenInfo (on a different 6664 // loop), which would invalidate the iterator computed 6665 // earlier. 6666 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6667 } 6668 6669 void ScalarEvolution::forgetAllLoops() { 6670 // This method is intended to forget all info about loops. It should 6671 // invalidate caches as if the following happened: 6672 // - The trip counts of all loops have changed arbitrarily 6673 // - Every llvm::Value has been updated in place to produce a different 6674 // result. 6675 BackedgeTakenCounts.clear(); 6676 PredicatedBackedgeTakenCounts.clear(); 6677 LoopPropertiesCache.clear(); 6678 ConstantEvolutionLoopExitValue.clear(); 6679 ValueExprMap.clear(); 6680 ValuesAtScopes.clear(); 6681 LoopDispositions.clear(); 6682 BlockDispositions.clear(); 6683 UnsignedRanges.clear(); 6684 SignedRanges.clear(); 6685 ExprValueMap.clear(); 6686 HasRecMap.clear(); 6687 MinTrailingZerosCache.clear(); 6688 PredicatedSCEVRewrites.clear(); 6689 } 6690 6691 void ScalarEvolution::forgetLoop(const Loop *L) { 6692 // Drop any stored trip count value. 6693 auto RemoveLoopFromBackedgeMap = 6694 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6695 auto BTCPos = Map.find(L); 6696 if (BTCPos != Map.end()) { 6697 BTCPos->second.clear(); 6698 Map.erase(BTCPos); 6699 } 6700 }; 6701 6702 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6703 SmallVector<Instruction *, 32> Worklist; 6704 SmallPtrSet<Instruction *, 16> Visited; 6705 6706 // Iterate over all the loops and sub-loops to drop SCEV information. 6707 while (!LoopWorklist.empty()) { 6708 auto *CurrL = LoopWorklist.pop_back_val(); 6709 6710 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6711 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6712 6713 // Drop information about predicated SCEV rewrites for this loop. 6714 for (auto I = PredicatedSCEVRewrites.begin(); 6715 I != PredicatedSCEVRewrites.end();) { 6716 std::pair<const SCEV *, const Loop *> Entry = I->first; 6717 if (Entry.second == CurrL) 6718 PredicatedSCEVRewrites.erase(I++); 6719 else 6720 ++I; 6721 } 6722 6723 auto LoopUsersItr = LoopUsers.find(CurrL); 6724 if (LoopUsersItr != LoopUsers.end()) { 6725 for (auto *S : LoopUsersItr->second) 6726 forgetMemoizedResults(S); 6727 LoopUsers.erase(LoopUsersItr); 6728 } 6729 6730 // Drop information about expressions based on loop-header PHIs. 6731 PushLoopPHIs(CurrL, Worklist); 6732 6733 while (!Worklist.empty()) { 6734 Instruction *I = Worklist.pop_back_val(); 6735 if (!Visited.insert(I).second) 6736 continue; 6737 6738 ValueExprMapType::iterator It = 6739 ValueExprMap.find_as(static_cast<Value *>(I)); 6740 if (It != ValueExprMap.end()) { 6741 eraseValueFromMap(It->first); 6742 forgetMemoizedResults(It->second); 6743 if (PHINode *PN = dyn_cast<PHINode>(I)) 6744 ConstantEvolutionLoopExitValue.erase(PN); 6745 } 6746 6747 PushDefUseChildren(I, Worklist); 6748 } 6749 6750 LoopPropertiesCache.erase(CurrL); 6751 // Forget all contained loops too, to avoid dangling entries in the 6752 // ValuesAtScopes map. 6753 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6754 } 6755 } 6756 6757 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6758 while (Loop *Parent = L->getParentLoop()) 6759 L = Parent; 6760 forgetLoop(L); 6761 } 6762 6763 void ScalarEvolution::forgetValue(Value *V) { 6764 Instruction *I = dyn_cast<Instruction>(V); 6765 if (!I) return; 6766 6767 // Drop information about expressions based on loop-header PHIs. 6768 SmallVector<Instruction *, 16> Worklist; 6769 Worklist.push_back(I); 6770 6771 SmallPtrSet<Instruction *, 8> Visited; 6772 while (!Worklist.empty()) { 6773 I = Worklist.pop_back_val(); 6774 if (!Visited.insert(I).second) 6775 continue; 6776 6777 ValueExprMapType::iterator It = 6778 ValueExprMap.find_as(static_cast<Value *>(I)); 6779 if (It != ValueExprMap.end()) { 6780 eraseValueFromMap(It->first); 6781 forgetMemoizedResults(It->second); 6782 if (PHINode *PN = dyn_cast<PHINode>(I)) 6783 ConstantEvolutionLoopExitValue.erase(PN); 6784 } 6785 6786 PushDefUseChildren(I, Worklist); 6787 } 6788 } 6789 6790 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 6791 LoopDispositions.clear(); 6792 } 6793 6794 /// Get the exact loop backedge taken count considering all loop exits. A 6795 /// computable result can only be returned for loops with all exiting blocks 6796 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6797 /// is never skipped. This is a valid assumption as long as the loop exits via 6798 /// that test. For precise results, it is the caller's responsibility to specify 6799 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6800 const SCEV * 6801 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6802 SCEVUnionPredicate *Preds) const { 6803 // If any exits were not computable, the loop is not computable. 6804 if (!isComplete() || ExitNotTaken.empty()) 6805 return SE->getCouldNotCompute(); 6806 6807 const BasicBlock *Latch = L->getLoopLatch(); 6808 // All exiting blocks we have collected must dominate the only backedge. 6809 if (!Latch) 6810 return SE->getCouldNotCompute(); 6811 6812 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6813 // count is simply a minimum out of all these calculated exit counts. 6814 SmallVector<const SCEV *, 2> Ops; 6815 for (auto &ENT : ExitNotTaken) { 6816 const SCEV *BECount = ENT.ExactNotTaken; 6817 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6818 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6819 "We should only have known counts for exiting blocks that dominate " 6820 "latch!"); 6821 6822 Ops.push_back(BECount); 6823 6824 if (Preds && !ENT.hasAlwaysTruePredicate()) 6825 Preds->add(ENT.Predicate.get()); 6826 6827 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6828 "Predicate should be always true!"); 6829 } 6830 6831 return SE->getUMinFromMismatchedTypes(Ops); 6832 } 6833 6834 /// Get the exact not taken count for this loop exit. 6835 const SCEV * 6836 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 6837 ScalarEvolution *SE) const { 6838 for (auto &ENT : ExitNotTaken) 6839 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6840 return ENT.ExactNotTaken; 6841 6842 return SE->getCouldNotCompute(); 6843 } 6844 6845 const SCEV * 6846 ScalarEvolution::BackedgeTakenInfo::getMax(const BasicBlock *ExitingBlock, 6847 ScalarEvolution *SE) const { 6848 for (auto &ENT : ExitNotTaken) 6849 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6850 return ENT.MaxNotTaken; 6851 6852 return SE->getCouldNotCompute(); 6853 } 6854 6855 /// getMax - Get the max backedge taken count for the loop. 6856 const SCEV * 6857 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6858 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6859 return !ENT.hasAlwaysTruePredicate(); 6860 }; 6861 6862 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6863 return SE->getCouldNotCompute(); 6864 6865 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6866 "No point in having a non-constant max backedge taken count!"); 6867 return getMax(); 6868 } 6869 6870 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6871 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6872 return !ENT.hasAlwaysTruePredicate(); 6873 }; 6874 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6875 } 6876 6877 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6878 ScalarEvolution *SE) const { 6879 if (getMax() && getMax() != SE->getCouldNotCompute() && 6880 SE->hasOperand(getMax(), S)) 6881 return true; 6882 6883 for (auto &ENT : ExitNotTaken) 6884 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6885 SE->hasOperand(ENT.ExactNotTaken, S)) 6886 return true; 6887 6888 return false; 6889 } 6890 6891 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6892 : ExactNotTaken(E), MaxNotTaken(E) { 6893 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6894 isa<SCEVConstant>(MaxNotTaken)) && 6895 "No point in having a non-constant max backedge taken count!"); 6896 } 6897 6898 ScalarEvolution::ExitLimit::ExitLimit( 6899 const SCEV *E, const SCEV *M, bool MaxOrZero, 6900 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6901 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6902 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6903 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6904 "Exact is not allowed to be less precise than Max"); 6905 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6906 isa<SCEVConstant>(MaxNotTaken)) && 6907 "No point in having a non-constant max backedge taken count!"); 6908 for (auto *PredSet : PredSetList) 6909 for (auto *P : *PredSet) 6910 addPredicate(P); 6911 } 6912 6913 ScalarEvolution::ExitLimit::ExitLimit( 6914 const SCEV *E, const SCEV *M, bool MaxOrZero, 6915 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6916 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6917 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6918 isa<SCEVConstant>(MaxNotTaken)) && 6919 "No point in having a non-constant max backedge taken count!"); 6920 } 6921 6922 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6923 bool MaxOrZero) 6924 : ExitLimit(E, M, MaxOrZero, None) { 6925 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6926 isa<SCEVConstant>(MaxNotTaken)) && 6927 "No point in having a non-constant max backedge taken count!"); 6928 } 6929 6930 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6931 /// computable exit into a persistent ExitNotTakenInfo array. 6932 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6933 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6934 ExitCounts, 6935 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6936 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6937 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6938 6939 ExitNotTaken.reserve(ExitCounts.size()); 6940 std::transform( 6941 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6942 [&](const EdgeExitInfo &EEI) { 6943 BasicBlock *ExitBB = EEI.first; 6944 const ExitLimit &EL = EEI.second; 6945 if (EL.Predicates.empty()) 6946 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6947 nullptr); 6948 6949 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6950 for (auto *Pred : EL.Predicates) 6951 Predicate->add(Pred); 6952 6953 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6954 std::move(Predicate)); 6955 }); 6956 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6957 "No point in having a non-constant max backedge taken count!"); 6958 } 6959 6960 /// Invalidate this result and free the ExitNotTakenInfo array. 6961 void ScalarEvolution::BackedgeTakenInfo::clear() { 6962 ExitNotTaken.clear(); 6963 } 6964 6965 /// Compute the number of times the backedge of the specified loop will execute. 6966 ScalarEvolution::BackedgeTakenInfo 6967 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6968 bool AllowPredicates) { 6969 SmallVector<BasicBlock *, 8> ExitingBlocks; 6970 L->getExitingBlocks(ExitingBlocks); 6971 6972 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6973 6974 SmallVector<EdgeExitInfo, 4> ExitCounts; 6975 bool CouldComputeBECount = true; 6976 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6977 const SCEV *MustExitMaxBECount = nullptr; 6978 const SCEV *MayExitMaxBECount = nullptr; 6979 bool MustExitMaxOrZero = false; 6980 6981 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6982 // and compute maxBECount. 6983 // Do a union of all the predicates here. 6984 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6985 BasicBlock *ExitBB = ExitingBlocks[i]; 6986 6987 // We canonicalize untaken exits to br (constant), ignore them so that 6988 // proving an exit untaken doesn't negatively impact our ability to reason 6989 // about the loop as whole. 6990 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 6991 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 6992 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6993 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 6994 continue; 6995 } 6996 6997 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6998 6999 assert((AllowPredicates || EL.Predicates.empty()) && 7000 "Predicated exit limit when predicates are not allowed!"); 7001 7002 // 1. For each exit that can be computed, add an entry to ExitCounts. 7003 // CouldComputeBECount is true only if all exits can be computed. 7004 if (EL.ExactNotTaken == getCouldNotCompute()) 7005 // We couldn't compute an exact value for this exit, so 7006 // we won't be able to compute an exact value for the loop. 7007 CouldComputeBECount = false; 7008 else 7009 ExitCounts.emplace_back(ExitBB, EL); 7010 7011 // 2. Derive the loop's MaxBECount from each exit's max number of 7012 // non-exiting iterations. Partition the loop exits into two kinds: 7013 // LoopMustExits and LoopMayExits. 7014 // 7015 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7016 // is a LoopMayExit. If any computable LoopMustExit is found, then 7017 // MaxBECount is the minimum EL.MaxNotTaken of computable 7018 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7019 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7020 // computable EL.MaxNotTaken. 7021 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7022 DT.dominates(ExitBB, Latch)) { 7023 if (!MustExitMaxBECount) { 7024 MustExitMaxBECount = EL.MaxNotTaken; 7025 MustExitMaxOrZero = EL.MaxOrZero; 7026 } else { 7027 MustExitMaxBECount = 7028 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7029 } 7030 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7031 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7032 MayExitMaxBECount = EL.MaxNotTaken; 7033 else { 7034 MayExitMaxBECount = 7035 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7036 } 7037 } 7038 } 7039 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7040 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7041 // The loop backedge will be taken the maximum or zero times if there's 7042 // a single exit that must be taken the maximum or zero times. 7043 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7044 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7045 MaxBECount, MaxOrZero); 7046 } 7047 7048 ScalarEvolution::ExitLimit 7049 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7050 bool AllowPredicates) { 7051 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7052 // If our exiting block does not dominate the latch, then its connection with 7053 // loop's exit limit may be far from trivial. 7054 const BasicBlock *Latch = L->getLoopLatch(); 7055 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7056 return getCouldNotCompute(); 7057 7058 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7059 Instruction *Term = ExitingBlock->getTerminator(); 7060 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7061 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7062 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7063 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7064 "It should have one successor in loop and one exit block!"); 7065 // Proceed to the next level to examine the exit condition expression. 7066 return computeExitLimitFromCond( 7067 L, BI->getCondition(), ExitIfTrue, 7068 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7069 } 7070 7071 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7072 // For switch, make sure that there is a single exit from the loop. 7073 BasicBlock *Exit = nullptr; 7074 for (auto *SBB : successors(ExitingBlock)) 7075 if (!L->contains(SBB)) { 7076 if (Exit) // Multiple exit successors. 7077 return getCouldNotCompute(); 7078 Exit = SBB; 7079 } 7080 assert(Exit && "Exiting block must have at least one exit"); 7081 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7082 /*ControlsExit=*/IsOnlyExit); 7083 } 7084 7085 return getCouldNotCompute(); 7086 } 7087 7088 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7089 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7090 bool ControlsExit, bool AllowPredicates) { 7091 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7092 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7093 ControlsExit, AllowPredicates); 7094 } 7095 7096 Optional<ScalarEvolution::ExitLimit> 7097 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7098 bool ExitIfTrue, bool ControlsExit, 7099 bool AllowPredicates) { 7100 (void)this->L; 7101 (void)this->ExitIfTrue; 7102 (void)this->AllowPredicates; 7103 7104 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7105 this->AllowPredicates == AllowPredicates && 7106 "Variance in assumed invariant key components!"); 7107 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7108 if (Itr == TripCountMap.end()) 7109 return None; 7110 return Itr->second; 7111 } 7112 7113 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7114 bool ExitIfTrue, 7115 bool ControlsExit, 7116 bool AllowPredicates, 7117 const ExitLimit &EL) { 7118 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7119 this->AllowPredicates == AllowPredicates && 7120 "Variance in assumed invariant key components!"); 7121 7122 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7123 assert(InsertResult.second && "Expected successful insertion!"); 7124 (void)InsertResult; 7125 (void)ExitIfTrue; 7126 } 7127 7128 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7129 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7130 bool ControlsExit, bool AllowPredicates) { 7131 7132 if (auto MaybeEL = 7133 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7134 return *MaybeEL; 7135 7136 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7137 ControlsExit, AllowPredicates); 7138 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7139 return EL; 7140 } 7141 7142 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7143 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7144 bool ControlsExit, bool AllowPredicates) { 7145 // Check if the controlling expression for this loop is an And or Or. 7146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7147 if (BO->getOpcode() == Instruction::And) { 7148 // Recurse on the operands of the and. 7149 bool EitherMayExit = !ExitIfTrue; 7150 ExitLimit EL0 = computeExitLimitFromCondCached( 7151 Cache, L, BO->getOperand(0), ExitIfTrue, 7152 ControlsExit && !EitherMayExit, AllowPredicates); 7153 ExitLimit EL1 = computeExitLimitFromCondCached( 7154 Cache, L, BO->getOperand(1), ExitIfTrue, 7155 ControlsExit && !EitherMayExit, AllowPredicates); 7156 // Be robust against unsimplified IR for the form "and i1 X, true" 7157 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7158 return CI->isOne() ? EL0 : EL1; 7159 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7160 return CI->isOne() ? EL1 : EL0; 7161 const SCEV *BECount = getCouldNotCompute(); 7162 const SCEV *MaxBECount = getCouldNotCompute(); 7163 if (EitherMayExit) { 7164 // Both conditions must be true for the loop to continue executing. 7165 // Choose the less conservative count. 7166 if (EL0.ExactNotTaken == getCouldNotCompute() || 7167 EL1.ExactNotTaken == getCouldNotCompute()) 7168 BECount = getCouldNotCompute(); 7169 else 7170 BECount = 7171 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7172 if (EL0.MaxNotTaken == getCouldNotCompute()) 7173 MaxBECount = EL1.MaxNotTaken; 7174 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7175 MaxBECount = EL0.MaxNotTaken; 7176 else 7177 MaxBECount = 7178 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7179 } else { 7180 // Both conditions must be true at the same time for the loop to exit. 7181 // For now, be conservative. 7182 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7183 MaxBECount = EL0.MaxNotTaken; 7184 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7185 BECount = EL0.ExactNotTaken; 7186 } 7187 7188 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7189 // to be more aggressive when computing BECount than when computing 7190 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7191 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7192 // to not. 7193 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7194 !isa<SCEVCouldNotCompute>(BECount)) 7195 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7196 7197 return ExitLimit(BECount, MaxBECount, false, 7198 {&EL0.Predicates, &EL1.Predicates}); 7199 } 7200 if (BO->getOpcode() == Instruction::Or) { 7201 // Recurse on the operands of the or. 7202 bool EitherMayExit = ExitIfTrue; 7203 ExitLimit EL0 = computeExitLimitFromCondCached( 7204 Cache, L, BO->getOperand(0), ExitIfTrue, 7205 ControlsExit && !EitherMayExit, AllowPredicates); 7206 ExitLimit EL1 = computeExitLimitFromCondCached( 7207 Cache, L, BO->getOperand(1), ExitIfTrue, 7208 ControlsExit && !EitherMayExit, AllowPredicates); 7209 // Be robust against unsimplified IR for the form "or i1 X, true" 7210 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7211 return CI->isZero() ? EL0 : EL1; 7212 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7213 return CI->isZero() ? EL1 : EL0; 7214 const SCEV *BECount = getCouldNotCompute(); 7215 const SCEV *MaxBECount = getCouldNotCompute(); 7216 if (EitherMayExit) { 7217 // Both conditions must be false for the loop to continue executing. 7218 // Choose the less conservative count. 7219 if (EL0.ExactNotTaken == getCouldNotCompute() || 7220 EL1.ExactNotTaken == getCouldNotCompute()) 7221 BECount = getCouldNotCompute(); 7222 else 7223 BECount = 7224 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7225 if (EL0.MaxNotTaken == getCouldNotCompute()) 7226 MaxBECount = EL1.MaxNotTaken; 7227 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7228 MaxBECount = EL0.MaxNotTaken; 7229 else 7230 MaxBECount = 7231 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7232 } else { 7233 // Both conditions must be false at the same time for the loop to exit. 7234 // For now, be conservative. 7235 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7236 MaxBECount = EL0.MaxNotTaken; 7237 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7238 BECount = EL0.ExactNotTaken; 7239 } 7240 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7241 // to be more aggressive when computing BECount than when computing 7242 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7243 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7244 // to not. 7245 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7246 !isa<SCEVCouldNotCompute>(BECount)) 7247 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7248 7249 return ExitLimit(BECount, MaxBECount, false, 7250 {&EL0.Predicates, &EL1.Predicates}); 7251 } 7252 } 7253 7254 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7255 // Proceed to the next level to examine the icmp. 7256 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7257 ExitLimit EL = 7258 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7259 if (EL.hasFullInfo() || !AllowPredicates) 7260 return EL; 7261 7262 // Try again, but use SCEV predicates this time. 7263 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7264 /*AllowPredicates=*/true); 7265 } 7266 7267 // Check for a constant condition. These are normally stripped out by 7268 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7269 // preserve the CFG and is temporarily leaving constant conditions 7270 // in place. 7271 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7272 if (ExitIfTrue == !CI->getZExtValue()) 7273 // The backedge is always taken. 7274 return getCouldNotCompute(); 7275 else 7276 // The backedge is never taken. 7277 return getZero(CI->getType()); 7278 } 7279 7280 // If it's not an integer or pointer comparison then compute it the hard way. 7281 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7282 } 7283 7284 ScalarEvolution::ExitLimit 7285 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7286 ICmpInst *ExitCond, 7287 bool ExitIfTrue, 7288 bool ControlsExit, 7289 bool AllowPredicates) { 7290 // If the condition was exit on true, convert the condition to exit on false 7291 ICmpInst::Predicate Pred; 7292 if (!ExitIfTrue) 7293 Pred = ExitCond->getPredicate(); 7294 else 7295 Pred = ExitCond->getInversePredicate(); 7296 const ICmpInst::Predicate OriginalPred = Pred; 7297 7298 // Handle common loops like: for (X = "string"; *X; ++X) 7299 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7300 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7301 ExitLimit ItCnt = 7302 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7303 if (ItCnt.hasAnyInfo()) 7304 return ItCnt; 7305 } 7306 7307 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7308 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7309 7310 // Try to evaluate any dependencies out of the loop. 7311 LHS = getSCEVAtScope(LHS, L); 7312 RHS = getSCEVAtScope(RHS, L); 7313 7314 // At this point, we would like to compute how many iterations of the 7315 // loop the predicate will return true for these inputs. 7316 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7317 // If there is a loop-invariant, force it into the RHS. 7318 std::swap(LHS, RHS); 7319 Pred = ICmpInst::getSwappedPredicate(Pred); 7320 } 7321 7322 // Simplify the operands before analyzing them. 7323 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7324 7325 // If we have a comparison of a chrec against a constant, try to use value 7326 // ranges to answer this query. 7327 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7328 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7329 if (AddRec->getLoop() == L) { 7330 // Form the constant range. 7331 ConstantRange CompRange = 7332 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7333 7334 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7335 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7336 } 7337 7338 switch (Pred) { 7339 case ICmpInst::ICMP_NE: { // while (X != Y) 7340 // Convert to: while (X-Y != 0) 7341 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7342 AllowPredicates); 7343 if (EL.hasAnyInfo()) return EL; 7344 break; 7345 } 7346 case ICmpInst::ICMP_EQ: { // while (X == Y) 7347 // Convert to: while (X-Y == 0) 7348 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7349 if (EL.hasAnyInfo()) return EL; 7350 break; 7351 } 7352 case ICmpInst::ICMP_SLT: 7353 case ICmpInst::ICMP_ULT: { // while (X < Y) 7354 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7355 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7356 AllowPredicates); 7357 if (EL.hasAnyInfo()) return EL; 7358 break; 7359 } 7360 case ICmpInst::ICMP_SGT: 7361 case ICmpInst::ICMP_UGT: { // while (X > Y) 7362 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7363 ExitLimit EL = 7364 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7365 AllowPredicates); 7366 if (EL.hasAnyInfo()) return EL; 7367 break; 7368 } 7369 default: 7370 break; 7371 } 7372 7373 auto *ExhaustiveCount = 7374 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7375 7376 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7377 return ExhaustiveCount; 7378 7379 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7380 ExitCond->getOperand(1), L, OriginalPred); 7381 } 7382 7383 ScalarEvolution::ExitLimit 7384 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7385 SwitchInst *Switch, 7386 BasicBlock *ExitingBlock, 7387 bool ControlsExit) { 7388 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7389 7390 // Give up if the exit is the default dest of a switch. 7391 if (Switch->getDefaultDest() == ExitingBlock) 7392 return getCouldNotCompute(); 7393 7394 assert(L->contains(Switch->getDefaultDest()) && 7395 "Default case must not exit the loop!"); 7396 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7397 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7398 7399 // while (X != Y) --> while (X-Y != 0) 7400 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7401 if (EL.hasAnyInfo()) 7402 return EL; 7403 7404 return getCouldNotCompute(); 7405 } 7406 7407 static ConstantInt * 7408 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7409 ScalarEvolution &SE) { 7410 const SCEV *InVal = SE.getConstant(C); 7411 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7412 assert(isa<SCEVConstant>(Val) && 7413 "Evaluation of SCEV at constant didn't fold correctly?"); 7414 return cast<SCEVConstant>(Val)->getValue(); 7415 } 7416 7417 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7418 /// compute the backedge execution count. 7419 ScalarEvolution::ExitLimit 7420 ScalarEvolution::computeLoadConstantCompareExitLimit( 7421 LoadInst *LI, 7422 Constant *RHS, 7423 const Loop *L, 7424 ICmpInst::Predicate predicate) { 7425 if (LI->isVolatile()) return getCouldNotCompute(); 7426 7427 // Check to see if the loaded pointer is a getelementptr of a global. 7428 // TODO: Use SCEV instead of manually grubbing with GEPs. 7429 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7430 if (!GEP) return getCouldNotCompute(); 7431 7432 // Make sure that it is really a constant global we are gepping, with an 7433 // initializer, and make sure the first IDX is really 0. 7434 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7435 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7436 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7437 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7438 return getCouldNotCompute(); 7439 7440 // Okay, we allow one non-constant index into the GEP instruction. 7441 Value *VarIdx = nullptr; 7442 std::vector<Constant*> Indexes; 7443 unsigned VarIdxNum = 0; 7444 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7445 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7446 Indexes.push_back(CI); 7447 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7448 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7449 VarIdx = GEP->getOperand(i); 7450 VarIdxNum = i-2; 7451 Indexes.push_back(nullptr); 7452 } 7453 7454 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7455 if (!VarIdx) 7456 return getCouldNotCompute(); 7457 7458 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7459 // Check to see if X is a loop variant variable value now. 7460 const SCEV *Idx = getSCEV(VarIdx); 7461 Idx = getSCEVAtScope(Idx, L); 7462 7463 // We can only recognize very limited forms of loop index expressions, in 7464 // particular, only affine AddRec's like {C1,+,C2}. 7465 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7466 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7467 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7468 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7469 return getCouldNotCompute(); 7470 7471 unsigned MaxSteps = MaxBruteForceIterations; 7472 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7473 ConstantInt *ItCst = ConstantInt::get( 7474 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7475 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7476 7477 // Form the GEP offset. 7478 Indexes[VarIdxNum] = Val; 7479 7480 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7481 Indexes); 7482 if (!Result) break; // Cannot compute! 7483 7484 // Evaluate the condition for this iteration. 7485 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7486 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7487 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7488 ++NumArrayLenItCounts; 7489 return getConstant(ItCst); // Found terminating iteration! 7490 } 7491 } 7492 return getCouldNotCompute(); 7493 } 7494 7495 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7496 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7497 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7498 if (!RHS) 7499 return getCouldNotCompute(); 7500 7501 const BasicBlock *Latch = L->getLoopLatch(); 7502 if (!Latch) 7503 return getCouldNotCompute(); 7504 7505 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7506 if (!Predecessor) 7507 return getCouldNotCompute(); 7508 7509 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7510 // Return LHS in OutLHS and shift_opt in OutOpCode. 7511 auto MatchPositiveShift = 7512 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7513 7514 using namespace PatternMatch; 7515 7516 ConstantInt *ShiftAmt; 7517 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7518 OutOpCode = Instruction::LShr; 7519 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7520 OutOpCode = Instruction::AShr; 7521 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7522 OutOpCode = Instruction::Shl; 7523 else 7524 return false; 7525 7526 return ShiftAmt->getValue().isStrictlyPositive(); 7527 }; 7528 7529 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7530 // 7531 // loop: 7532 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7533 // %iv.shifted = lshr i32 %iv, <positive constant> 7534 // 7535 // Return true on a successful match. Return the corresponding PHI node (%iv 7536 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7537 auto MatchShiftRecurrence = 7538 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7539 Optional<Instruction::BinaryOps> PostShiftOpCode; 7540 7541 { 7542 Instruction::BinaryOps OpC; 7543 Value *V; 7544 7545 // If we encounter a shift instruction, "peel off" the shift operation, 7546 // and remember that we did so. Later when we inspect %iv's backedge 7547 // value, we will make sure that the backedge value uses the same 7548 // operation. 7549 // 7550 // Note: the peeled shift operation does not have to be the same 7551 // instruction as the one feeding into the PHI's backedge value. We only 7552 // really care about it being the same *kind* of shift instruction -- 7553 // that's all that is required for our later inferences to hold. 7554 if (MatchPositiveShift(LHS, V, OpC)) { 7555 PostShiftOpCode = OpC; 7556 LHS = V; 7557 } 7558 } 7559 7560 PNOut = dyn_cast<PHINode>(LHS); 7561 if (!PNOut || PNOut->getParent() != L->getHeader()) 7562 return false; 7563 7564 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7565 Value *OpLHS; 7566 7567 return 7568 // The backedge value for the PHI node must be a shift by a positive 7569 // amount 7570 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7571 7572 // of the PHI node itself 7573 OpLHS == PNOut && 7574 7575 // and the kind of shift should be match the kind of shift we peeled 7576 // off, if any. 7577 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7578 }; 7579 7580 PHINode *PN; 7581 Instruction::BinaryOps OpCode; 7582 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7583 return getCouldNotCompute(); 7584 7585 const DataLayout &DL = getDataLayout(); 7586 7587 // The key rationale for this optimization is that for some kinds of shift 7588 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7589 // within a finite number of iterations. If the condition guarding the 7590 // backedge (in the sense that the backedge is taken if the condition is true) 7591 // is false for the value the shift recurrence stabilizes to, then we know 7592 // that the backedge is taken only a finite number of times. 7593 7594 ConstantInt *StableValue = nullptr; 7595 switch (OpCode) { 7596 default: 7597 llvm_unreachable("Impossible case!"); 7598 7599 case Instruction::AShr: { 7600 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7601 // bitwidth(K) iterations. 7602 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7603 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7604 Predecessor->getTerminator(), &DT); 7605 auto *Ty = cast<IntegerType>(RHS->getType()); 7606 if (Known.isNonNegative()) 7607 StableValue = ConstantInt::get(Ty, 0); 7608 else if (Known.isNegative()) 7609 StableValue = ConstantInt::get(Ty, -1, true); 7610 else 7611 return getCouldNotCompute(); 7612 7613 break; 7614 } 7615 case Instruction::LShr: 7616 case Instruction::Shl: 7617 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7618 // stabilize to 0 in at most bitwidth(K) iterations. 7619 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7620 break; 7621 } 7622 7623 auto *Result = 7624 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7625 assert(Result->getType()->isIntegerTy(1) && 7626 "Otherwise cannot be an operand to a branch instruction"); 7627 7628 if (Result->isZeroValue()) { 7629 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7630 const SCEV *UpperBound = 7631 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7632 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7633 } 7634 7635 return getCouldNotCompute(); 7636 } 7637 7638 /// Return true if we can constant fold an instruction of the specified type, 7639 /// assuming that all operands were constants. 7640 static bool CanConstantFold(const Instruction *I) { 7641 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7642 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7643 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7644 return true; 7645 7646 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7647 if (const Function *F = CI->getCalledFunction()) 7648 return canConstantFoldCallTo(CI, F); 7649 return false; 7650 } 7651 7652 /// Determine whether this instruction can constant evolve within this loop 7653 /// assuming its operands can all constant evolve. 7654 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7655 // An instruction outside of the loop can't be derived from a loop PHI. 7656 if (!L->contains(I)) return false; 7657 7658 if (isa<PHINode>(I)) { 7659 // We don't currently keep track of the control flow needed to evaluate 7660 // PHIs, so we cannot handle PHIs inside of loops. 7661 return L->getHeader() == I->getParent(); 7662 } 7663 7664 // If we won't be able to constant fold this expression even if the operands 7665 // are constants, bail early. 7666 return CanConstantFold(I); 7667 } 7668 7669 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7670 /// recursing through each instruction operand until reaching a loop header phi. 7671 static PHINode * 7672 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7673 DenseMap<Instruction *, PHINode *> &PHIMap, 7674 unsigned Depth) { 7675 if (Depth > MaxConstantEvolvingDepth) 7676 return nullptr; 7677 7678 // Otherwise, we can evaluate this instruction if all of its operands are 7679 // constant or derived from a PHI node themselves. 7680 PHINode *PHI = nullptr; 7681 for (Value *Op : UseInst->operands()) { 7682 if (isa<Constant>(Op)) continue; 7683 7684 Instruction *OpInst = dyn_cast<Instruction>(Op); 7685 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7686 7687 PHINode *P = dyn_cast<PHINode>(OpInst); 7688 if (!P) 7689 // If this operand is already visited, reuse the prior result. 7690 // We may have P != PHI if this is the deepest point at which the 7691 // inconsistent paths meet. 7692 P = PHIMap.lookup(OpInst); 7693 if (!P) { 7694 // Recurse and memoize the results, whether a phi is found or not. 7695 // This recursive call invalidates pointers into PHIMap. 7696 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7697 PHIMap[OpInst] = P; 7698 } 7699 if (!P) 7700 return nullptr; // Not evolving from PHI 7701 if (PHI && PHI != P) 7702 return nullptr; // Evolving from multiple different PHIs. 7703 PHI = P; 7704 } 7705 // This is a expression evolving from a constant PHI! 7706 return PHI; 7707 } 7708 7709 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7710 /// in the loop that V is derived from. We allow arbitrary operations along the 7711 /// way, but the operands of an operation must either be constants or a value 7712 /// derived from a constant PHI. If this expression does not fit with these 7713 /// constraints, return null. 7714 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7715 Instruction *I = dyn_cast<Instruction>(V); 7716 if (!I || !canConstantEvolve(I, L)) return nullptr; 7717 7718 if (PHINode *PN = dyn_cast<PHINode>(I)) 7719 return PN; 7720 7721 // Record non-constant instructions contained by the loop. 7722 DenseMap<Instruction *, PHINode *> PHIMap; 7723 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7724 } 7725 7726 /// EvaluateExpression - Given an expression that passes the 7727 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7728 /// in the loop has the value PHIVal. If we can't fold this expression for some 7729 /// reason, return null. 7730 static Constant *EvaluateExpression(Value *V, const Loop *L, 7731 DenseMap<Instruction *, Constant *> &Vals, 7732 const DataLayout &DL, 7733 const TargetLibraryInfo *TLI) { 7734 // Convenient constant check, but redundant for recursive calls. 7735 if (Constant *C = dyn_cast<Constant>(V)) return C; 7736 Instruction *I = dyn_cast<Instruction>(V); 7737 if (!I) return nullptr; 7738 7739 if (Constant *C = Vals.lookup(I)) return C; 7740 7741 // An instruction inside the loop depends on a value outside the loop that we 7742 // weren't given a mapping for, or a value such as a call inside the loop. 7743 if (!canConstantEvolve(I, L)) return nullptr; 7744 7745 // An unmapped PHI can be due to a branch or another loop inside this loop, 7746 // or due to this not being the initial iteration through a loop where we 7747 // couldn't compute the evolution of this particular PHI last time. 7748 if (isa<PHINode>(I)) return nullptr; 7749 7750 std::vector<Constant*> Operands(I->getNumOperands()); 7751 7752 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7753 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7754 if (!Operand) { 7755 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7756 if (!Operands[i]) return nullptr; 7757 continue; 7758 } 7759 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7760 Vals[Operand] = C; 7761 if (!C) return nullptr; 7762 Operands[i] = C; 7763 } 7764 7765 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7766 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7767 Operands[1], DL, TLI); 7768 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7769 if (!LI->isVolatile()) 7770 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7771 } 7772 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7773 } 7774 7775 7776 // If every incoming value to PN except the one for BB is a specific Constant, 7777 // return that, else return nullptr. 7778 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7779 Constant *IncomingVal = nullptr; 7780 7781 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7782 if (PN->getIncomingBlock(i) == BB) 7783 continue; 7784 7785 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7786 if (!CurrentVal) 7787 return nullptr; 7788 7789 if (IncomingVal != CurrentVal) { 7790 if (IncomingVal) 7791 return nullptr; 7792 IncomingVal = CurrentVal; 7793 } 7794 } 7795 7796 return IncomingVal; 7797 } 7798 7799 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7800 /// in the header of its containing loop, we know the loop executes a 7801 /// constant number of times, and the PHI node is just a recurrence 7802 /// involving constants, fold it. 7803 Constant * 7804 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7805 const APInt &BEs, 7806 const Loop *L) { 7807 auto I = ConstantEvolutionLoopExitValue.find(PN); 7808 if (I != ConstantEvolutionLoopExitValue.end()) 7809 return I->second; 7810 7811 if (BEs.ugt(MaxBruteForceIterations)) 7812 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7813 7814 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7815 7816 DenseMap<Instruction *, Constant *> CurrentIterVals; 7817 BasicBlock *Header = L->getHeader(); 7818 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7819 7820 BasicBlock *Latch = L->getLoopLatch(); 7821 if (!Latch) 7822 return nullptr; 7823 7824 for (PHINode &PHI : Header->phis()) { 7825 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7826 CurrentIterVals[&PHI] = StartCST; 7827 } 7828 if (!CurrentIterVals.count(PN)) 7829 return RetVal = nullptr; 7830 7831 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7832 7833 // Execute the loop symbolically to determine the exit value. 7834 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7835 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7836 7837 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7838 unsigned IterationNum = 0; 7839 const DataLayout &DL = getDataLayout(); 7840 for (; ; ++IterationNum) { 7841 if (IterationNum == NumIterations) 7842 return RetVal = CurrentIterVals[PN]; // Got exit value! 7843 7844 // Compute the value of the PHIs for the next iteration. 7845 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7846 DenseMap<Instruction *, Constant *> NextIterVals; 7847 Constant *NextPHI = 7848 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7849 if (!NextPHI) 7850 return nullptr; // Couldn't evaluate! 7851 NextIterVals[PN] = NextPHI; 7852 7853 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7854 7855 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7856 // cease to be able to evaluate one of them or if they stop evolving, 7857 // because that doesn't necessarily prevent us from computing PN. 7858 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7859 for (const auto &I : CurrentIterVals) { 7860 PHINode *PHI = dyn_cast<PHINode>(I.first); 7861 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7862 PHIsToCompute.emplace_back(PHI, I.second); 7863 } 7864 // We use two distinct loops because EvaluateExpression may invalidate any 7865 // iterators into CurrentIterVals. 7866 for (const auto &I : PHIsToCompute) { 7867 PHINode *PHI = I.first; 7868 Constant *&NextPHI = NextIterVals[PHI]; 7869 if (!NextPHI) { // Not already computed. 7870 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7871 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7872 } 7873 if (NextPHI != I.second) 7874 StoppedEvolving = false; 7875 } 7876 7877 // If all entries in CurrentIterVals == NextIterVals then we can stop 7878 // iterating, the loop can't continue to change. 7879 if (StoppedEvolving) 7880 return RetVal = CurrentIterVals[PN]; 7881 7882 CurrentIterVals.swap(NextIterVals); 7883 } 7884 } 7885 7886 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7887 Value *Cond, 7888 bool ExitWhen) { 7889 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7890 if (!PN) return getCouldNotCompute(); 7891 7892 // If the loop is canonicalized, the PHI will have exactly two entries. 7893 // That's the only form we support here. 7894 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7895 7896 DenseMap<Instruction *, Constant *> CurrentIterVals; 7897 BasicBlock *Header = L->getHeader(); 7898 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7899 7900 BasicBlock *Latch = L->getLoopLatch(); 7901 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7902 7903 for (PHINode &PHI : Header->phis()) { 7904 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7905 CurrentIterVals[&PHI] = StartCST; 7906 } 7907 if (!CurrentIterVals.count(PN)) 7908 return getCouldNotCompute(); 7909 7910 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7911 // the loop symbolically to determine when the condition gets a value of 7912 // "ExitWhen". 7913 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7914 const DataLayout &DL = getDataLayout(); 7915 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7916 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7917 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7918 7919 // Couldn't symbolically evaluate. 7920 if (!CondVal) return getCouldNotCompute(); 7921 7922 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7923 ++NumBruteForceTripCountsComputed; 7924 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7925 } 7926 7927 // Update all the PHI nodes for the next iteration. 7928 DenseMap<Instruction *, Constant *> NextIterVals; 7929 7930 // Create a list of which PHIs we need to compute. We want to do this before 7931 // calling EvaluateExpression on them because that may invalidate iterators 7932 // into CurrentIterVals. 7933 SmallVector<PHINode *, 8> PHIsToCompute; 7934 for (const auto &I : CurrentIterVals) { 7935 PHINode *PHI = dyn_cast<PHINode>(I.first); 7936 if (!PHI || PHI->getParent() != Header) continue; 7937 PHIsToCompute.push_back(PHI); 7938 } 7939 for (PHINode *PHI : PHIsToCompute) { 7940 Constant *&NextPHI = NextIterVals[PHI]; 7941 if (NextPHI) continue; // Already computed! 7942 7943 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7944 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7945 } 7946 CurrentIterVals.swap(NextIterVals); 7947 } 7948 7949 // Too many iterations were needed to evaluate. 7950 return getCouldNotCompute(); 7951 } 7952 7953 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7954 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7955 ValuesAtScopes[V]; 7956 // Check to see if we've folded this expression at this loop before. 7957 for (auto &LS : Values) 7958 if (LS.first == L) 7959 return LS.second ? LS.second : V; 7960 7961 Values.emplace_back(L, nullptr); 7962 7963 // Otherwise compute it. 7964 const SCEV *C = computeSCEVAtScope(V, L); 7965 for (auto &LS : reverse(ValuesAtScopes[V])) 7966 if (LS.first == L) { 7967 LS.second = C; 7968 break; 7969 } 7970 return C; 7971 } 7972 7973 /// This builds up a Constant using the ConstantExpr interface. That way, we 7974 /// will return Constants for objects which aren't represented by a 7975 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7976 /// Returns NULL if the SCEV isn't representable as a Constant. 7977 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7978 switch (V->getSCEVType()) { 7979 case scCouldNotCompute: 7980 case scAddRecExpr: 7981 return nullptr; 7982 case scConstant: 7983 return cast<SCEVConstant>(V)->getValue(); 7984 case scUnknown: 7985 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7986 case scSignExtend: { 7987 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7988 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7989 return ConstantExpr::getSExt(CastOp, SS->getType()); 7990 return nullptr; 7991 } 7992 case scZeroExtend: { 7993 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7994 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7995 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7996 return nullptr; 7997 } 7998 case scTruncate: { 7999 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8000 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8001 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8002 return nullptr; 8003 } 8004 case scAddExpr: { 8005 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8006 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8007 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8008 unsigned AS = PTy->getAddressSpace(); 8009 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8010 C = ConstantExpr::getBitCast(C, DestPtrTy); 8011 } 8012 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8013 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8014 if (!C2) 8015 return nullptr; 8016 8017 // First pointer! 8018 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8019 unsigned AS = C2->getType()->getPointerAddressSpace(); 8020 std::swap(C, C2); 8021 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8022 // The offsets have been converted to bytes. We can add bytes to an 8023 // i8* by GEP with the byte count in the first index. 8024 C = ConstantExpr::getBitCast(C, DestPtrTy); 8025 } 8026 8027 // Don't bother trying to sum two pointers. We probably can't 8028 // statically compute a load that results from it anyway. 8029 if (C2->getType()->isPointerTy()) 8030 return nullptr; 8031 8032 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8033 if (PTy->getElementType()->isStructTy()) 8034 C2 = ConstantExpr::getIntegerCast( 8035 C2, Type::getInt32Ty(C->getContext()), true); 8036 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8037 } else 8038 C = ConstantExpr::getAdd(C, C2); 8039 } 8040 return C; 8041 } 8042 return nullptr; 8043 } 8044 case scMulExpr: { 8045 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8046 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8047 // Don't bother with pointers at all. 8048 if (C->getType()->isPointerTy()) 8049 return nullptr; 8050 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8051 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8052 if (!C2 || C2->getType()->isPointerTy()) 8053 return nullptr; 8054 C = ConstantExpr::getMul(C, C2); 8055 } 8056 return C; 8057 } 8058 return nullptr; 8059 } 8060 case scUDivExpr: { 8061 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8062 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8063 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8064 if (LHS->getType() == RHS->getType()) 8065 return ConstantExpr::getUDiv(LHS, RHS); 8066 return nullptr; 8067 } 8068 case scSMaxExpr: 8069 case scUMaxExpr: 8070 case scSMinExpr: 8071 case scUMinExpr: 8072 return nullptr; // TODO: smax, umax, smin, umax. 8073 } 8074 llvm_unreachable("Unknown SCEV kind!"); 8075 } 8076 8077 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8078 if (isa<SCEVConstant>(V)) return V; 8079 8080 // If this instruction is evolved from a constant-evolving PHI, compute the 8081 // exit value from the loop without using SCEVs. 8082 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8083 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8084 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8085 const Loop *CurrLoop = this->LI[I->getParent()]; 8086 // Looking for loop exit value. 8087 if (CurrLoop && CurrLoop->getParentLoop() == L && 8088 PN->getParent() == CurrLoop->getHeader()) { 8089 // Okay, there is no closed form solution for the PHI node. Check 8090 // to see if the loop that contains it has a known backedge-taken 8091 // count. If so, we may be able to force computation of the exit 8092 // value. 8093 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8094 // This trivial case can show up in some degenerate cases where 8095 // the incoming IR has not yet been fully simplified. 8096 if (BackedgeTakenCount->isZero()) { 8097 Value *InitValue = nullptr; 8098 bool MultipleInitValues = false; 8099 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8100 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8101 if (!InitValue) 8102 InitValue = PN->getIncomingValue(i); 8103 else if (InitValue != PN->getIncomingValue(i)) { 8104 MultipleInitValues = true; 8105 break; 8106 } 8107 } 8108 } 8109 if (!MultipleInitValues && InitValue) 8110 return getSCEV(InitValue); 8111 } 8112 // Do we have a loop invariant value flowing around the backedge 8113 // for a loop which must execute the backedge? 8114 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8115 isKnownPositive(BackedgeTakenCount) && 8116 PN->getNumIncomingValues() == 2) { 8117 8118 unsigned InLoopPred = 8119 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8120 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8121 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8122 return getSCEV(BackedgeVal); 8123 } 8124 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8125 // Okay, we know how many times the containing loop executes. If 8126 // this is a constant evolving PHI node, get the final value at 8127 // the specified iteration number. 8128 Constant *RV = getConstantEvolutionLoopExitValue( 8129 PN, BTCC->getAPInt(), CurrLoop); 8130 if (RV) return getSCEV(RV); 8131 } 8132 } 8133 8134 // If there is a single-input Phi, evaluate it at our scope. If we can 8135 // prove that this replacement does not break LCSSA form, use new value. 8136 if (PN->getNumOperands() == 1) { 8137 const SCEV *Input = getSCEV(PN->getOperand(0)); 8138 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8139 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8140 // for the simplest case just support constants. 8141 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8142 } 8143 } 8144 8145 // Okay, this is an expression that we cannot symbolically evaluate 8146 // into a SCEV. Check to see if it's possible to symbolically evaluate 8147 // the arguments into constants, and if so, try to constant propagate the 8148 // result. This is particularly useful for computing loop exit values. 8149 if (CanConstantFold(I)) { 8150 SmallVector<Constant *, 4> Operands; 8151 bool MadeImprovement = false; 8152 for (Value *Op : I->operands()) { 8153 if (Constant *C = dyn_cast<Constant>(Op)) { 8154 Operands.push_back(C); 8155 continue; 8156 } 8157 8158 // If any of the operands is non-constant and if they are 8159 // non-integer and non-pointer, don't even try to analyze them 8160 // with scev techniques. 8161 if (!isSCEVable(Op->getType())) 8162 return V; 8163 8164 const SCEV *OrigV = getSCEV(Op); 8165 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8166 MadeImprovement |= OrigV != OpV; 8167 8168 Constant *C = BuildConstantFromSCEV(OpV); 8169 if (!C) return V; 8170 if (C->getType() != Op->getType()) 8171 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8172 Op->getType(), 8173 false), 8174 C, Op->getType()); 8175 Operands.push_back(C); 8176 } 8177 8178 // Check to see if getSCEVAtScope actually made an improvement. 8179 if (MadeImprovement) { 8180 Constant *C = nullptr; 8181 const DataLayout &DL = getDataLayout(); 8182 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8183 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8184 Operands[1], DL, &TLI); 8185 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8186 if (!Load->isVolatile()) 8187 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8188 DL); 8189 } else 8190 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8191 if (!C) return V; 8192 return getSCEV(C); 8193 } 8194 } 8195 } 8196 8197 // This is some other type of SCEVUnknown, just return it. 8198 return V; 8199 } 8200 8201 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8202 // Avoid performing the look-up in the common case where the specified 8203 // expression has no loop-variant portions. 8204 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8205 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8206 if (OpAtScope != Comm->getOperand(i)) { 8207 // Okay, at least one of these operands is loop variant but might be 8208 // foldable. Build a new instance of the folded commutative expression. 8209 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8210 Comm->op_begin()+i); 8211 NewOps.push_back(OpAtScope); 8212 8213 for (++i; i != e; ++i) { 8214 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8215 NewOps.push_back(OpAtScope); 8216 } 8217 if (isa<SCEVAddExpr>(Comm)) 8218 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8219 if (isa<SCEVMulExpr>(Comm)) 8220 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8221 if (isa<SCEVMinMaxExpr>(Comm)) 8222 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8223 llvm_unreachable("Unknown commutative SCEV type!"); 8224 } 8225 } 8226 // If we got here, all operands are loop invariant. 8227 return Comm; 8228 } 8229 8230 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8231 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8232 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8233 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8234 return Div; // must be loop invariant 8235 return getUDivExpr(LHS, RHS); 8236 } 8237 8238 // If this is a loop recurrence for a loop that does not contain L, then we 8239 // are dealing with the final value computed by the loop. 8240 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8241 // First, attempt to evaluate each operand. 8242 // Avoid performing the look-up in the common case where the specified 8243 // expression has no loop-variant portions. 8244 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8245 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8246 if (OpAtScope == AddRec->getOperand(i)) 8247 continue; 8248 8249 // Okay, at least one of these operands is loop variant but might be 8250 // foldable. Build a new instance of the folded commutative expression. 8251 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8252 AddRec->op_begin()+i); 8253 NewOps.push_back(OpAtScope); 8254 for (++i; i != e; ++i) 8255 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8256 8257 const SCEV *FoldedRec = 8258 getAddRecExpr(NewOps, AddRec->getLoop(), 8259 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8260 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8261 // The addrec may be folded to a nonrecurrence, for example, if the 8262 // induction variable is multiplied by zero after constant folding. Go 8263 // ahead and return the folded value. 8264 if (!AddRec) 8265 return FoldedRec; 8266 break; 8267 } 8268 8269 // If the scope is outside the addrec's loop, evaluate it by using the 8270 // loop exit value of the addrec. 8271 if (!AddRec->getLoop()->contains(L)) { 8272 // To evaluate this recurrence, we need to know how many times the AddRec 8273 // loop iterates. Compute this now. 8274 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8275 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8276 8277 // Then, evaluate the AddRec. 8278 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8279 } 8280 8281 return AddRec; 8282 } 8283 8284 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8285 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8286 if (Op == Cast->getOperand()) 8287 return Cast; // must be loop invariant 8288 return getZeroExtendExpr(Op, Cast->getType()); 8289 } 8290 8291 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8292 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8293 if (Op == Cast->getOperand()) 8294 return Cast; // must be loop invariant 8295 return getSignExtendExpr(Op, Cast->getType()); 8296 } 8297 8298 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8299 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8300 if (Op == Cast->getOperand()) 8301 return Cast; // must be loop invariant 8302 return getTruncateExpr(Op, Cast->getType()); 8303 } 8304 8305 llvm_unreachable("Unknown SCEV type!"); 8306 } 8307 8308 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8309 return getSCEVAtScope(getSCEV(V), L); 8310 } 8311 8312 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8313 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8314 return stripInjectiveFunctions(ZExt->getOperand()); 8315 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8316 return stripInjectiveFunctions(SExt->getOperand()); 8317 return S; 8318 } 8319 8320 /// Finds the minimum unsigned root of the following equation: 8321 /// 8322 /// A * X = B (mod N) 8323 /// 8324 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8325 /// A and B isn't important. 8326 /// 8327 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8328 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8329 ScalarEvolution &SE) { 8330 uint32_t BW = A.getBitWidth(); 8331 assert(BW == SE.getTypeSizeInBits(B->getType())); 8332 assert(A != 0 && "A must be non-zero."); 8333 8334 // 1. D = gcd(A, N) 8335 // 8336 // The gcd of A and N may have only one prime factor: 2. The number of 8337 // trailing zeros in A is its multiplicity 8338 uint32_t Mult2 = A.countTrailingZeros(); 8339 // D = 2^Mult2 8340 8341 // 2. Check if B is divisible by D. 8342 // 8343 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8344 // is not less than multiplicity of this prime factor for D. 8345 if (SE.GetMinTrailingZeros(B) < Mult2) 8346 return SE.getCouldNotCompute(); 8347 8348 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8349 // modulo (N / D). 8350 // 8351 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8352 // (N / D) in general. The inverse itself always fits into BW bits, though, 8353 // so we immediately truncate it. 8354 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8355 APInt Mod(BW + 1, 0); 8356 Mod.setBit(BW - Mult2); // Mod = N / D 8357 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8358 8359 // 4. Compute the minimum unsigned root of the equation: 8360 // I * (B / D) mod (N / D) 8361 // To simplify the computation, we factor out the divide by D: 8362 // (I * B mod N) / D 8363 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8364 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8365 } 8366 8367 /// For a given quadratic addrec, generate coefficients of the corresponding 8368 /// quadratic equation, multiplied by a common value to ensure that they are 8369 /// integers. 8370 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8371 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8372 /// were multiplied by, and BitWidth is the bit width of the original addrec 8373 /// coefficients. 8374 /// This function returns None if the addrec coefficients are not compile- 8375 /// time constants. 8376 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8377 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8378 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8379 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8380 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8381 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8382 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8383 << *AddRec << '\n'); 8384 8385 // We currently can only solve this if the coefficients are constants. 8386 if (!LC || !MC || !NC) { 8387 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8388 return None; 8389 } 8390 8391 APInt L = LC->getAPInt(); 8392 APInt M = MC->getAPInt(); 8393 APInt N = NC->getAPInt(); 8394 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8395 8396 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8397 unsigned NewWidth = BitWidth + 1; 8398 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8399 << BitWidth << '\n'); 8400 // The sign-extension (as opposed to a zero-extension) here matches the 8401 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8402 N = N.sext(NewWidth); 8403 M = M.sext(NewWidth); 8404 L = L.sext(NewWidth); 8405 8406 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8407 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8408 // L+M, L+2M+N, L+3M+3N, ... 8409 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8410 // 8411 // The equation Acc = 0 is then 8412 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8413 // In a quadratic form it becomes: 8414 // N n^2 + (2M-N) n + 2L = 0. 8415 8416 APInt A = N; 8417 APInt B = 2 * M - A; 8418 APInt C = 2 * L; 8419 APInt T = APInt(NewWidth, 2); 8420 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8421 << "x + " << C << ", coeff bw: " << NewWidth 8422 << ", multiplied by " << T << '\n'); 8423 return std::make_tuple(A, B, C, T, BitWidth); 8424 } 8425 8426 /// Helper function to compare optional APInts: 8427 /// (a) if X and Y both exist, return min(X, Y), 8428 /// (b) if neither X nor Y exist, return None, 8429 /// (c) if exactly one of X and Y exists, return that value. 8430 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8431 if (X.hasValue() && Y.hasValue()) { 8432 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8433 APInt XW = X->sextOrSelf(W); 8434 APInt YW = Y->sextOrSelf(W); 8435 return XW.slt(YW) ? *X : *Y; 8436 } 8437 if (!X.hasValue() && !Y.hasValue()) 8438 return None; 8439 return X.hasValue() ? *X : *Y; 8440 } 8441 8442 /// Helper function to truncate an optional APInt to a given BitWidth. 8443 /// When solving addrec-related equations, it is preferable to return a value 8444 /// that has the same bit width as the original addrec's coefficients. If the 8445 /// solution fits in the original bit width, truncate it (except for i1). 8446 /// Returning a value of a different bit width may inhibit some optimizations. 8447 /// 8448 /// In general, a solution to a quadratic equation generated from an addrec 8449 /// may require BW+1 bits, where BW is the bit width of the addrec's 8450 /// coefficients. The reason is that the coefficients of the quadratic 8451 /// equation are BW+1 bits wide (to avoid truncation when converting from 8452 /// the addrec to the equation). 8453 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8454 if (!X.hasValue()) 8455 return None; 8456 unsigned W = X->getBitWidth(); 8457 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8458 return X->trunc(BitWidth); 8459 return X; 8460 } 8461 8462 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8463 /// iterations. The values L, M, N are assumed to be signed, and they 8464 /// should all have the same bit widths. 8465 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8466 /// where BW is the bit width of the addrec's coefficients. 8467 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8468 /// returned as such, otherwise the bit width of the returned value may 8469 /// be greater than BW. 8470 /// 8471 /// This function returns None if 8472 /// (a) the addrec coefficients are not constant, or 8473 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8474 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8475 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8476 static Optional<APInt> 8477 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8478 APInt A, B, C, M; 8479 unsigned BitWidth; 8480 auto T = GetQuadraticEquation(AddRec); 8481 if (!T.hasValue()) 8482 return None; 8483 8484 std::tie(A, B, C, M, BitWidth) = *T; 8485 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8486 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8487 if (!X.hasValue()) 8488 return None; 8489 8490 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8491 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8492 if (!V->isZero()) 8493 return None; 8494 8495 return TruncIfPossible(X, BitWidth); 8496 } 8497 8498 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8499 /// iterations. The values M, N are assumed to be signed, and they 8500 /// should all have the same bit widths. 8501 /// Find the least n such that c(n) does not belong to the given range, 8502 /// while c(n-1) does. 8503 /// 8504 /// This function returns None if 8505 /// (a) the addrec coefficients are not constant, or 8506 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8507 /// bounds of the range. 8508 static Optional<APInt> 8509 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8510 const ConstantRange &Range, ScalarEvolution &SE) { 8511 assert(AddRec->getOperand(0)->isZero() && 8512 "Starting value of addrec should be 0"); 8513 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8514 << Range << ", addrec " << *AddRec << '\n'); 8515 // This case is handled in getNumIterationsInRange. Here we can assume that 8516 // we start in the range. 8517 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8518 "Addrec's initial value should be in range"); 8519 8520 APInt A, B, C, M; 8521 unsigned BitWidth; 8522 auto T = GetQuadraticEquation(AddRec); 8523 if (!T.hasValue()) 8524 return None; 8525 8526 // Be careful about the return value: there can be two reasons for not 8527 // returning an actual number. First, if no solutions to the equations 8528 // were found, and second, if the solutions don't leave the given range. 8529 // The first case means that the actual solution is "unknown", the second 8530 // means that it's known, but not valid. If the solution is unknown, we 8531 // cannot make any conclusions. 8532 // Return a pair: the optional solution and a flag indicating if the 8533 // solution was found. 8534 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8535 // Solve for signed overflow and unsigned overflow, pick the lower 8536 // solution. 8537 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8538 << Bound << " (before multiplying by " << M << ")\n"); 8539 Bound *= M; // The quadratic equation multiplier. 8540 8541 Optional<APInt> SO = None; 8542 if (BitWidth > 1) { 8543 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8544 "signed overflow\n"); 8545 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8546 } 8547 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8548 "unsigned overflow\n"); 8549 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8550 BitWidth+1); 8551 8552 auto LeavesRange = [&] (const APInt &X) { 8553 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8554 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8555 if (Range.contains(V0->getValue())) 8556 return false; 8557 // X should be at least 1, so X-1 is non-negative. 8558 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8559 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8560 if (Range.contains(V1->getValue())) 8561 return true; 8562 return false; 8563 }; 8564 8565 // If SolveQuadraticEquationWrap returns None, it means that there can 8566 // be a solution, but the function failed to find it. We cannot treat it 8567 // as "no solution". 8568 if (!SO.hasValue() || !UO.hasValue()) 8569 return { None, false }; 8570 8571 // Check the smaller value first to see if it leaves the range. 8572 // At this point, both SO and UO must have values. 8573 Optional<APInt> Min = MinOptional(SO, UO); 8574 if (LeavesRange(*Min)) 8575 return { Min, true }; 8576 Optional<APInt> Max = Min == SO ? UO : SO; 8577 if (LeavesRange(*Max)) 8578 return { Max, true }; 8579 8580 // Solutions were found, but were eliminated, hence the "true". 8581 return { None, true }; 8582 }; 8583 8584 std::tie(A, B, C, M, BitWidth) = *T; 8585 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8586 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8587 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8588 auto SL = SolveForBoundary(Lower); 8589 auto SU = SolveForBoundary(Upper); 8590 // If any of the solutions was unknown, no meaninigful conclusions can 8591 // be made. 8592 if (!SL.second || !SU.second) 8593 return None; 8594 8595 // Claim: The correct solution is not some value between Min and Max. 8596 // 8597 // Justification: Assuming that Min and Max are different values, one of 8598 // them is when the first signed overflow happens, the other is when the 8599 // first unsigned overflow happens. Crossing the range boundary is only 8600 // possible via an overflow (treating 0 as a special case of it, modeling 8601 // an overflow as crossing k*2^W for some k). 8602 // 8603 // The interesting case here is when Min was eliminated as an invalid 8604 // solution, but Max was not. The argument is that if there was another 8605 // overflow between Min and Max, it would also have been eliminated if 8606 // it was considered. 8607 // 8608 // For a given boundary, it is possible to have two overflows of the same 8609 // type (signed/unsigned) without having the other type in between: this 8610 // can happen when the vertex of the parabola is between the iterations 8611 // corresponding to the overflows. This is only possible when the two 8612 // overflows cross k*2^W for the same k. In such case, if the second one 8613 // left the range (and was the first one to do so), the first overflow 8614 // would have to enter the range, which would mean that either we had left 8615 // the range before or that we started outside of it. Both of these cases 8616 // are contradictions. 8617 // 8618 // Claim: In the case where SolveForBoundary returns None, the correct 8619 // solution is not some value between the Max for this boundary and the 8620 // Min of the other boundary. 8621 // 8622 // Justification: Assume that we had such Max_A and Min_B corresponding 8623 // to range boundaries A and B and such that Max_A < Min_B. If there was 8624 // a solution between Max_A and Min_B, it would have to be caused by an 8625 // overflow corresponding to either A or B. It cannot correspond to B, 8626 // since Min_B is the first occurrence of such an overflow. If it 8627 // corresponded to A, it would have to be either a signed or an unsigned 8628 // overflow that is larger than both eliminated overflows for A. But 8629 // between the eliminated overflows and this overflow, the values would 8630 // cover the entire value space, thus crossing the other boundary, which 8631 // is a contradiction. 8632 8633 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8634 } 8635 8636 ScalarEvolution::ExitLimit 8637 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8638 bool AllowPredicates) { 8639 8640 // This is only used for loops with a "x != y" exit test. The exit condition 8641 // is now expressed as a single expression, V = x-y. So the exit test is 8642 // effectively V != 0. We know and take advantage of the fact that this 8643 // expression only being used in a comparison by zero context. 8644 8645 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8646 // If the value is a constant 8647 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8648 // If the value is already zero, the branch will execute zero times. 8649 if (C->getValue()->isZero()) return C; 8650 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8651 } 8652 8653 const SCEVAddRecExpr *AddRec = 8654 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8655 8656 if (!AddRec && AllowPredicates) 8657 // Try to make this an AddRec using runtime tests, in the first X 8658 // iterations of this loop, where X is the SCEV expression found by the 8659 // algorithm below. 8660 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8661 8662 if (!AddRec || AddRec->getLoop() != L) 8663 return getCouldNotCompute(); 8664 8665 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8666 // the quadratic equation to solve it. 8667 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8668 // We can only use this value if the chrec ends up with an exact zero 8669 // value at this index. When solving for "X*X != 5", for example, we 8670 // should not accept a root of 2. 8671 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8672 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8673 return ExitLimit(R, R, false, Predicates); 8674 } 8675 return getCouldNotCompute(); 8676 } 8677 8678 // Otherwise we can only handle this if it is affine. 8679 if (!AddRec->isAffine()) 8680 return getCouldNotCompute(); 8681 8682 // If this is an affine expression, the execution count of this branch is 8683 // the minimum unsigned root of the following equation: 8684 // 8685 // Start + Step*N = 0 (mod 2^BW) 8686 // 8687 // equivalent to: 8688 // 8689 // Step*N = -Start (mod 2^BW) 8690 // 8691 // where BW is the common bit width of Start and Step. 8692 8693 // Get the initial value for the loop. 8694 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8695 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8696 8697 // For now we handle only constant steps. 8698 // 8699 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8700 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8701 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8702 // We have not yet seen any such cases. 8703 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8704 if (!StepC || StepC->getValue()->isZero()) 8705 return getCouldNotCompute(); 8706 8707 // For positive steps (counting up until unsigned overflow): 8708 // N = -Start/Step (as unsigned) 8709 // For negative steps (counting down to zero): 8710 // N = Start/-Step 8711 // First compute the unsigned distance from zero in the direction of Step. 8712 bool CountDown = StepC->getAPInt().isNegative(); 8713 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8714 8715 // Handle unitary steps, which cannot wraparound. 8716 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8717 // N = Distance (as unsigned) 8718 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8719 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 8720 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 8721 if (MaxBECountBase.ult(MaxBECount)) 8722 MaxBECount = MaxBECountBase; 8723 8724 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8725 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8726 // case, and see if we can improve the bound. 8727 // 8728 // Explicitly handling this here is necessary because getUnsignedRange 8729 // isn't context-sensitive; it doesn't know that we only care about the 8730 // range inside the loop. 8731 const SCEV *Zero = getZero(Distance->getType()); 8732 const SCEV *One = getOne(Distance->getType()); 8733 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8734 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8735 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8736 // as "unsigned_max(Distance + 1) - 1". 8737 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8738 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8739 } 8740 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8741 } 8742 8743 // If the condition controls loop exit (the loop exits only if the expression 8744 // is true) and the addition is no-wrap we can use unsigned divide to 8745 // compute the backedge count. In this case, the step may not divide the 8746 // distance, but we don't care because if the condition is "missed" the loop 8747 // will have undefined behavior due to wrapping. 8748 if (ControlsExit && AddRec->hasNoSelfWrap() && 8749 loopHasNoAbnormalExits(AddRec->getLoop())) { 8750 const SCEV *Exact = 8751 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8752 const SCEV *Max = 8753 Exact == getCouldNotCompute() 8754 ? Exact 8755 : getConstant(getUnsignedRangeMax(Exact)); 8756 return ExitLimit(Exact, Max, false, Predicates); 8757 } 8758 8759 // Solve the general equation. 8760 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8761 getNegativeSCEV(Start), *this); 8762 const SCEV *M = E == getCouldNotCompute() 8763 ? E 8764 : getConstant(getUnsignedRangeMax(E)); 8765 return ExitLimit(E, M, false, Predicates); 8766 } 8767 8768 ScalarEvolution::ExitLimit 8769 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8770 // Loops that look like: while (X == 0) are very strange indeed. We don't 8771 // handle them yet except for the trivial case. This could be expanded in the 8772 // future as needed. 8773 8774 // If the value is a constant, check to see if it is known to be non-zero 8775 // already. If so, the backedge will execute zero times. 8776 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8777 if (!C->getValue()->isZero()) 8778 return getZero(C->getType()); 8779 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8780 } 8781 8782 // We could implement others, but I really doubt anyone writes loops like 8783 // this, and if they did, they would already be constant folded. 8784 return getCouldNotCompute(); 8785 } 8786 8787 std::pair<const BasicBlock *, const BasicBlock *> 8788 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 8789 const { 8790 // If the block has a unique predecessor, then there is no path from the 8791 // predecessor to the block that does not go through the direct edge 8792 // from the predecessor to the block. 8793 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 8794 return {Pred, BB}; 8795 8796 // A loop's header is defined to be a block that dominates the loop. 8797 // If the header has a unique predecessor outside the loop, it must be 8798 // a block that has exactly one successor that can reach the loop. 8799 if (const Loop *L = LI.getLoopFor(BB)) 8800 return {L->getLoopPredecessor(), L->getHeader()}; 8801 8802 return {nullptr, nullptr}; 8803 } 8804 8805 /// SCEV structural equivalence is usually sufficient for testing whether two 8806 /// expressions are equal, however for the purposes of looking for a condition 8807 /// guarding a loop, it can be useful to be a little more general, since a 8808 /// front-end may have replicated the controlling expression. 8809 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8810 // Quick check to see if they are the same SCEV. 8811 if (A == B) return true; 8812 8813 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8814 // Not all instructions that are "identical" compute the same value. For 8815 // instance, two distinct alloca instructions allocating the same type are 8816 // identical and do not read memory; but compute distinct values. 8817 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8818 }; 8819 8820 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8821 // two different instructions with the same value. Check for this case. 8822 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8823 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8824 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8825 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8826 if (ComputesEqualValues(AI, BI)) 8827 return true; 8828 8829 // Otherwise assume they may have a different value. 8830 return false; 8831 } 8832 8833 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8834 const SCEV *&LHS, const SCEV *&RHS, 8835 unsigned Depth) { 8836 bool Changed = false; 8837 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8838 // '0 != 0'. 8839 auto TrivialCase = [&](bool TriviallyTrue) { 8840 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8841 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8842 return true; 8843 }; 8844 // If we hit the max recursion limit bail out. 8845 if (Depth >= 3) 8846 return false; 8847 8848 // Canonicalize a constant to the right side. 8849 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8850 // Check for both operands constant. 8851 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8852 if (ConstantExpr::getICmp(Pred, 8853 LHSC->getValue(), 8854 RHSC->getValue())->isNullValue()) 8855 return TrivialCase(false); 8856 else 8857 return TrivialCase(true); 8858 } 8859 // Otherwise swap the operands to put the constant on the right. 8860 std::swap(LHS, RHS); 8861 Pred = ICmpInst::getSwappedPredicate(Pred); 8862 Changed = true; 8863 } 8864 8865 // If we're comparing an addrec with a value which is loop-invariant in the 8866 // addrec's loop, put the addrec on the left. Also make a dominance check, 8867 // as both operands could be addrecs loop-invariant in each other's loop. 8868 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8869 const Loop *L = AR->getLoop(); 8870 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8871 std::swap(LHS, RHS); 8872 Pred = ICmpInst::getSwappedPredicate(Pred); 8873 Changed = true; 8874 } 8875 } 8876 8877 // If there's a constant operand, canonicalize comparisons with boundary 8878 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8879 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8880 const APInt &RA = RC->getAPInt(); 8881 8882 bool SimplifiedByConstantRange = false; 8883 8884 if (!ICmpInst::isEquality(Pred)) { 8885 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8886 if (ExactCR.isFullSet()) 8887 return TrivialCase(true); 8888 else if (ExactCR.isEmptySet()) 8889 return TrivialCase(false); 8890 8891 APInt NewRHS; 8892 CmpInst::Predicate NewPred; 8893 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8894 ICmpInst::isEquality(NewPred)) { 8895 // We were able to convert an inequality to an equality. 8896 Pred = NewPred; 8897 RHS = getConstant(NewRHS); 8898 Changed = SimplifiedByConstantRange = true; 8899 } 8900 } 8901 8902 if (!SimplifiedByConstantRange) { 8903 switch (Pred) { 8904 default: 8905 break; 8906 case ICmpInst::ICMP_EQ: 8907 case ICmpInst::ICMP_NE: 8908 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8909 if (!RA) 8910 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8911 if (const SCEVMulExpr *ME = 8912 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8913 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8914 ME->getOperand(0)->isAllOnesValue()) { 8915 RHS = AE->getOperand(1); 8916 LHS = ME->getOperand(1); 8917 Changed = true; 8918 } 8919 break; 8920 8921 8922 // The "Should have been caught earlier!" messages refer to the fact 8923 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8924 // should have fired on the corresponding cases, and canonicalized the 8925 // check to trivial case. 8926 8927 case ICmpInst::ICMP_UGE: 8928 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8929 Pred = ICmpInst::ICMP_UGT; 8930 RHS = getConstant(RA - 1); 8931 Changed = true; 8932 break; 8933 case ICmpInst::ICMP_ULE: 8934 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8935 Pred = ICmpInst::ICMP_ULT; 8936 RHS = getConstant(RA + 1); 8937 Changed = true; 8938 break; 8939 case ICmpInst::ICMP_SGE: 8940 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8941 Pred = ICmpInst::ICMP_SGT; 8942 RHS = getConstant(RA - 1); 8943 Changed = true; 8944 break; 8945 case ICmpInst::ICMP_SLE: 8946 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8947 Pred = ICmpInst::ICMP_SLT; 8948 RHS = getConstant(RA + 1); 8949 Changed = true; 8950 break; 8951 } 8952 } 8953 } 8954 8955 // Check for obvious equality. 8956 if (HasSameValue(LHS, RHS)) { 8957 if (ICmpInst::isTrueWhenEqual(Pred)) 8958 return TrivialCase(true); 8959 if (ICmpInst::isFalseWhenEqual(Pred)) 8960 return TrivialCase(false); 8961 } 8962 8963 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8964 // adding or subtracting 1 from one of the operands. 8965 switch (Pred) { 8966 case ICmpInst::ICMP_SLE: 8967 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8968 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8969 SCEV::FlagNSW); 8970 Pred = ICmpInst::ICMP_SLT; 8971 Changed = true; 8972 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8973 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8974 SCEV::FlagNSW); 8975 Pred = ICmpInst::ICMP_SLT; 8976 Changed = true; 8977 } 8978 break; 8979 case ICmpInst::ICMP_SGE: 8980 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8981 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8982 SCEV::FlagNSW); 8983 Pred = ICmpInst::ICMP_SGT; 8984 Changed = true; 8985 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8986 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8987 SCEV::FlagNSW); 8988 Pred = ICmpInst::ICMP_SGT; 8989 Changed = true; 8990 } 8991 break; 8992 case ICmpInst::ICMP_ULE: 8993 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8994 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8995 SCEV::FlagNUW); 8996 Pred = ICmpInst::ICMP_ULT; 8997 Changed = true; 8998 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8999 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9000 Pred = ICmpInst::ICMP_ULT; 9001 Changed = true; 9002 } 9003 break; 9004 case ICmpInst::ICMP_UGE: 9005 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9006 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9007 Pred = ICmpInst::ICMP_UGT; 9008 Changed = true; 9009 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9010 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9011 SCEV::FlagNUW); 9012 Pred = ICmpInst::ICMP_UGT; 9013 Changed = true; 9014 } 9015 break; 9016 default: 9017 break; 9018 } 9019 9020 // TODO: More simplifications are possible here. 9021 9022 // Recursively simplify until we either hit a recursion limit or nothing 9023 // changes. 9024 if (Changed) 9025 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9026 9027 return Changed; 9028 } 9029 9030 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9031 return getSignedRangeMax(S).isNegative(); 9032 } 9033 9034 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9035 return getSignedRangeMin(S).isStrictlyPositive(); 9036 } 9037 9038 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9039 return !getSignedRangeMin(S).isNegative(); 9040 } 9041 9042 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9043 return !getSignedRangeMax(S).isStrictlyPositive(); 9044 } 9045 9046 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9047 return isKnownNegative(S) || isKnownPositive(S); 9048 } 9049 9050 std::pair<const SCEV *, const SCEV *> 9051 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9052 // Compute SCEV on entry of loop L. 9053 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9054 if (Start == getCouldNotCompute()) 9055 return { Start, Start }; 9056 // Compute post increment SCEV for loop L. 9057 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9058 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9059 return { Start, PostInc }; 9060 } 9061 9062 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9063 const SCEV *LHS, const SCEV *RHS) { 9064 // First collect all loops. 9065 SmallPtrSet<const Loop *, 8> LoopsUsed; 9066 getUsedLoops(LHS, LoopsUsed); 9067 getUsedLoops(RHS, LoopsUsed); 9068 9069 if (LoopsUsed.empty()) 9070 return false; 9071 9072 // Domination relationship must be a linear order on collected loops. 9073 #ifndef NDEBUG 9074 for (auto *L1 : LoopsUsed) 9075 for (auto *L2 : LoopsUsed) 9076 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9077 DT.dominates(L2->getHeader(), L1->getHeader())) && 9078 "Domination relationship is not a linear order"); 9079 #endif 9080 9081 const Loop *MDL = 9082 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9083 [&](const Loop *L1, const Loop *L2) { 9084 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9085 }); 9086 9087 // Get init and post increment value for LHS. 9088 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9089 // if LHS contains unknown non-invariant SCEV then bail out. 9090 if (SplitLHS.first == getCouldNotCompute()) 9091 return false; 9092 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9093 // Get init and post increment value for RHS. 9094 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9095 // if RHS contains unknown non-invariant SCEV then bail out. 9096 if (SplitRHS.first == getCouldNotCompute()) 9097 return false; 9098 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9099 // It is possible that init SCEV contains an invariant load but it does 9100 // not dominate MDL and is not available at MDL loop entry, so we should 9101 // check it here. 9102 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9103 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9104 return false; 9105 9106 // It seems backedge guard check is faster than entry one so in some cases 9107 // it can speed up whole estimation by short circuit 9108 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9109 SplitRHS.second) && 9110 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9111 } 9112 9113 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9114 const SCEV *LHS, const SCEV *RHS) { 9115 // Canonicalize the inputs first. 9116 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9117 9118 if (isKnownViaInduction(Pred, LHS, RHS)) 9119 return true; 9120 9121 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9122 return true; 9123 9124 // Otherwise see what can be done with some simple reasoning. 9125 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9126 } 9127 9128 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9129 const SCEV *LHS, const SCEV *RHS, 9130 const Instruction *Context) { 9131 // TODO: Analyze guards and assumes from Context's block. 9132 return isKnownPredicate(Pred, LHS, RHS) || 9133 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9134 } 9135 9136 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9137 const SCEVAddRecExpr *LHS, 9138 const SCEV *RHS) { 9139 const Loop *L = LHS->getLoop(); 9140 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9141 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9142 } 9143 9144 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9145 ICmpInst::Predicate Pred, 9146 bool &Increasing) { 9147 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9148 9149 #ifndef NDEBUG 9150 // Verify an invariant: inverting the predicate should turn a monotonically 9151 // increasing change to a monotonically decreasing one, and vice versa. 9152 bool IncreasingSwapped; 9153 bool ResultSwapped = isMonotonicPredicateImpl( 9154 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9155 9156 assert(Result == ResultSwapped && "should be able to analyze both!"); 9157 if (ResultSwapped) 9158 assert(Increasing == !IncreasingSwapped && 9159 "monotonicity should flip as we flip the predicate"); 9160 #endif 9161 9162 return Result; 9163 } 9164 9165 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9166 ICmpInst::Predicate Pred, 9167 bool &Increasing) { 9168 9169 // A zero step value for LHS means the induction variable is essentially a 9170 // loop invariant value. We don't really depend on the predicate actually 9171 // flipping from false to true (for increasing predicates, and the other way 9172 // around for decreasing predicates), all we care about is that *if* the 9173 // predicate changes then it only changes from false to true. 9174 // 9175 // A zero step value in itself is not very useful, but there may be places 9176 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9177 // as general as possible. 9178 9179 switch (Pred) { 9180 default: 9181 return false; // Conservative answer 9182 9183 case ICmpInst::ICMP_UGT: 9184 case ICmpInst::ICMP_UGE: 9185 case ICmpInst::ICMP_ULT: 9186 case ICmpInst::ICMP_ULE: 9187 if (!LHS->hasNoUnsignedWrap()) 9188 return false; 9189 9190 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9191 return true; 9192 9193 case ICmpInst::ICMP_SGT: 9194 case ICmpInst::ICMP_SGE: 9195 case ICmpInst::ICMP_SLT: 9196 case ICmpInst::ICMP_SLE: { 9197 if (!LHS->hasNoSignedWrap()) 9198 return false; 9199 9200 const SCEV *Step = LHS->getStepRecurrence(*this); 9201 9202 if (isKnownNonNegative(Step)) { 9203 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9204 return true; 9205 } 9206 9207 if (isKnownNonPositive(Step)) { 9208 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9209 return true; 9210 } 9211 9212 return false; 9213 } 9214 9215 } 9216 9217 llvm_unreachable("switch has default clause!"); 9218 } 9219 9220 bool ScalarEvolution::isLoopInvariantPredicate( 9221 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9222 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9223 const SCEV *&InvariantRHS) { 9224 9225 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9226 if (!isLoopInvariant(RHS, L)) { 9227 if (!isLoopInvariant(LHS, L)) 9228 return false; 9229 9230 std::swap(LHS, RHS); 9231 Pred = ICmpInst::getSwappedPredicate(Pred); 9232 } 9233 9234 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9235 if (!ArLHS || ArLHS->getLoop() != L) 9236 return false; 9237 9238 bool Increasing; 9239 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9240 return false; 9241 9242 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9243 // true as the loop iterates, and the backedge is control dependent on 9244 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9245 // 9246 // * if the predicate was false in the first iteration then the predicate 9247 // is never evaluated again, since the loop exits without taking the 9248 // backedge. 9249 // * if the predicate was true in the first iteration then it will 9250 // continue to be true for all future iterations since it is 9251 // monotonically increasing. 9252 // 9253 // For both the above possibilities, we can replace the loop varying 9254 // predicate with its value on the first iteration of the loop (which is 9255 // loop invariant). 9256 // 9257 // A similar reasoning applies for a monotonically decreasing predicate, by 9258 // replacing true with false and false with true in the above two bullets. 9259 9260 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9261 9262 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9263 return false; 9264 9265 InvariantPred = Pred; 9266 InvariantLHS = ArLHS->getStart(); 9267 InvariantRHS = RHS; 9268 return true; 9269 } 9270 9271 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9272 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9273 if (HasSameValue(LHS, RHS)) 9274 return ICmpInst::isTrueWhenEqual(Pred); 9275 9276 // This code is split out from isKnownPredicate because it is called from 9277 // within isLoopEntryGuardedByCond. 9278 9279 auto CheckRanges = 9280 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9281 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9282 .contains(RangeLHS); 9283 }; 9284 9285 // The check at the top of the function catches the case where the values are 9286 // known to be equal. 9287 if (Pred == CmpInst::ICMP_EQ) 9288 return false; 9289 9290 if (Pred == CmpInst::ICMP_NE) 9291 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9292 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9293 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9294 9295 if (CmpInst::isSigned(Pred)) 9296 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9297 9298 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9299 } 9300 9301 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9302 const SCEV *LHS, 9303 const SCEV *RHS) { 9304 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9305 // Return Y via OutY. 9306 auto MatchBinaryAddToConst = 9307 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9308 SCEV::NoWrapFlags ExpectedFlags) { 9309 const SCEV *NonConstOp, *ConstOp; 9310 SCEV::NoWrapFlags FlagsPresent; 9311 9312 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9313 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9314 return false; 9315 9316 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9317 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9318 }; 9319 9320 APInt C; 9321 9322 switch (Pred) { 9323 default: 9324 break; 9325 9326 case ICmpInst::ICMP_SGE: 9327 std::swap(LHS, RHS); 9328 LLVM_FALLTHROUGH; 9329 case ICmpInst::ICMP_SLE: 9330 // X s<= (X + C)<nsw> if C >= 0 9331 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9332 return true; 9333 9334 // (X + C)<nsw> s<= X if C <= 0 9335 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9336 !C.isStrictlyPositive()) 9337 return true; 9338 break; 9339 9340 case ICmpInst::ICMP_SGT: 9341 std::swap(LHS, RHS); 9342 LLVM_FALLTHROUGH; 9343 case ICmpInst::ICMP_SLT: 9344 // X s< (X + C)<nsw> if C > 0 9345 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9346 C.isStrictlyPositive()) 9347 return true; 9348 9349 // (X + C)<nsw> s< X if C < 0 9350 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9351 return true; 9352 break; 9353 9354 case ICmpInst::ICMP_UGE: 9355 std::swap(LHS, RHS); 9356 LLVM_FALLTHROUGH; 9357 case ICmpInst::ICMP_ULE: 9358 // X u<= (X + C)<nuw> for any C 9359 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9360 return true; 9361 break; 9362 9363 case ICmpInst::ICMP_UGT: 9364 std::swap(LHS, RHS); 9365 LLVM_FALLTHROUGH; 9366 case ICmpInst::ICMP_ULT: 9367 // X u< (X + C)<nuw> if C != 0 9368 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9369 return true; 9370 break; 9371 } 9372 9373 return false; 9374 } 9375 9376 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9377 const SCEV *LHS, 9378 const SCEV *RHS) { 9379 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9380 return false; 9381 9382 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9383 // the stack can result in exponential time complexity. 9384 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9385 9386 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9387 // 9388 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9389 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9390 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9391 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9392 // use isKnownPredicate later if needed. 9393 return isKnownNonNegative(RHS) && 9394 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9395 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9396 } 9397 9398 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9399 ICmpInst::Predicate Pred, 9400 const SCEV *LHS, const SCEV *RHS) { 9401 // No need to even try if we know the module has no guards. 9402 if (!HasGuards) 9403 return false; 9404 9405 return any_of(*BB, [&](const Instruction &I) { 9406 using namespace llvm::PatternMatch; 9407 9408 Value *Condition; 9409 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9410 m_Value(Condition))) && 9411 isImpliedCond(Pred, LHS, RHS, Condition, false); 9412 }); 9413 } 9414 9415 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9416 /// protected by a conditional between LHS and RHS. This is used to 9417 /// to eliminate casts. 9418 bool 9419 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9420 ICmpInst::Predicate Pred, 9421 const SCEV *LHS, const SCEV *RHS) { 9422 // Interpret a null as meaning no loop, where there is obviously no guard 9423 // (interprocedural conditions notwithstanding). 9424 if (!L) return true; 9425 9426 if (VerifyIR) 9427 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9428 "This cannot be done on broken IR!"); 9429 9430 9431 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9432 return true; 9433 9434 BasicBlock *Latch = L->getLoopLatch(); 9435 if (!Latch) 9436 return false; 9437 9438 BranchInst *LoopContinuePredicate = 9439 dyn_cast<BranchInst>(Latch->getTerminator()); 9440 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9441 isImpliedCond(Pred, LHS, RHS, 9442 LoopContinuePredicate->getCondition(), 9443 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9444 return true; 9445 9446 // We don't want more than one activation of the following loops on the stack 9447 // -- that can lead to O(n!) time complexity. 9448 if (WalkingBEDominatingConds) 9449 return false; 9450 9451 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9452 9453 // See if we can exploit a trip count to prove the predicate. 9454 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9455 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9456 if (LatchBECount != getCouldNotCompute()) { 9457 // We know that Latch branches back to the loop header exactly 9458 // LatchBECount times. This means the backdege condition at Latch is 9459 // equivalent to "{0,+,1} u< LatchBECount". 9460 Type *Ty = LatchBECount->getType(); 9461 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9462 const SCEV *LoopCounter = 9463 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9464 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9465 LatchBECount)) 9466 return true; 9467 } 9468 9469 // Check conditions due to any @llvm.assume intrinsics. 9470 for (auto &AssumeVH : AC.assumptions()) { 9471 if (!AssumeVH) 9472 continue; 9473 auto *CI = cast<CallInst>(AssumeVH); 9474 if (!DT.dominates(CI, Latch->getTerminator())) 9475 continue; 9476 9477 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9478 return true; 9479 } 9480 9481 // If the loop is not reachable from the entry block, we risk running into an 9482 // infinite loop as we walk up into the dom tree. These loops do not matter 9483 // anyway, so we just return a conservative answer when we see them. 9484 if (!DT.isReachableFromEntry(L->getHeader())) 9485 return false; 9486 9487 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9488 return true; 9489 9490 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9491 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9492 assert(DTN && "should reach the loop header before reaching the root!"); 9493 9494 BasicBlock *BB = DTN->getBlock(); 9495 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9496 return true; 9497 9498 BasicBlock *PBB = BB->getSinglePredecessor(); 9499 if (!PBB) 9500 continue; 9501 9502 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9503 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9504 continue; 9505 9506 Value *Condition = ContinuePredicate->getCondition(); 9507 9508 // If we have an edge `E` within the loop body that dominates the only 9509 // latch, the condition guarding `E` also guards the backedge. This 9510 // reasoning works only for loops with a single latch. 9511 9512 BasicBlockEdge DominatingEdge(PBB, BB); 9513 if (DominatingEdge.isSingleEdge()) { 9514 // We're constructively (and conservatively) enumerating edges within the 9515 // loop body that dominate the latch. The dominator tree better agree 9516 // with us on this: 9517 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9518 9519 if (isImpliedCond(Pred, LHS, RHS, Condition, 9520 BB != ContinuePredicate->getSuccessor(0))) 9521 return true; 9522 } 9523 } 9524 9525 return false; 9526 } 9527 9528 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9529 ICmpInst::Predicate Pred, 9530 const SCEV *LHS, 9531 const SCEV *RHS) { 9532 if (VerifyIR) 9533 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9534 "This cannot be done on broken IR!"); 9535 9536 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9537 return true; 9538 9539 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9540 // the facts (a >= b && a != b) separately. A typical situation is when the 9541 // non-strict comparison is known from ranges and non-equality is known from 9542 // dominating predicates. If we are proving strict comparison, we always try 9543 // to prove non-equality and non-strict comparison separately. 9544 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9545 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9546 bool ProvedNonStrictComparison = false; 9547 bool ProvedNonEquality = false; 9548 9549 if (ProvingStrictComparison) { 9550 ProvedNonStrictComparison = 9551 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9552 ProvedNonEquality = 9553 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9554 if (ProvedNonStrictComparison && ProvedNonEquality) 9555 return true; 9556 } 9557 9558 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9559 auto ProveViaGuard = [&](const BasicBlock *Block) { 9560 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9561 return true; 9562 if (ProvingStrictComparison) { 9563 if (!ProvedNonStrictComparison) 9564 ProvedNonStrictComparison = 9565 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9566 if (!ProvedNonEquality) 9567 ProvedNonEquality = 9568 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9569 if (ProvedNonStrictComparison && ProvedNonEquality) 9570 return true; 9571 } 9572 return false; 9573 }; 9574 9575 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9576 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9577 const Instruction *Context = &BB->front(); 9578 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9579 return true; 9580 if (ProvingStrictComparison) { 9581 if (!ProvedNonStrictComparison) 9582 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 9583 Condition, Inverse, Context); 9584 if (!ProvedNonEquality) 9585 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 9586 Condition, Inverse, Context); 9587 if (ProvedNonStrictComparison && ProvedNonEquality) 9588 return true; 9589 } 9590 return false; 9591 }; 9592 9593 // Starting at the block's predecessor, climb up the predecessor chain, as long 9594 // as there are predecessors that can be found that have unique successors 9595 // leading to the original block. 9596 const Loop *ContainingLoop = LI.getLoopFor(BB); 9597 const BasicBlock *PredBB; 9598 if (ContainingLoop && ContainingLoop->getHeader() == BB) 9599 PredBB = ContainingLoop->getLoopPredecessor(); 9600 else 9601 PredBB = BB->getSinglePredecessor(); 9602 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 9603 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9604 if (ProveViaGuard(Pair.first)) 9605 return true; 9606 9607 const BranchInst *LoopEntryPredicate = 9608 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9609 if (!LoopEntryPredicate || 9610 LoopEntryPredicate->isUnconditional()) 9611 continue; 9612 9613 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9614 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9615 return true; 9616 } 9617 9618 // Check conditions due to any @llvm.assume intrinsics. 9619 for (auto &AssumeVH : AC.assumptions()) { 9620 if (!AssumeVH) 9621 continue; 9622 auto *CI = cast<CallInst>(AssumeVH); 9623 if (!DT.dominates(CI, BB)) 9624 continue; 9625 9626 if (ProveViaCond(CI->getArgOperand(0), false)) 9627 return true; 9628 } 9629 9630 return false; 9631 } 9632 9633 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9634 ICmpInst::Predicate Pred, 9635 const SCEV *LHS, 9636 const SCEV *RHS) { 9637 // Interpret a null as meaning no loop, where there is obviously no guard 9638 // (interprocedural conditions notwithstanding). 9639 if (!L) 9640 return false; 9641 9642 // Both LHS and RHS must be available at loop entry. 9643 assert(isAvailableAtLoopEntry(LHS, L) && 9644 "LHS is not available at Loop Entry"); 9645 assert(isAvailableAtLoopEntry(RHS, L) && 9646 "RHS is not available at Loop Entry"); 9647 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 9648 } 9649 9650 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9651 const SCEV *RHS, 9652 const Value *FoundCondValue, bool Inverse, 9653 const Instruction *Context) { 9654 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9655 return false; 9656 9657 auto ClearOnExit = 9658 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9659 9660 // Recursively handle And and Or conditions. 9661 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9662 if (BO->getOpcode() == Instruction::And) { 9663 if (!Inverse) 9664 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9665 Context) || 9666 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9667 Context); 9668 } else if (BO->getOpcode() == Instruction::Or) { 9669 if (Inverse) 9670 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9671 Context) || 9672 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9673 Context); 9674 } 9675 } 9676 9677 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9678 if (!ICI) return false; 9679 9680 // Now that we found a conditional branch that dominates the loop or controls 9681 // the loop latch. Check to see if it is the comparison we are looking for. 9682 ICmpInst::Predicate FoundPred; 9683 if (Inverse) 9684 FoundPred = ICI->getInversePredicate(); 9685 else 9686 FoundPred = ICI->getPredicate(); 9687 9688 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9689 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9690 9691 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 9692 } 9693 9694 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9695 const SCEV *RHS, 9696 ICmpInst::Predicate FoundPred, 9697 const SCEV *FoundLHS, const SCEV *FoundRHS, 9698 const Instruction *Context) { 9699 // Balance the types. 9700 if (getTypeSizeInBits(LHS->getType()) < 9701 getTypeSizeInBits(FoundLHS->getType())) { 9702 if (CmpInst::isSigned(Pred)) { 9703 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9704 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9705 } else { 9706 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9707 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9708 } 9709 } else if (getTypeSizeInBits(LHS->getType()) > 9710 getTypeSizeInBits(FoundLHS->getType())) { 9711 if (CmpInst::isSigned(FoundPred)) { 9712 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9713 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9714 } else { 9715 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9716 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9717 } 9718 } 9719 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 9720 FoundRHS, Context); 9721 } 9722 9723 bool ScalarEvolution::isImpliedCondBalancedTypes( 9724 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9725 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 9726 const Instruction *Context) { 9727 assert(getTypeSizeInBits(LHS->getType()) == 9728 getTypeSizeInBits(FoundLHS->getType()) && 9729 "Types should be balanced!"); 9730 // Canonicalize the query to match the way instcombine will have 9731 // canonicalized the comparison. 9732 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9733 if (LHS == RHS) 9734 return CmpInst::isTrueWhenEqual(Pred); 9735 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9736 if (FoundLHS == FoundRHS) 9737 return CmpInst::isFalseWhenEqual(FoundPred); 9738 9739 // Check to see if we can make the LHS or RHS match. 9740 if (LHS == FoundRHS || RHS == FoundLHS) { 9741 if (isa<SCEVConstant>(RHS)) { 9742 std::swap(FoundLHS, FoundRHS); 9743 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9744 } else { 9745 std::swap(LHS, RHS); 9746 Pred = ICmpInst::getSwappedPredicate(Pred); 9747 } 9748 } 9749 9750 // Check whether the found predicate is the same as the desired predicate. 9751 if (FoundPred == Pred) 9752 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9753 9754 // Check whether swapping the found predicate makes it the same as the 9755 // desired predicate. 9756 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9757 if (isa<SCEVConstant>(RHS)) 9758 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 9759 else 9760 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 9761 LHS, FoundLHS, FoundRHS, Context); 9762 } 9763 9764 // Unsigned comparison is the same as signed comparison when both the operands 9765 // are non-negative. 9766 if (CmpInst::isUnsigned(FoundPred) && 9767 CmpInst::getSignedPredicate(FoundPred) == Pred && 9768 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9769 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9770 9771 // Check if we can make progress by sharpening ranges. 9772 if (FoundPred == ICmpInst::ICMP_NE && 9773 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9774 9775 const SCEVConstant *C = nullptr; 9776 const SCEV *V = nullptr; 9777 9778 if (isa<SCEVConstant>(FoundLHS)) { 9779 C = cast<SCEVConstant>(FoundLHS); 9780 V = FoundRHS; 9781 } else { 9782 C = cast<SCEVConstant>(FoundRHS); 9783 V = FoundLHS; 9784 } 9785 9786 // The guarding predicate tells us that C != V. If the known range 9787 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9788 // range we consider has to correspond to same signedness as the 9789 // predicate we're interested in folding. 9790 9791 APInt Min = ICmpInst::isSigned(Pred) ? 9792 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9793 9794 if (Min == C->getAPInt()) { 9795 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9796 // This is true even if (Min + 1) wraps around -- in case of 9797 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9798 9799 APInt SharperMin = Min + 1; 9800 9801 switch (Pred) { 9802 case ICmpInst::ICMP_SGE: 9803 case ICmpInst::ICMP_UGE: 9804 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9805 // RHS, we're done. 9806 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 9807 Context)) 9808 return true; 9809 LLVM_FALLTHROUGH; 9810 9811 case ICmpInst::ICMP_SGT: 9812 case ICmpInst::ICMP_UGT: 9813 // We know from the range information that (V `Pred` Min || 9814 // V == Min). We know from the guarding condition that !(V 9815 // == Min). This gives us 9816 // 9817 // V `Pred` Min || V == Min && !(V == Min) 9818 // => V `Pred` Min 9819 // 9820 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9821 9822 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 9823 Context)) 9824 return true; 9825 break; 9826 9827 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 9828 case ICmpInst::ICMP_SLE: 9829 case ICmpInst::ICMP_ULE: 9830 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9831 LHS, V, getConstant(SharperMin), Context)) 9832 return true; 9833 LLVM_FALLTHROUGH; 9834 9835 case ICmpInst::ICMP_SLT: 9836 case ICmpInst::ICMP_ULT: 9837 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9838 LHS, V, getConstant(Min), Context)) 9839 return true; 9840 break; 9841 9842 default: 9843 // No change 9844 break; 9845 } 9846 } 9847 } 9848 9849 // Check whether the actual condition is beyond sufficient. 9850 if (FoundPred == ICmpInst::ICMP_EQ) 9851 if (ICmpInst::isTrueWhenEqual(Pred)) 9852 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 9853 return true; 9854 if (Pred == ICmpInst::ICMP_NE) 9855 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9856 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 9857 Context)) 9858 return true; 9859 9860 // Otherwise assume the worst. 9861 return false; 9862 } 9863 9864 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9865 const SCEV *&L, const SCEV *&R, 9866 SCEV::NoWrapFlags &Flags) { 9867 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9868 if (!AE || AE->getNumOperands() != 2) 9869 return false; 9870 9871 L = AE->getOperand(0); 9872 R = AE->getOperand(1); 9873 Flags = AE->getNoWrapFlags(); 9874 return true; 9875 } 9876 9877 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9878 const SCEV *Less) { 9879 // We avoid subtracting expressions here because this function is usually 9880 // fairly deep in the call stack (i.e. is called many times). 9881 9882 // X - X = 0. 9883 if (More == Less) 9884 return APInt(getTypeSizeInBits(More->getType()), 0); 9885 9886 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9887 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9888 const auto *MAR = cast<SCEVAddRecExpr>(More); 9889 9890 if (LAR->getLoop() != MAR->getLoop()) 9891 return None; 9892 9893 // We look at affine expressions only; not for correctness but to keep 9894 // getStepRecurrence cheap. 9895 if (!LAR->isAffine() || !MAR->isAffine()) 9896 return None; 9897 9898 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9899 return None; 9900 9901 Less = LAR->getStart(); 9902 More = MAR->getStart(); 9903 9904 // fall through 9905 } 9906 9907 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9908 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9909 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9910 return M - L; 9911 } 9912 9913 SCEV::NoWrapFlags Flags; 9914 const SCEV *LLess = nullptr, *RLess = nullptr; 9915 const SCEV *LMore = nullptr, *RMore = nullptr; 9916 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9917 // Compare (X + C1) vs X. 9918 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9919 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9920 if (RLess == More) 9921 return -(C1->getAPInt()); 9922 9923 // Compare X vs (X + C2). 9924 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9925 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9926 if (RMore == Less) 9927 return C2->getAPInt(); 9928 9929 // Compare (X + C1) vs (X + C2). 9930 if (C1 && C2 && RLess == RMore) 9931 return C2->getAPInt() - C1->getAPInt(); 9932 9933 return None; 9934 } 9935 9936 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 9937 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9938 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 9939 // Try to recognize the following pattern: 9940 // 9941 // FoundRHS = ... 9942 // ... 9943 // loop: 9944 // FoundLHS = {Start,+,W} 9945 // context_bb: // Basic block from the same loop 9946 // known(Pred, FoundLHS, FoundRHS) 9947 // 9948 // If some predicate is known in the context of a loop, it is also known on 9949 // each iteration of this loop, including the first iteration. Therefore, in 9950 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 9951 // prove the original pred using this fact. 9952 if (!Context) 9953 return false; 9954 const BasicBlock *ContextBB = Context->getParent(); 9955 // Make sure AR varies in the context block. 9956 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 9957 const Loop *L = AR->getLoop(); 9958 // Make sure that context belongs to the loop and executes on 1st iteration 9959 // (if it ever executes at all). 9960 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 9961 return false; 9962 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 9963 return false; 9964 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 9965 } 9966 9967 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 9968 const Loop *L = AR->getLoop(); 9969 // Make sure that context belongs to the loop and executes on 1st iteration 9970 // (if it ever executes at all). 9971 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 9972 return false; 9973 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 9974 return false; 9975 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 9976 } 9977 9978 return false; 9979 } 9980 9981 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9982 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9983 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9984 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9985 return false; 9986 9987 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9988 if (!AddRecLHS) 9989 return false; 9990 9991 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9992 if (!AddRecFoundLHS) 9993 return false; 9994 9995 // We'd like to let SCEV reason about control dependencies, so we constrain 9996 // both the inequalities to be about add recurrences on the same loop. This 9997 // way we can use isLoopEntryGuardedByCond later. 9998 9999 const Loop *L = AddRecFoundLHS->getLoop(); 10000 if (L != AddRecLHS->getLoop()) 10001 return false; 10002 10003 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10004 // 10005 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10006 // ... (2) 10007 // 10008 // Informal proof for (2), assuming (1) [*]: 10009 // 10010 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10011 // 10012 // Then 10013 // 10014 // FoundLHS s< FoundRHS s< INT_MIN - C 10015 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10016 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10017 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10018 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10019 // <=> FoundLHS + C s< FoundRHS + C 10020 // 10021 // [*]: (1) can be proved by ruling out overflow. 10022 // 10023 // [**]: This can be proved by analyzing all the four possibilities: 10024 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10025 // (A s>= 0, B s>= 0). 10026 // 10027 // Note: 10028 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10029 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10030 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10031 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10032 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10033 // C)". 10034 10035 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10036 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10037 if (!LDiff || !RDiff || *LDiff != *RDiff) 10038 return false; 10039 10040 if (LDiff->isMinValue()) 10041 return true; 10042 10043 APInt FoundRHSLimit; 10044 10045 if (Pred == CmpInst::ICMP_ULT) { 10046 FoundRHSLimit = -(*RDiff); 10047 } else { 10048 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10049 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10050 } 10051 10052 // Try to prove (1) or (2), as needed. 10053 return isAvailableAtLoopEntry(FoundRHS, L) && 10054 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10055 getConstant(FoundRHSLimit)); 10056 } 10057 10058 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10059 const SCEV *LHS, const SCEV *RHS, 10060 const SCEV *FoundLHS, 10061 const SCEV *FoundRHS, unsigned Depth) { 10062 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10063 10064 auto ClearOnExit = make_scope_exit([&]() { 10065 if (LPhi) { 10066 bool Erased = PendingMerges.erase(LPhi); 10067 assert(Erased && "Failed to erase LPhi!"); 10068 (void)Erased; 10069 } 10070 if (RPhi) { 10071 bool Erased = PendingMerges.erase(RPhi); 10072 assert(Erased && "Failed to erase RPhi!"); 10073 (void)Erased; 10074 } 10075 }); 10076 10077 // Find respective Phis and check that they are not being pending. 10078 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10079 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10080 if (!PendingMerges.insert(Phi).second) 10081 return false; 10082 LPhi = Phi; 10083 } 10084 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10085 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10086 // If we detect a loop of Phi nodes being processed by this method, for 10087 // example: 10088 // 10089 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10090 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10091 // 10092 // we don't want to deal with a case that complex, so return conservative 10093 // answer false. 10094 if (!PendingMerges.insert(Phi).second) 10095 return false; 10096 RPhi = Phi; 10097 } 10098 10099 // If none of LHS, RHS is a Phi, nothing to do here. 10100 if (!LPhi && !RPhi) 10101 return false; 10102 10103 // If there is a SCEVUnknown Phi we are interested in, make it left. 10104 if (!LPhi) { 10105 std::swap(LHS, RHS); 10106 std::swap(FoundLHS, FoundRHS); 10107 std::swap(LPhi, RPhi); 10108 Pred = ICmpInst::getSwappedPredicate(Pred); 10109 } 10110 10111 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10112 const BasicBlock *LBB = LPhi->getParent(); 10113 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10114 10115 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10116 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10117 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10118 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10119 }; 10120 10121 if (RPhi && RPhi->getParent() == LBB) { 10122 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10123 // If we compare two Phis from the same block, and for each entry block 10124 // the predicate is true for incoming values from this block, then the 10125 // predicate is also true for the Phis. 10126 for (const BasicBlock *IncBB : predecessors(LBB)) { 10127 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10128 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10129 if (!ProvedEasily(L, R)) 10130 return false; 10131 } 10132 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10133 // Case two: RHS is also a Phi from the same basic block, and it is an 10134 // AddRec. It means that there is a loop which has both AddRec and Unknown 10135 // PHIs, for it we can compare incoming values of AddRec from above the loop 10136 // and latch with their respective incoming values of LPhi. 10137 // TODO: Generalize to handle loops with many inputs in a header. 10138 if (LPhi->getNumIncomingValues() != 2) return false; 10139 10140 auto *RLoop = RAR->getLoop(); 10141 auto *Predecessor = RLoop->getLoopPredecessor(); 10142 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10143 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10144 if (!ProvedEasily(L1, RAR->getStart())) 10145 return false; 10146 auto *Latch = RLoop->getLoopLatch(); 10147 assert(Latch && "Loop with AddRec with no latch?"); 10148 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10149 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10150 return false; 10151 } else { 10152 // In all other cases go over inputs of LHS and compare each of them to RHS, 10153 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10154 // At this point RHS is either a non-Phi, or it is a Phi from some block 10155 // different from LBB. 10156 for (const BasicBlock *IncBB : predecessors(LBB)) { 10157 // Check that RHS is available in this block. 10158 if (!dominates(RHS, IncBB)) 10159 return false; 10160 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10161 if (!ProvedEasily(L, RHS)) 10162 return false; 10163 } 10164 } 10165 return true; 10166 } 10167 10168 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10169 const SCEV *LHS, const SCEV *RHS, 10170 const SCEV *FoundLHS, 10171 const SCEV *FoundRHS, 10172 const Instruction *Context) { 10173 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10174 return true; 10175 10176 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10177 return true; 10178 10179 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10180 Context)) 10181 return true; 10182 10183 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10184 FoundLHS, FoundRHS) || 10185 // ~x < ~y --> x > y 10186 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10187 getNotSCEV(FoundRHS), 10188 getNotSCEV(FoundLHS)); 10189 } 10190 10191 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10192 template <typename MinMaxExprType> 10193 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10194 const SCEV *Candidate) { 10195 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10196 if (!MinMaxExpr) 10197 return false; 10198 10199 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10200 } 10201 10202 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10203 ICmpInst::Predicate Pred, 10204 const SCEV *LHS, const SCEV *RHS) { 10205 // If both sides are affine addrecs for the same loop, with equal 10206 // steps, and we know the recurrences don't wrap, then we only 10207 // need to check the predicate on the starting values. 10208 10209 if (!ICmpInst::isRelational(Pred)) 10210 return false; 10211 10212 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10213 if (!LAR) 10214 return false; 10215 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10216 if (!RAR) 10217 return false; 10218 if (LAR->getLoop() != RAR->getLoop()) 10219 return false; 10220 if (!LAR->isAffine() || !RAR->isAffine()) 10221 return false; 10222 10223 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10224 return false; 10225 10226 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10227 SCEV::FlagNSW : SCEV::FlagNUW; 10228 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10229 return false; 10230 10231 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10232 } 10233 10234 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10235 /// expression? 10236 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10237 ICmpInst::Predicate Pred, 10238 const SCEV *LHS, const SCEV *RHS) { 10239 switch (Pred) { 10240 default: 10241 return false; 10242 10243 case ICmpInst::ICMP_SGE: 10244 std::swap(LHS, RHS); 10245 LLVM_FALLTHROUGH; 10246 case ICmpInst::ICMP_SLE: 10247 return 10248 // min(A, ...) <= A 10249 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10250 // A <= max(A, ...) 10251 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10252 10253 case ICmpInst::ICMP_UGE: 10254 std::swap(LHS, RHS); 10255 LLVM_FALLTHROUGH; 10256 case ICmpInst::ICMP_ULE: 10257 return 10258 // min(A, ...) <= A 10259 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10260 // A <= max(A, ...) 10261 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10262 } 10263 10264 llvm_unreachable("covered switch fell through?!"); 10265 } 10266 10267 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10268 const SCEV *LHS, const SCEV *RHS, 10269 const SCEV *FoundLHS, 10270 const SCEV *FoundRHS, 10271 unsigned Depth) { 10272 assert(getTypeSizeInBits(LHS->getType()) == 10273 getTypeSizeInBits(RHS->getType()) && 10274 "LHS and RHS have different sizes?"); 10275 assert(getTypeSizeInBits(FoundLHS->getType()) == 10276 getTypeSizeInBits(FoundRHS->getType()) && 10277 "FoundLHS and FoundRHS have different sizes?"); 10278 // We want to avoid hurting the compile time with analysis of too big trees. 10279 if (Depth > MaxSCEVOperationsImplicationDepth) 10280 return false; 10281 10282 // We only want to work with GT comparison so far. 10283 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10284 Pred = CmpInst::getSwappedPredicate(Pred); 10285 std::swap(LHS, RHS); 10286 std::swap(FoundLHS, FoundRHS); 10287 } 10288 10289 // For unsigned, try to reduce it to corresponding signed comparison. 10290 if (Pred == ICmpInst::ICMP_UGT) 10291 // We can replace unsigned predicate with its signed counterpart if all 10292 // involved values are non-negative. 10293 // TODO: We could have better support for unsigned. 10294 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10295 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10296 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10297 // use this fact to prove that LHS and RHS are non-negative. 10298 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10299 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10300 FoundRHS) && 10301 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10302 FoundRHS)) 10303 Pred = ICmpInst::ICMP_SGT; 10304 } 10305 10306 if (Pred != ICmpInst::ICMP_SGT) 10307 return false; 10308 10309 auto GetOpFromSExt = [&](const SCEV *S) { 10310 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10311 return Ext->getOperand(); 10312 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10313 // the constant in some cases. 10314 return S; 10315 }; 10316 10317 // Acquire values from extensions. 10318 auto *OrigLHS = LHS; 10319 auto *OrigFoundLHS = FoundLHS; 10320 LHS = GetOpFromSExt(LHS); 10321 FoundLHS = GetOpFromSExt(FoundLHS); 10322 10323 // Is the SGT predicate can be proved trivially or using the found context. 10324 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10325 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10326 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10327 FoundRHS, Depth + 1); 10328 }; 10329 10330 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10331 // We want to avoid creation of any new non-constant SCEV. Since we are 10332 // going to compare the operands to RHS, we should be certain that we don't 10333 // need any size extensions for this. So let's decline all cases when the 10334 // sizes of types of LHS and RHS do not match. 10335 // TODO: Maybe try to get RHS from sext to catch more cases? 10336 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10337 return false; 10338 10339 // Should not overflow. 10340 if (!LHSAddExpr->hasNoSignedWrap()) 10341 return false; 10342 10343 auto *LL = LHSAddExpr->getOperand(0); 10344 auto *LR = LHSAddExpr->getOperand(1); 10345 auto *MinusOne = getMinusOne(RHS->getType()); 10346 10347 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10348 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10349 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10350 }; 10351 // Try to prove the following rule: 10352 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10353 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10354 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10355 return true; 10356 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10357 Value *LL, *LR; 10358 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10359 10360 using namespace llvm::PatternMatch; 10361 10362 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10363 // Rules for division. 10364 // We are going to perform some comparisons with Denominator and its 10365 // derivative expressions. In general case, creating a SCEV for it may 10366 // lead to a complex analysis of the entire graph, and in particular it 10367 // can request trip count recalculation for the same loop. This would 10368 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10369 // this, we only want to create SCEVs that are constants in this section. 10370 // So we bail if Denominator is not a constant. 10371 if (!isa<ConstantInt>(LR)) 10372 return false; 10373 10374 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10375 10376 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10377 // then a SCEV for the numerator already exists and matches with FoundLHS. 10378 auto *Numerator = getExistingSCEV(LL); 10379 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10380 return false; 10381 10382 // Make sure that the numerator matches with FoundLHS and the denominator 10383 // is positive. 10384 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10385 return false; 10386 10387 auto *DTy = Denominator->getType(); 10388 auto *FRHSTy = FoundRHS->getType(); 10389 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10390 // One of types is a pointer and another one is not. We cannot extend 10391 // them properly to a wider type, so let us just reject this case. 10392 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10393 // to avoid this check. 10394 return false; 10395 10396 // Given that: 10397 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10398 auto *WTy = getWiderType(DTy, FRHSTy); 10399 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10400 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10401 10402 // Try to prove the following rule: 10403 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10404 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10405 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10406 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10407 if (isKnownNonPositive(RHS) && 10408 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10409 return true; 10410 10411 // Try to prove the following rule: 10412 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10413 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10414 // If we divide it by Denominator > 2, then: 10415 // 1. If FoundLHS is negative, then the result is 0. 10416 // 2. If FoundLHS is non-negative, then the result is non-negative. 10417 // Anyways, the result is non-negative. 10418 auto *MinusOne = getMinusOne(WTy); 10419 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10420 if (isKnownNegative(RHS) && 10421 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10422 return true; 10423 } 10424 } 10425 10426 // If our expression contained SCEVUnknown Phis, and we split it down and now 10427 // need to prove something for them, try to prove the predicate for every 10428 // possible incoming values of those Phis. 10429 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10430 return true; 10431 10432 return false; 10433 } 10434 10435 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10436 const SCEV *LHS, const SCEV *RHS) { 10437 // zext x u<= sext x, sext x s<= zext x 10438 switch (Pred) { 10439 case ICmpInst::ICMP_SGE: 10440 std::swap(LHS, RHS); 10441 LLVM_FALLTHROUGH; 10442 case ICmpInst::ICMP_SLE: { 10443 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10444 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10445 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10446 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10447 return true; 10448 break; 10449 } 10450 case ICmpInst::ICMP_UGE: 10451 std::swap(LHS, RHS); 10452 LLVM_FALLTHROUGH; 10453 case ICmpInst::ICMP_ULE: { 10454 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10455 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10456 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10457 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10458 return true; 10459 break; 10460 } 10461 default: 10462 break; 10463 }; 10464 return false; 10465 } 10466 10467 bool 10468 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10469 const SCEV *LHS, const SCEV *RHS) { 10470 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10471 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10472 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10473 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10474 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10475 } 10476 10477 bool 10478 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10479 const SCEV *LHS, const SCEV *RHS, 10480 const SCEV *FoundLHS, 10481 const SCEV *FoundRHS) { 10482 switch (Pred) { 10483 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10484 case ICmpInst::ICMP_EQ: 10485 case ICmpInst::ICMP_NE: 10486 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10487 return true; 10488 break; 10489 case ICmpInst::ICMP_SLT: 10490 case ICmpInst::ICMP_SLE: 10491 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10492 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10493 return true; 10494 break; 10495 case ICmpInst::ICMP_SGT: 10496 case ICmpInst::ICMP_SGE: 10497 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10498 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10499 return true; 10500 break; 10501 case ICmpInst::ICMP_ULT: 10502 case ICmpInst::ICMP_ULE: 10503 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10504 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10505 return true; 10506 break; 10507 case ICmpInst::ICMP_UGT: 10508 case ICmpInst::ICMP_UGE: 10509 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10510 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10511 return true; 10512 break; 10513 } 10514 10515 // Maybe it can be proved via operations? 10516 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10517 return true; 10518 10519 return false; 10520 } 10521 10522 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10523 const SCEV *LHS, 10524 const SCEV *RHS, 10525 const SCEV *FoundLHS, 10526 const SCEV *FoundRHS) { 10527 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10528 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10529 // reduce the compile time impact of this optimization. 10530 return false; 10531 10532 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10533 if (!Addend) 10534 return false; 10535 10536 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10537 10538 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10539 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10540 ConstantRange FoundLHSRange = 10541 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10542 10543 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10544 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10545 10546 // We can also compute the range of values for `LHS` that satisfy the 10547 // consequent, "`LHS` `Pred` `RHS`": 10548 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10549 ConstantRange SatisfyingLHSRange = 10550 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10551 10552 // The antecedent implies the consequent if every value of `LHS` that 10553 // satisfies the antecedent also satisfies the consequent. 10554 return SatisfyingLHSRange.contains(LHSRange); 10555 } 10556 10557 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10558 bool IsSigned, bool NoWrap) { 10559 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10560 10561 if (NoWrap) return false; 10562 10563 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10564 const SCEV *One = getOne(Stride->getType()); 10565 10566 if (IsSigned) { 10567 APInt MaxRHS = getSignedRangeMax(RHS); 10568 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10569 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10570 10571 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10572 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10573 } 10574 10575 APInt MaxRHS = getUnsignedRangeMax(RHS); 10576 APInt MaxValue = APInt::getMaxValue(BitWidth); 10577 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10578 10579 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10580 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10581 } 10582 10583 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10584 bool IsSigned, bool NoWrap) { 10585 if (NoWrap) return false; 10586 10587 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10588 const SCEV *One = getOne(Stride->getType()); 10589 10590 if (IsSigned) { 10591 APInt MinRHS = getSignedRangeMin(RHS); 10592 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10593 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10594 10595 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10596 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10597 } 10598 10599 APInt MinRHS = getUnsignedRangeMin(RHS); 10600 APInt MinValue = APInt::getMinValue(BitWidth); 10601 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10602 10603 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10604 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10605 } 10606 10607 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10608 bool Equality) { 10609 const SCEV *One = getOne(Step->getType()); 10610 Delta = Equality ? getAddExpr(Delta, Step) 10611 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10612 return getUDivExpr(Delta, Step); 10613 } 10614 10615 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10616 const SCEV *Stride, 10617 const SCEV *End, 10618 unsigned BitWidth, 10619 bool IsSigned) { 10620 10621 assert(!isKnownNonPositive(Stride) && 10622 "Stride is expected strictly positive!"); 10623 // Calculate the maximum backedge count based on the range of values 10624 // permitted by Start, End, and Stride. 10625 const SCEV *MaxBECount; 10626 APInt MinStart = 10627 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10628 10629 APInt StrideForMaxBECount = 10630 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10631 10632 // We already know that the stride is positive, so we paper over conservatism 10633 // in our range computation by forcing StrideForMaxBECount to be at least one. 10634 // In theory this is unnecessary, but we expect MaxBECount to be a 10635 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10636 // is nothing to constant fold it to). 10637 APInt One(BitWidth, 1, IsSigned); 10638 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10639 10640 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10641 : APInt::getMaxValue(BitWidth); 10642 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10643 10644 // Although End can be a MAX expression we estimate MaxEnd considering only 10645 // the case End = RHS of the loop termination condition. This is safe because 10646 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10647 // taken count. 10648 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10649 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10650 10651 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10652 getConstant(StrideForMaxBECount) /* Step */, 10653 false /* Equality */); 10654 10655 return MaxBECount; 10656 } 10657 10658 ScalarEvolution::ExitLimit 10659 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10660 const Loop *L, bool IsSigned, 10661 bool ControlsExit, bool AllowPredicates) { 10662 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10663 10664 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10665 bool PredicatedIV = false; 10666 10667 if (!IV && AllowPredicates) { 10668 // Try to make this an AddRec using runtime tests, in the first X 10669 // iterations of this loop, where X is the SCEV expression found by the 10670 // algorithm below. 10671 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10672 PredicatedIV = true; 10673 } 10674 10675 // Avoid weird loops 10676 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10677 return getCouldNotCompute(); 10678 10679 bool NoWrap = ControlsExit && 10680 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10681 10682 const SCEV *Stride = IV->getStepRecurrence(*this); 10683 10684 bool PositiveStride = isKnownPositive(Stride); 10685 10686 // Avoid negative or zero stride values. 10687 if (!PositiveStride) { 10688 // We can compute the correct backedge taken count for loops with unknown 10689 // strides if we can prove that the loop is not an infinite loop with side 10690 // effects. Here's the loop structure we are trying to handle - 10691 // 10692 // i = start 10693 // do { 10694 // A[i] = i; 10695 // i += s; 10696 // } while (i < end); 10697 // 10698 // The backedge taken count for such loops is evaluated as - 10699 // (max(end, start + stride) - start - 1) /u stride 10700 // 10701 // The additional preconditions that we need to check to prove correctness 10702 // of the above formula is as follows - 10703 // 10704 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10705 // NoWrap flag). 10706 // b) loop is single exit with no side effects. 10707 // 10708 // 10709 // Precondition a) implies that if the stride is negative, this is a single 10710 // trip loop. The backedge taken count formula reduces to zero in this case. 10711 // 10712 // Precondition b) implies that the unknown stride cannot be zero otherwise 10713 // we have UB. 10714 // 10715 // The positive stride case is the same as isKnownPositive(Stride) returning 10716 // true (original behavior of the function). 10717 // 10718 // We want to make sure that the stride is truly unknown as there are edge 10719 // cases where ScalarEvolution propagates no wrap flags to the 10720 // post-increment/decrement IV even though the increment/decrement operation 10721 // itself is wrapping. The computed backedge taken count may be wrong in 10722 // such cases. This is prevented by checking that the stride is not known to 10723 // be either positive or non-positive. For example, no wrap flags are 10724 // propagated to the post-increment IV of this loop with a trip count of 2 - 10725 // 10726 // unsigned char i; 10727 // for(i=127; i<128; i+=129) 10728 // A[i] = i; 10729 // 10730 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10731 !loopHasNoSideEffects(L)) 10732 return getCouldNotCompute(); 10733 } else if (!Stride->isOne() && 10734 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10735 // Avoid proven overflow cases: this will ensure that the backedge taken 10736 // count will not generate any unsigned overflow. Relaxed no-overflow 10737 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10738 // undefined behaviors like the case of C language. 10739 return getCouldNotCompute(); 10740 10741 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10742 : ICmpInst::ICMP_ULT; 10743 const SCEV *Start = IV->getStart(); 10744 const SCEV *End = RHS; 10745 // When the RHS is not invariant, we do not know the end bound of the loop and 10746 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10747 // calculate the MaxBECount, given the start, stride and max value for the end 10748 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10749 // checked above). 10750 if (!isLoopInvariant(RHS, L)) { 10751 const SCEV *MaxBECount = computeMaxBECountForLT( 10752 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10753 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10754 false /*MaxOrZero*/, Predicates); 10755 } 10756 // If the backedge is taken at least once, then it will be taken 10757 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10758 // is the LHS value of the less-than comparison the first time it is evaluated 10759 // and End is the RHS. 10760 const SCEV *BECountIfBackedgeTaken = 10761 computeBECount(getMinusSCEV(End, Start), Stride, false); 10762 // If the loop entry is guarded by the result of the backedge test of the 10763 // first loop iteration, then we know the backedge will be taken at least 10764 // once and so the backedge taken count is as above. If not then we use the 10765 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10766 // as if the backedge is taken at least once max(End,Start) is End and so the 10767 // result is as above, and if not max(End,Start) is Start so we get a backedge 10768 // count of zero. 10769 const SCEV *BECount; 10770 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10771 BECount = BECountIfBackedgeTaken; 10772 else { 10773 // If we know that RHS >= Start in the context of loop, then we know that 10774 // max(RHS, Start) = RHS at this point. 10775 if (isLoopEntryGuardedByCond( 10776 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 10777 End = RHS; 10778 else 10779 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10780 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10781 } 10782 10783 const SCEV *MaxBECount; 10784 bool MaxOrZero = false; 10785 if (isa<SCEVConstant>(BECount)) 10786 MaxBECount = BECount; 10787 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10788 // If we know exactly how many times the backedge will be taken if it's 10789 // taken at least once, then the backedge count will either be that or 10790 // zero. 10791 MaxBECount = BECountIfBackedgeTaken; 10792 MaxOrZero = true; 10793 } else { 10794 MaxBECount = computeMaxBECountForLT( 10795 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10796 } 10797 10798 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10799 !isa<SCEVCouldNotCompute>(BECount)) 10800 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10801 10802 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10803 } 10804 10805 ScalarEvolution::ExitLimit 10806 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10807 const Loop *L, bool IsSigned, 10808 bool ControlsExit, bool AllowPredicates) { 10809 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10810 // We handle only IV > Invariant 10811 if (!isLoopInvariant(RHS, L)) 10812 return getCouldNotCompute(); 10813 10814 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10815 if (!IV && AllowPredicates) 10816 // Try to make this an AddRec using runtime tests, in the first X 10817 // iterations of this loop, where X is the SCEV expression found by the 10818 // algorithm below. 10819 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10820 10821 // Avoid weird loops 10822 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10823 return getCouldNotCompute(); 10824 10825 bool NoWrap = ControlsExit && 10826 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10827 10828 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10829 10830 // Avoid negative or zero stride values 10831 if (!isKnownPositive(Stride)) 10832 return getCouldNotCompute(); 10833 10834 // Avoid proven overflow cases: this will ensure that the backedge taken count 10835 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10836 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10837 // behaviors like the case of C language. 10838 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10839 return getCouldNotCompute(); 10840 10841 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10842 : ICmpInst::ICMP_UGT; 10843 10844 const SCEV *Start = IV->getStart(); 10845 const SCEV *End = RHS; 10846 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 10847 // If we know that Start >= RHS in the context of loop, then we know that 10848 // min(RHS, Start) = RHS at this point. 10849 if (isLoopEntryGuardedByCond( 10850 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 10851 End = RHS; 10852 else 10853 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10854 } 10855 10856 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10857 10858 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10859 : getUnsignedRangeMax(Start); 10860 10861 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10862 : getUnsignedRangeMin(Stride); 10863 10864 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10865 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10866 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10867 10868 // Although End can be a MIN expression we estimate MinEnd considering only 10869 // the case End = RHS. This is safe because in the other case (Start - End) 10870 // is zero, leading to a zero maximum backedge taken count. 10871 APInt MinEnd = 10872 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10873 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10874 10875 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10876 ? BECount 10877 : computeBECount(getConstant(MaxStart - MinEnd), 10878 getConstant(MinStride), false); 10879 10880 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10881 MaxBECount = BECount; 10882 10883 return ExitLimit(BECount, MaxBECount, false, Predicates); 10884 } 10885 10886 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10887 ScalarEvolution &SE) const { 10888 if (Range.isFullSet()) // Infinite loop. 10889 return SE.getCouldNotCompute(); 10890 10891 // If the start is a non-zero constant, shift the range to simplify things. 10892 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10893 if (!SC->getValue()->isZero()) { 10894 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10895 Operands[0] = SE.getZero(SC->getType()); 10896 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10897 getNoWrapFlags(FlagNW)); 10898 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10899 return ShiftedAddRec->getNumIterationsInRange( 10900 Range.subtract(SC->getAPInt()), SE); 10901 // This is strange and shouldn't happen. 10902 return SE.getCouldNotCompute(); 10903 } 10904 10905 // The only time we can solve this is when we have all constant indices. 10906 // Otherwise, we cannot determine the overflow conditions. 10907 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10908 return SE.getCouldNotCompute(); 10909 10910 // Okay at this point we know that all elements of the chrec are constants and 10911 // that the start element is zero. 10912 10913 // First check to see if the range contains zero. If not, the first 10914 // iteration exits. 10915 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10916 if (!Range.contains(APInt(BitWidth, 0))) 10917 return SE.getZero(getType()); 10918 10919 if (isAffine()) { 10920 // If this is an affine expression then we have this situation: 10921 // Solve {0,+,A} in Range === Ax in Range 10922 10923 // We know that zero is in the range. If A is positive then we know that 10924 // the upper value of the range must be the first possible exit value. 10925 // If A is negative then the lower of the range is the last possible loop 10926 // value. Also note that we already checked for a full range. 10927 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10928 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10929 10930 // The exit value should be (End+A)/A. 10931 APInt ExitVal = (End + A).udiv(A); 10932 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10933 10934 // Evaluate at the exit value. If we really did fall out of the valid 10935 // range, then we computed our trip count, otherwise wrap around or other 10936 // things must have happened. 10937 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10938 if (Range.contains(Val->getValue())) 10939 return SE.getCouldNotCompute(); // Something strange happened 10940 10941 // Ensure that the previous value is in the range. This is a sanity check. 10942 assert(Range.contains( 10943 EvaluateConstantChrecAtConstant(this, 10944 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10945 "Linear scev computation is off in a bad way!"); 10946 return SE.getConstant(ExitValue); 10947 } 10948 10949 if (isQuadratic()) { 10950 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10951 return SE.getConstant(S.getValue()); 10952 } 10953 10954 return SE.getCouldNotCompute(); 10955 } 10956 10957 const SCEVAddRecExpr * 10958 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10959 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10960 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10961 // but in this case we cannot guarantee that the value returned will be an 10962 // AddRec because SCEV does not have a fixed point where it stops 10963 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10964 // may happen if we reach arithmetic depth limit while simplifying. So we 10965 // construct the returned value explicitly. 10966 SmallVector<const SCEV *, 3> Ops; 10967 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10968 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10969 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10970 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10971 // We know that the last operand is not a constant zero (otherwise it would 10972 // have been popped out earlier). This guarantees us that if the result has 10973 // the same last operand, then it will also not be popped out, meaning that 10974 // the returned value will be an AddRec. 10975 const SCEV *Last = getOperand(getNumOperands() - 1); 10976 assert(!Last->isZero() && "Recurrency with zero step?"); 10977 Ops.push_back(Last); 10978 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10979 SCEV::FlagAnyWrap)); 10980 } 10981 10982 // Return true when S contains at least an undef value. 10983 static inline bool containsUndefs(const SCEV *S) { 10984 return SCEVExprContains(S, [](const SCEV *S) { 10985 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10986 return isa<UndefValue>(SU->getValue()); 10987 return false; 10988 }); 10989 } 10990 10991 namespace { 10992 10993 // Collect all steps of SCEV expressions. 10994 struct SCEVCollectStrides { 10995 ScalarEvolution &SE; 10996 SmallVectorImpl<const SCEV *> &Strides; 10997 10998 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10999 : SE(SE), Strides(S) {} 11000 11001 bool follow(const SCEV *S) { 11002 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11003 Strides.push_back(AR->getStepRecurrence(SE)); 11004 return true; 11005 } 11006 11007 bool isDone() const { return false; } 11008 }; 11009 11010 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11011 struct SCEVCollectTerms { 11012 SmallVectorImpl<const SCEV *> &Terms; 11013 11014 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11015 11016 bool follow(const SCEV *S) { 11017 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11018 isa<SCEVSignExtendExpr>(S)) { 11019 if (!containsUndefs(S)) 11020 Terms.push_back(S); 11021 11022 // Stop recursion: once we collected a term, do not walk its operands. 11023 return false; 11024 } 11025 11026 // Keep looking. 11027 return true; 11028 } 11029 11030 bool isDone() const { return false; } 11031 }; 11032 11033 // Check if a SCEV contains an AddRecExpr. 11034 struct SCEVHasAddRec { 11035 bool &ContainsAddRec; 11036 11037 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11038 ContainsAddRec = false; 11039 } 11040 11041 bool follow(const SCEV *S) { 11042 if (isa<SCEVAddRecExpr>(S)) { 11043 ContainsAddRec = true; 11044 11045 // Stop recursion: once we collected a term, do not walk its operands. 11046 return false; 11047 } 11048 11049 // Keep looking. 11050 return true; 11051 } 11052 11053 bool isDone() const { return false; } 11054 }; 11055 11056 // Find factors that are multiplied with an expression that (possibly as a 11057 // subexpression) contains an AddRecExpr. In the expression: 11058 // 11059 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11060 // 11061 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11062 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11063 // parameters as they form a product with an induction variable. 11064 // 11065 // This collector expects all array size parameters to be in the same MulExpr. 11066 // It might be necessary to later add support for collecting parameters that are 11067 // spread over different nested MulExpr. 11068 struct SCEVCollectAddRecMultiplies { 11069 SmallVectorImpl<const SCEV *> &Terms; 11070 ScalarEvolution &SE; 11071 11072 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11073 : Terms(T), SE(SE) {} 11074 11075 bool follow(const SCEV *S) { 11076 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11077 bool HasAddRec = false; 11078 SmallVector<const SCEV *, 0> Operands; 11079 for (auto Op : Mul->operands()) { 11080 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11081 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11082 Operands.push_back(Op); 11083 } else if (Unknown) { 11084 HasAddRec = true; 11085 } else { 11086 bool ContainsAddRec = false; 11087 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11088 visitAll(Op, ContiansAddRec); 11089 HasAddRec |= ContainsAddRec; 11090 } 11091 } 11092 if (Operands.size() == 0) 11093 return true; 11094 11095 if (!HasAddRec) 11096 return false; 11097 11098 Terms.push_back(SE.getMulExpr(Operands)); 11099 // Stop recursion: once we collected a term, do not walk its operands. 11100 return false; 11101 } 11102 11103 // Keep looking. 11104 return true; 11105 } 11106 11107 bool isDone() const { return false; } 11108 }; 11109 11110 } // end anonymous namespace 11111 11112 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11113 /// two places: 11114 /// 1) The strides of AddRec expressions. 11115 /// 2) Unknowns that are multiplied with AddRec expressions. 11116 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11117 SmallVectorImpl<const SCEV *> &Terms) { 11118 SmallVector<const SCEV *, 4> Strides; 11119 SCEVCollectStrides StrideCollector(*this, Strides); 11120 visitAll(Expr, StrideCollector); 11121 11122 LLVM_DEBUG({ 11123 dbgs() << "Strides:\n"; 11124 for (const SCEV *S : Strides) 11125 dbgs() << *S << "\n"; 11126 }); 11127 11128 for (const SCEV *S : Strides) { 11129 SCEVCollectTerms TermCollector(Terms); 11130 visitAll(S, TermCollector); 11131 } 11132 11133 LLVM_DEBUG({ 11134 dbgs() << "Terms:\n"; 11135 for (const SCEV *T : Terms) 11136 dbgs() << *T << "\n"; 11137 }); 11138 11139 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11140 visitAll(Expr, MulCollector); 11141 } 11142 11143 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11144 SmallVectorImpl<const SCEV *> &Terms, 11145 SmallVectorImpl<const SCEV *> &Sizes) { 11146 int Last = Terms.size() - 1; 11147 const SCEV *Step = Terms[Last]; 11148 11149 // End of recursion. 11150 if (Last == 0) { 11151 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11152 SmallVector<const SCEV *, 2> Qs; 11153 for (const SCEV *Op : M->operands()) 11154 if (!isa<SCEVConstant>(Op)) 11155 Qs.push_back(Op); 11156 11157 Step = SE.getMulExpr(Qs); 11158 } 11159 11160 Sizes.push_back(Step); 11161 return true; 11162 } 11163 11164 for (const SCEV *&Term : Terms) { 11165 // Normalize the terms before the next call to findArrayDimensionsRec. 11166 const SCEV *Q, *R; 11167 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11168 11169 // Bail out when GCD does not evenly divide one of the terms. 11170 if (!R->isZero()) 11171 return false; 11172 11173 Term = Q; 11174 } 11175 11176 // Remove all SCEVConstants. 11177 Terms.erase( 11178 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11179 Terms.end()); 11180 11181 if (Terms.size() > 0) 11182 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11183 return false; 11184 11185 Sizes.push_back(Step); 11186 return true; 11187 } 11188 11189 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11190 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11191 for (const SCEV *T : Terms) 11192 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11193 return true; 11194 11195 return false; 11196 } 11197 11198 // Return the number of product terms in S. 11199 static inline int numberOfTerms(const SCEV *S) { 11200 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11201 return Expr->getNumOperands(); 11202 return 1; 11203 } 11204 11205 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11206 if (isa<SCEVConstant>(T)) 11207 return nullptr; 11208 11209 if (isa<SCEVUnknown>(T)) 11210 return T; 11211 11212 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11213 SmallVector<const SCEV *, 2> Factors; 11214 for (const SCEV *Op : M->operands()) 11215 if (!isa<SCEVConstant>(Op)) 11216 Factors.push_back(Op); 11217 11218 return SE.getMulExpr(Factors); 11219 } 11220 11221 return T; 11222 } 11223 11224 /// Return the size of an element read or written by Inst. 11225 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11226 Type *Ty; 11227 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11228 Ty = Store->getValueOperand()->getType(); 11229 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11230 Ty = Load->getType(); 11231 else 11232 return nullptr; 11233 11234 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11235 return getSizeOfExpr(ETy, Ty); 11236 } 11237 11238 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11239 SmallVectorImpl<const SCEV *> &Sizes, 11240 const SCEV *ElementSize) { 11241 if (Terms.size() < 1 || !ElementSize) 11242 return; 11243 11244 // Early return when Terms do not contain parameters: we do not delinearize 11245 // non parametric SCEVs. 11246 if (!containsParameters(Terms)) 11247 return; 11248 11249 LLVM_DEBUG({ 11250 dbgs() << "Terms:\n"; 11251 for (const SCEV *T : Terms) 11252 dbgs() << *T << "\n"; 11253 }); 11254 11255 // Remove duplicates. 11256 array_pod_sort(Terms.begin(), Terms.end()); 11257 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11258 11259 // Put larger terms first. 11260 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11261 return numberOfTerms(LHS) > numberOfTerms(RHS); 11262 }); 11263 11264 // Try to divide all terms by the element size. If term is not divisible by 11265 // element size, proceed with the original term. 11266 for (const SCEV *&Term : Terms) { 11267 const SCEV *Q, *R; 11268 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11269 if (!Q->isZero()) 11270 Term = Q; 11271 } 11272 11273 SmallVector<const SCEV *, 4> NewTerms; 11274 11275 // Remove constant factors. 11276 for (const SCEV *T : Terms) 11277 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11278 NewTerms.push_back(NewT); 11279 11280 LLVM_DEBUG({ 11281 dbgs() << "Terms after sorting:\n"; 11282 for (const SCEV *T : NewTerms) 11283 dbgs() << *T << "\n"; 11284 }); 11285 11286 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11287 Sizes.clear(); 11288 return; 11289 } 11290 11291 // The last element to be pushed into Sizes is the size of an element. 11292 Sizes.push_back(ElementSize); 11293 11294 LLVM_DEBUG({ 11295 dbgs() << "Sizes:\n"; 11296 for (const SCEV *S : Sizes) 11297 dbgs() << *S << "\n"; 11298 }); 11299 } 11300 11301 void ScalarEvolution::computeAccessFunctions( 11302 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11303 SmallVectorImpl<const SCEV *> &Sizes) { 11304 // Early exit in case this SCEV is not an affine multivariate function. 11305 if (Sizes.empty()) 11306 return; 11307 11308 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11309 if (!AR->isAffine()) 11310 return; 11311 11312 const SCEV *Res = Expr; 11313 int Last = Sizes.size() - 1; 11314 for (int i = Last; i >= 0; i--) { 11315 const SCEV *Q, *R; 11316 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11317 11318 LLVM_DEBUG({ 11319 dbgs() << "Res: " << *Res << "\n"; 11320 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11321 dbgs() << "Res divided by Sizes[i]:\n"; 11322 dbgs() << "Quotient: " << *Q << "\n"; 11323 dbgs() << "Remainder: " << *R << "\n"; 11324 }); 11325 11326 Res = Q; 11327 11328 // Do not record the last subscript corresponding to the size of elements in 11329 // the array. 11330 if (i == Last) { 11331 11332 // Bail out if the remainder is too complex. 11333 if (isa<SCEVAddRecExpr>(R)) { 11334 Subscripts.clear(); 11335 Sizes.clear(); 11336 return; 11337 } 11338 11339 continue; 11340 } 11341 11342 // Record the access function for the current subscript. 11343 Subscripts.push_back(R); 11344 } 11345 11346 // Also push in last position the remainder of the last division: it will be 11347 // the access function of the innermost dimension. 11348 Subscripts.push_back(Res); 11349 11350 std::reverse(Subscripts.begin(), Subscripts.end()); 11351 11352 LLVM_DEBUG({ 11353 dbgs() << "Subscripts:\n"; 11354 for (const SCEV *S : Subscripts) 11355 dbgs() << *S << "\n"; 11356 }); 11357 } 11358 11359 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11360 /// sizes of an array access. Returns the remainder of the delinearization that 11361 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11362 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11363 /// expressions in the stride and base of a SCEV corresponding to the 11364 /// computation of a GCD (greatest common divisor) of base and stride. When 11365 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11366 /// 11367 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11368 /// 11369 /// void foo(long n, long m, long o, double A[n][m][o]) { 11370 /// 11371 /// for (long i = 0; i < n; i++) 11372 /// for (long j = 0; j < m; j++) 11373 /// for (long k = 0; k < o; k++) 11374 /// A[i][j][k] = 1.0; 11375 /// } 11376 /// 11377 /// the delinearization input is the following AddRec SCEV: 11378 /// 11379 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11380 /// 11381 /// From this SCEV, we are able to say that the base offset of the access is %A 11382 /// because it appears as an offset that does not divide any of the strides in 11383 /// the loops: 11384 /// 11385 /// CHECK: Base offset: %A 11386 /// 11387 /// and then SCEV->delinearize determines the size of some of the dimensions of 11388 /// the array as these are the multiples by which the strides are happening: 11389 /// 11390 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11391 /// 11392 /// Note that the outermost dimension remains of UnknownSize because there are 11393 /// no strides that would help identifying the size of the last dimension: when 11394 /// the array has been statically allocated, one could compute the size of that 11395 /// dimension by dividing the overall size of the array by the size of the known 11396 /// dimensions: %m * %o * 8. 11397 /// 11398 /// Finally delinearize provides the access functions for the array reference 11399 /// that does correspond to A[i][j][k] of the above C testcase: 11400 /// 11401 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11402 /// 11403 /// The testcases are checking the output of a function pass: 11404 /// DelinearizationPass that walks through all loads and stores of a function 11405 /// asking for the SCEV of the memory access with respect to all enclosing 11406 /// loops, calling SCEV->delinearize on that and printing the results. 11407 void ScalarEvolution::delinearize(const SCEV *Expr, 11408 SmallVectorImpl<const SCEV *> &Subscripts, 11409 SmallVectorImpl<const SCEV *> &Sizes, 11410 const SCEV *ElementSize) { 11411 // First step: collect parametric terms. 11412 SmallVector<const SCEV *, 4> Terms; 11413 collectParametricTerms(Expr, Terms); 11414 11415 if (Terms.empty()) 11416 return; 11417 11418 // Second step: find subscript sizes. 11419 findArrayDimensions(Terms, Sizes, ElementSize); 11420 11421 if (Sizes.empty()) 11422 return; 11423 11424 // Third step: compute the access functions for each subscript. 11425 computeAccessFunctions(Expr, Subscripts, Sizes); 11426 11427 if (Subscripts.empty()) 11428 return; 11429 11430 LLVM_DEBUG({ 11431 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11432 dbgs() << "ArrayDecl[UnknownSize]"; 11433 for (const SCEV *S : Sizes) 11434 dbgs() << "[" << *S << "]"; 11435 11436 dbgs() << "\nArrayRef"; 11437 for (const SCEV *S : Subscripts) 11438 dbgs() << "[" << *S << "]"; 11439 dbgs() << "\n"; 11440 }); 11441 } 11442 11443 bool ScalarEvolution::getIndexExpressionsFromGEP( 11444 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11445 SmallVectorImpl<int> &Sizes) { 11446 assert(Subscripts.empty() && Sizes.empty() && 11447 "Expected output lists to be empty on entry to this function."); 11448 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11449 Type *Ty = GEP->getPointerOperandType(); 11450 bool DroppedFirstDim = false; 11451 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11452 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11453 if (i == 1) { 11454 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11455 Ty = PtrTy->getElementType(); 11456 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11457 Ty = ArrayTy->getElementType(); 11458 } else { 11459 Subscripts.clear(); 11460 Sizes.clear(); 11461 return false; 11462 } 11463 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11464 if (Const->getValue()->isZero()) { 11465 DroppedFirstDim = true; 11466 continue; 11467 } 11468 Subscripts.push_back(Expr); 11469 continue; 11470 } 11471 11472 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11473 if (!ArrayTy) { 11474 Subscripts.clear(); 11475 Sizes.clear(); 11476 return false; 11477 } 11478 11479 Subscripts.push_back(Expr); 11480 if (!(DroppedFirstDim && i == 2)) 11481 Sizes.push_back(ArrayTy->getNumElements()); 11482 11483 Ty = ArrayTy->getElementType(); 11484 } 11485 return !Subscripts.empty(); 11486 } 11487 11488 //===----------------------------------------------------------------------===// 11489 // SCEVCallbackVH Class Implementation 11490 //===----------------------------------------------------------------------===// 11491 11492 void ScalarEvolution::SCEVCallbackVH::deleted() { 11493 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11494 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11495 SE->ConstantEvolutionLoopExitValue.erase(PN); 11496 SE->eraseValueFromMap(getValPtr()); 11497 // this now dangles! 11498 } 11499 11500 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11501 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11502 11503 // Forget all the expressions associated with users of the old value, 11504 // so that future queries will recompute the expressions using the new 11505 // value. 11506 Value *Old = getValPtr(); 11507 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11508 SmallPtrSet<User *, 8> Visited; 11509 while (!Worklist.empty()) { 11510 User *U = Worklist.pop_back_val(); 11511 // Deleting the Old value will cause this to dangle. Postpone 11512 // that until everything else is done. 11513 if (U == Old) 11514 continue; 11515 if (!Visited.insert(U).second) 11516 continue; 11517 if (PHINode *PN = dyn_cast<PHINode>(U)) 11518 SE->ConstantEvolutionLoopExitValue.erase(PN); 11519 SE->eraseValueFromMap(U); 11520 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11521 } 11522 // Delete the Old value. 11523 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11524 SE->ConstantEvolutionLoopExitValue.erase(PN); 11525 SE->eraseValueFromMap(Old); 11526 // this now dangles! 11527 } 11528 11529 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11530 : CallbackVH(V), SE(se) {} 11531 11532 //===----------------------------------------------------------------------===// 11533 // ScalarEvolution Class Implementation 11534 //===----------------------------------------------------------------------===// 11535 11536 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11537 AssumptionCache &AC, DominatorTree &DT, 11538 LoopInfo &LI) 11539 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11540 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11541 LoopDispositions(64), BlockDispositions(64) { 11542 // To use guards for proving predicates, we need to scan every instruction in 11543 // relevant basic blocks, and not just terminators. Doing this is a waste of 11544 // time if the IR does not actually contain any calls to 11545 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11546 // 11547 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11548 // to _add_ guards to the module when there weren't any before, and wants 11549 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11550 // efficient in lieu of being smart in that rather obscure case. 11551 11552 auto *GuardDecl = F.getParent()->getFunction( 11553 Intrinsic::getName(Intrinsic::experimental_guard)); 11554 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11555 } 11556 11557 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11558 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11559 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11560 ValueExprMap(std::move(Arg.ValueExprMap)), 11561 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11562 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11563 PendingMerges(std::move(Arg.PendingMerges)), 11564 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11565 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11566 PredicatedBackedgeTakenCounts( 11567 std::move(Arg.PredicatedBackedgeTakenCounts)), 11568 ConstantEvolutionLoopExitValue( 11569 std::move(Arg.ConstantEvolutionLoopExitValue)), 11570 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11571 LoopDispositions(std::move(Arg.LoopDispositions)), 11572 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11573 BlockDispositions(std::move(Arg.BlockDispositions)), 11574 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11575 SignedRanges(std::move(Arg.SignedRanges)), 11576 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11577 UniquePreds(std::move(Arg.UniquePreds)), 11578 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11579 LoopUsers(std::move(Arg.LoopUsers)), 11580 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11581 FirstUnknown(Arg.FirstUnknown) { 11582 Arg.FirstUnknown = nullptr; 11583 } 11584 11585 ScalarEvolution::~ScalarEvolution() { 11586 // Iterate through all the SCEVUnknown instances and call their 11587 // destructors, so that they release their references to their values. 11588 for (SCEVUnknown *U = FirstUnknown; U;) { 11589 SCEVUnknown *Tmp = U; 11590 U = U->Next; 11591 Tmp->~SCEVUnknown(); 11592 } 11593 FirstUnknown = nullptr; 11594 11595 ExprValueMap.clear(); 11596 ValueExprMap.clear(); 11597 HasRecMap.clear(); 11598 11599 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11600 // that a loop had multiple computable exits. 11601 for (auto &BTCI : BackedgeTakenCounts) 11602 BTCI.second.clear(); 11603 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11604 BTCI.second.clear(); 11605 11606 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11607 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11608 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11609 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11610 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11611 } 11612 11613 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11614 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11615 } 11616 11617 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11618 const Loop *L) { 11619 // Print all inner loops first 11620 for (Loop *I : *L) 11621 PrintLoopInfo(OS, SE, I); 11622 11623 OS << "Loop "; 11624 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11625 OS << ": "; 11626 11627 SmallVector<BasicBlock *, 8> ExitingBlocks; 11628 L->getExitingBlocks(ExitingBlocks); 11629 if (ExitingBlocks.size() != 1) 11630 OS << "<multiple exits> "; 11631 11632 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11633 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11634 else 11635 OS << "Unpredictable backedge-taken count.\n"; 11636 11637 if (ExitingBlocks.size() > 1) 11638 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11639 OS << " exit count for " << ExitingBlock->getName() << ": " 11640 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11641 } 11642 11643 OS << "Loop "; 11644 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11645 OS << ": "; 11646 11647 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11648 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11649 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11650 OS << ", actual taken count either this or zero."; 11651 } else { 11652 OS << "Unpredictable max backedge-taken count. "; 11653 } 11654 11655 OS << "\n" 11656 "Loop "; 11657 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11658 OS << ": "; 11659 11660 SCEVUnionPredicate Pred; 11661 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11662 if (!isa<SCEVCouldNotCompute>(PBT)) { 11663 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11664 OS << " Predicates:\n"; 11665 Pred.print(OS, 4); 11666 } else { 11667 OS << "Unpredictable predicated backedge-taken count. "; 11668 } 11669 OS << "\n"; 11670 11671 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11672 OS << "Loop "; 11673 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11674 OS << ": "; 11675 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11676 } 11677 } 11678 11679 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11680 switch (LD) { 11681 case ScalarEvolution::LoopVariant: 11682 return "Variant"; 11683 case ScalarEvolution::LoopInvariant: 11684 return "Invariant"; 11685 case ScalarEvolution::LoopComputable: 11686 return "Computable"; 11687 } 11688 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11689 } 11690 11691 void ScalarEvolution::print(raw_ostream &OS) const { 11692 // ScalarEvolution's implementation of the print method is to print 11693 // out SCEV values of all instructions that are interesting. Doing 11694 // this potentially causes it to create new SCEV objects though, 11695 // which technically conflicts with the const qualifier. This isn't 11696 // observable from outside the class though, so casting away the 11697 // const isn't dangerous. 11698 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11699 11700 if (ClassifyExpressions) { 11701 OS << "Classifying expressions for: "; 11702 F.printAsOperand(OS, /*PrintType=*/false); 11703 OS << "\n"; 11704 for (Instruction &I : instructions(F)) 11705 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11706 OS << I << '\n'; 11707 OS << " --> "; 11708 const SCEV *SV = SE.getSCEV(&I); 11709 SV->print(OS); 11710 if (!isa<SCEVCouldNotCompute>(SV)) { 11711 OS << " U: "; 11712 SE.getUnsignedRange(SV).print(OS); 11713 OS << " S: "; 11714 SE.getSignedRange(SV).print(OS); 11715 } 11716 11717 const Loop *L = LI.getLoopFor(I.getParent()); 11718 11719 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11720 if (AtUse != SV) { 11721 OS << " --> "; 11722 AtUse->print(OS); 11723 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11724 OS << " U: "; 11725 SE.getUnsignedRange(AtUse).print(OS); 11726 OS << " S: "; 11727 SE.getSignedRange(AtUse).print(OS); 11728 } 11729 } 11730 11731 if (L) { 11732 OS << "\t\t" "Exits: "; 11733 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11734 if (!SE.isLoopInvariant(ExitValue, L)) { 11735 OS << "<<Unknown>>"; 11736 } else { 11737 OS << *ExitValue; 11738 } 11739 11740 bool First = true; 11741 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11742 if (First) { 11743 OS << "\t\t" "LoopDispositions: { "; 11744 First = false; 11745 } else { 11746 OS << ", "; 11747 } 11748 11749 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11750 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11751 } 11752 11753 for (auto *InnerL : depth_first(L)) { 11754 if (InnerL == L) 11755 continue; 11756 if (First) { 11757 OS << "\t\t" "LoopDispositions: { "; 11758 First = false; 11759 } else { 11760 OS << ", "; 11761 } 11762 11763 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11764 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11765 } 11766 11767 OS << " }"; 11768 } 11769 11770 OS << "\n"; 11771 } 11772 } 11773 11774 OS << "Determining loop execution counts for: "; 11775 F.printAsOperand(OS, /*PrintType=*/false); 11776 OS << "\n"; 11777 for (Loop *I : LI) 11778 PrintLoopInfo(OS, &SE, I); 11779 } 11780 11781 ScalarEvolution::LoopDisposition 11782 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11783 auto &Values = LoopDispositions[S]; 11784 for (auto &V : Values) { 11785 if (V.getPointer() == L) 11786 return V.getInt(); 11787 } 11788 Values.emplace_back(L, LoopVariant); 11789 LoopDisposition D = computeLoopDisposition(S, L); 11790 auto &Values2 = LoopDispositions[S]; 11791 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11792 if (V.getPointer() == L) { 11793 V.setInt(D); 11794 break; 11795 } 11796 } 11797 return D; 11798 } 11799 11800 ScalarEvolution::LoopDisposition 11801 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11802 switch (S->getSCEVType()) { 11803 case scConstant: 11804 return LoopInvariant; 11805 case scTruncate: 11806 case scZeroExtend: 11807 case scSignExtend: 11808 return getLoopDisposition(cast<SCEVIntegralCastExpr>(S)->getOperand(), L); 11809 case scAddRecExpr: { 11810 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11811 11812 // If L is the addrec's loop, it's computable. 11813 if (AR->getLoop() == L) 11814 return LoopComputable; 11815 11816 // Add recurrences are never invariant in the function-body (null loop). 11817 if (!L) 11818 return LoopVariant; 11819 11820 // Everything that is not defined at loop entry is variant. 11821 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11822 return LoopVariant; 11823 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11824 " dominate the contained loop's header?"); 11825 11826 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11827 if (AR->getLoop()->contains(L)) 11828 return LoopInvariant; 11829 11830 // This recurrence is variant w.r.t. L if any of its operands 11831 // are variant. 11832 for (auto *Op : AR->operands()) 11833 if (!isLoopInvariant(Op, L)) 11834 return LoopVariant; 11835 11836 // Otherwise it's loop-invariant. 11837 return LoopInvariant; 11838 } 11839 case scAddExpr: 11840 case scMulExpr: 11841 case scUMaxExpr: 11842 case scSMaxExpr: 11843 case scUMinExpr: 11844 case scSMinExpr: { 11845 bool HasVarying = false; 11846 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11847 LoopDisposition D = getLoopDisposition(Op, L); 11848 if (D == LoopVariant) 11849 return LoopVariant; 11850 if (D == LoopComputable) 11851 HasVarying = true; 11852 } 11853 return HasVarying ? LoopComputable : LoopInvariant; 11854 } 11855 case scUDivExpr: { 11856 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11857 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11858 if (LD == LoopVariant) 11859 return LoopVariant; 11860 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11861 if (RD == LoopVariant) 11862 return LoopVariant; 11863 return (LD == LoopInvariant && RD == LoopInvariant) ? 11864 LoopInvariant : LoopComputable; 11865 } 11866 case scUnknown: 11867 // All non-instruction values are loop invariant. All instructions are loop 11868 // invariant if they are not contained in the specified loop. 11869 // Instructions are never considered invariant in the function body 11870 // (null loop) because they are defined within the "loop". 11871 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11872 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11873 return LoopInvariant; 11874 case scCouldNotCompute: 11875 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11876 } 11877 llvm_unreachable("Unknown SCEV kind!"); 11878 } 11879 11880 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11881 return getLoopDisposition(S, L) == LoopInvariant; 11882 } 11883 11884 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11885 return getLoopDisposition(S, L) == LoopComputable; 11886 } 11887 11888 ScalarEvolution::BlockDisposition 11889 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11890 auto &Values = BlockDispositions[S]; 11891 for (auto &V : Values) { 11892 if (V.getPointer() == BB) 11893 return V.getInt(); 11894 } 11895 Values.emplace_back(BB, DoesNotDominateBlock); 11896 BlockDisposition D = computeBlockDisposition(S, BB); 11897 auto &Values2 = BlockDispositions[S]; 11898 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11899 if (V.getPointer() == BB) { 11900 V.setInt(D); 11901 break; 11902 } 11903 } 11904 return D; 11905 } 11906 11907 ScalarEvolution::BlockDisposition 11908 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11909 switch (S->getSCEVType()) { 11910 case scConstant: 11911 return ProperlyDominatesBlock; 11912 case scTruncate: 11913 case scZeroExtend: 11914 case scSignExtend: 11915 return getBlockDisposition(cast<SCEVIntegralCastExpr>(S)->getOperand(), BB); 11916 case scAddRecExpr: { 11917 // This uses a "dominates" query instead of "properly dominates" query 11918 // to test for proper dominance too, because the instruction which 11919 // produces the addrec's value is a PHI, and a PHI effectively properly 11920 // dominates its entire containing block. 11921 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11922 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11923 return DoesNotDominateBlock; 11924 11925 // Fall through into SCEVNAryExpr handling. 11926 LLVM_FALLTHROUGH; 11927 } 11928 case scAddExpr: 11929 case scMulExpr: 11930 case scUMaxExpr: 11931 case scSMaxExpr: 11932 case scUMinExpr: 11933 case scSMinExpr: { 11934 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11935 bool Proper = true; 11936 for (const SCEV *NAryOp : NAry->operands()) { 11937 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11938 if (D == DoesNotDominateBlock) 11939 return DoesNotDominateBlock; 11940 if (D == DominatesBlock) 11941 Proper = false; 11942 } 11943 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11944 } 11945 case scUDivExpr: { 11946 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11947 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11948 BlockDisposition LD = getBlockDisposition(LHS, BB); 11949 if (LD == DoesNotDominateBlock) 11950 return DoesNotDominateBlock; 11951 BlockDisposition RD = getBlockDisposition(RHS, BB); 11952 if (RD == DoesNotDominateBlock) 11953 return DoesNotDominateBlock; 11954 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11955 ProperlyDominatesBlock : DominatesBlock; 11956 } 11957 case scUnknown: 11958 if (Instruction *I = 11959 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11960 if (I->getParent() == BB) 11961 return DominatesBlock; 11962 if (DT.properlyDominates(I->getParent(), BB)) 11963 return ProperlyDominatesBlock; 11964 return DoesNotDominateBlock; 11965 } 11966 return ProperlyDominatesBlock; 11967 case scCouldNotCompute: 11968 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11969 } 11970 llvm_unreachable("Unknown SCEV kind!"); 11971 } 11972 11973 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11974 return getBlockDisposition(S, BB) >= DominatesBlock; 11975 } 11976 11977 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11978 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11979 } 11980 11981 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11982 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11983 } 11984 11985 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11986 auto IsS = [&](const SCEV *X) { return S == X; }; 11987 auto ContainsS = [&](const SCEV *X) { 11988 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11989 }; 11990 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11991 } 11992 11993 void 11994 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11995 ValuesAtScopes.erase(S); 11996 LoopDispositions.erase(S); 11997 BlockDispositions.erase(S); 11998 UnsignedRanges.erase(S); 11999 SignedRanges.erase(S); 12000 ExprValueMap.erase(S); 12001 HasRecMap.erase(S); 12002 MinTrailingZerosCache.erase(S); 12003 12004 for (auto I = PredicatedSCEVRewrites.begin(); 12005 I != PredicatedSCEVRewrites.end();) { 12006 std::pair<const SCEV *, const Loop *> Entry = I->first; 12007 if (Entry.first == S) 12008 PredicatedSCEVRewrites.erase(I++); 12009 else 12010 ++I; 12011 } 12012 12013 auto RemoveSCEVFromBackedgeMap = 12014 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12015 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12016 BackedgeTakenInfo &BEInfo = I->second; 12017 if (BEInfo.hasOperand(S, this)) { 12018 BEInfo.clear(); 12019 Map.erase(I++); 12020 } else 12021 ++I; 12022 } 12023 }; 12024 12025 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12026 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12027 } 12028 12029 void 12030 ScalarEvolution::getUsedLoops(const SCEV *S, 12031 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12032 struct FindUsedLoops { 12033 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12034 : LoopsUsed(LoopsUsed) {} 12035 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12036 bool follow(const SCEV *S) { 12037 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12038 LoopsUsed.insert(AR->getLoop()); 12039 return true; 12040 } 12041 12042 bool isDone() const { return false; } 12043 }; 12044 12045 FindUsedLoops F(LoopsUsed); 12046 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12047 } 12048 12049 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12050 SmallPtrSet<const Loop *, 8> LoopsUsed; 12051 getUsedLoops(S, LoopsUsed); 12052 for (auto *L : LoopsUsed) 12053 LoopUsers[L].push_back(S); 12054 } 12055 12056 void ScalarEvolution::verify() const { 12057 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12058 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12059 12060 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12061 12062 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12063 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12064 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12065 12066 const SCEV *visitConstant(const SCEVConstant *Constant) { 12067 return SE.getConstant(Constant->getAPInt()); 12068 } 12069 12070 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12071 return SE.getUnknown(Expr->getValue()); 12072 } 12073 12074 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12075 return SE.getCouldNotCompute(); 12076 } 12077 }; 12078 12079 SCEVMapper SCM(SE2); 12080 12081 while (!LoopStack.empty()) { 12082 auto *L = LoopStack.pop_back_val(); 12083 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12084 12085 auto *CurBECount = SCM.visit( 12086 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12087 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12088 12089 if (CurBECount == SE2.getCouldNotCompute() || 12090 NewBECount == SE2.getCouldNotCompute()) { 12091 // NB! This situation is legal, but is very suspicious -- whatever pass 12092 // change the loop to make a trip count go from could not compute to 12093 // computable or vice-versa *should have* invalidated SCEV. However, we 12094 // choose not to assert here (for now) since we don't want false 12095 // positives. 12096 continue; 12097 } 12098 12099 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12100 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12101 // not propagate undef aggressively). This means we can (and do) fail 12102 // verification in cases where a transform makes the trip count of a loop 12103 // go from "undef" to "undef+1" (say). The transform is fine, since in 12104 // both cases the loop iterates "undef" times, but SCEV thinks we 12105 // increased the trip count of the loop by 1 incorrectly. 12106 continue; 12107 } 12108 12109 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12110 SE.getTypeSizeInBits(NewBECount->getType())) 12111 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12112 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12113 SE.getTypeSizeInBits(NewBECount->getType())) 12114 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12115 12116 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12117 12118 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12119 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12120 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12121 dbgs() << "Old: " << *CurBECount << "\n"; 12122 dbgs() << "New: " << *NewBECount << "\n"; 12123 dbgs() << "Delta: " << *Delta << "\n"; 12124 std::abort(); 12125 } 12126 } 12127 12128 // Collect all valid loops currently in LoopInfo. 12129 SmallPtrSet<Loop *, 32> ValidLoops; 12130 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12131 while (!Worklist.empty()) { 12132 Loop *L = Worklist.pop_back_val(); 12133 if (ValidLoops.contains(L)) 12134 continue; 12135 ValidLoops.insert(L); 12136 Worklist.append(L->begin(), L->end()); 12137 } 12138 // Check for SCEV expressions referencing invalid/deleted loops. 12139 for (auto &KV : ValueExprMap) { 12140 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12141 if (!AR) 12142 continue; 12143 assert(ValidLoops.contains(AR->getLoop()) && 12144 "AddRec references invalid loop"); 12145 } 12146 } 12147 12148 bool ScalarEvolution::invalidate( 12149 Function &F, const PreservedAnalyses &PA, 12150 FunctionAnalysisManager::Invalidator &Inv) { 12151 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12152 // of its dependencies is invalidated. 12153 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12154 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12155 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12156 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12157 Inv.invalidate<LoopAnalysis>(F, PA); 12158 } 12159 12160 AnalysisKey ScalarEvolutionAnalysis::Key; 12161 12162 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12163 FunctionAnalysisManager &AM) { 12164 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12165 AM.getResult<AssumptionAnalysis>(F), 12166 AM.getResult<DominatorTreeAnalysis>(F), 12167 AM.getResult<LoopAnalysis>(F)); 12168 } 12169 12170 PreservedAnalyses 12171 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12172 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12173 return PreservedAnalyses::all(); 12174 } 12175 12176 PreservedAnalyses 12177 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12178 // For compatibility with opt's -analyze feature under legacy pass manager 12179 // which was not ported to NPM. This keeps tests using 12180 // update_analyze_test_checks.py working. 12181 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12182 << F.getName() << "':\n"; 12183 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12184 return PreservedAnalyses::all(); 12185 } 12186 12187 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12188 "Scalar Evolution Analysis", false, true) 12189 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12190 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12191 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12192 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12193 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12194 "Scalar Evolution Analysis", false, true) 12195 12196 char ScalarEvolutionWrapperPass::ID = 0; 12197 12198 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12199 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12200 } 12201 12202 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12203 SE.reset(new ScalarEvolution( 12204 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12205 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12206 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12207 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12208 return false; 12209 } 12210 12211 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12212 12213 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12214 SE->print(OS); 12215 } 12216 12217 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12218 if (!VerifySCEV) 12219 return; 12220 12221 SE->verify(); 12222 } 12223 12224 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12225 AU.setPreservesAll(); 12226 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12227 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12228 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12229 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12230 } 12231 12232 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12233 const SCEV *RHS) { 12234 FoldingSetNodeID ID; 12235 assert(LHS->getType() == RHS->getType() && 12236 "Type mismatch between LHS and RHS"); 12237 // Unique this node based on the arguments 12238 ID.AddInteger(SCEVPredicate::P_Equal); 12239 ID.AddPointer(LHS); 12240 ID.AddPointer(RHS); 12241 void *IP = nullptr; 12242 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12243 return S; 12244 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12245 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12246 UniquePreds.InsertNode(Eq, IP); 12247 return Eq; 12248 } 12249 12250 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12251 const SCEVAddRecExpr *AR, 12252 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12253 FoldingSetNodeID ID; 12254 // Unique this node based on the arguments 12255 ID.AddInteger(SCEVPredicate::P_Wrap); 12256 ID.AddPointer(AR); 12257 ID.AddInteger(AddedFlags); 12258 void *IP = nullptr; 12259 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12260 return S; 12261 auto *OF = new (SCEVAllocator) 12262 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12263 UniquePreds.InsertNode(OF, IP); 12264 return OF; 12265 } 12266 12267 namespace { 12268 12269 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12270 public: 12271 12272 /// Rewrites \p S in the context of a loop L and the SCEV predication 12273 /// infrastructure. 12274 /// 12275 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12276 /// equivalences present in \p Pred. 12277 /// 12278 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12279 /// \p NewPreds such that the result will be an AddRecExpr. 12280 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12281 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12282 SCEVUnionPredicate *Pred) { 12283 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12284 return Rewriter.visit(S); 12285 } 12286 12287 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12288 if (Pred) { 12289 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12290 for (auto *Pred : ExprPreds) 12291 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12292 if (IPred->getLHS() == Expr) 12293 return IPred->getRHS(); 12294 } 12295 return convertToAddRecWithPreds(Expr); 12296 } 12297 12298 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12299 const SCEV *Operand = visit(Expr->getOperand()); 12300 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12301 if (AR && AR->getLoop() == L && AR->isAffine()) { 12302 // This couldn't be folded because the operand didn't have the nuw 12303 // flag. Add the nusw flag as an assumption that we could make. 12304 const SCEV *Step = AR->getStepRecurrence(SE); 12305 Type *Ty = Expr->getType(); 12306 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12307 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12308 SE.getSignExtendExpr(Step, Ty), L, 12309 AR->getNoWrapFlags()); 12310 } 12311 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12312 } 12313 12314 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12315 const SCEV *Operand = visit(Expr->getOperand()); 12316 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12317 if (AR && AR->getLoop() == L && AR->isAffine()) { 12318 // This couldn't be folded because the operand didn't have the nsw 12319 // flag. Add the nssw flag as an assumption that we could make. 12320 const SCEV *Step = AR->getStepRecurrence(SE); 12321 Type *Ty = Expr->getType(); 12322 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12323 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12324 SE.getSignExtendExpr(Step, Ty), L, 12325 AR->getNoWrapFlags()); 12326 } 12327 return SE.getSignExtendExpr(Operand, Expr->getType()); 12328 } 12329 12330 private: 12331 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12332 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12333 SCEVUnionPredicate *Pred) 12334 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12335 12336 bool addOverflowAssumption(const SCEVPredicate *P) { 12337 if (!NewPreds) { 12338 // Check if we've already made this assumption. 12339 return Pred && Pred->implies(P); 12340 } 12341 NewPreds->insert(P); 12342 return true; 12343 } 12344 12345 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12346 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12347 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12348 return addOverflowAssumption(A); 12349 } 12350 12351 // If \p Expr represents a PHINode, we try to see if it can be represented 12352 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12353 // to add this predicate as a runtime overflow check, we return the AddRec. 12354 // If \p Expr does not meet these conditions (is not a PHI node, or we 12355 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12356 // return \p Expr. 12357 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12358 if (!isa<PHINode>(Expr->getValue())) 12359 return Expr; 12360 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12361 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12362 if (!PredicatedRewrite) 12363 return Expr; 12364 for (auto *P : PredicatedRewrite->second){ 12365 // Wrap predicates from outer loops are not supported. 12366 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12367 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12368 if (L != AR->getLoop()) 12369 return Expr; 12370 } 12371 if (!addOverflowAssumption(P)) 12372 return Expr; 12373 } 12374 return PredicatedRewrite->first; 12375 } 12376 12377 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12378 SCEVUnionPredicate *Pred; 12379 const Loop *L; 12380 }; 12381 12382 } // end anonymous namespace 12383 12384 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12385 SCEVUnionPredicate &Preds) { 12386 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12387 } 12388 12389 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12390 const SCEV *S, const Loop *L, 12391 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12392 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12393 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12394 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12395 12396 if (!AddRec) 12397 return nullptr; 12398 12399 // Since the transformation was successful, we can now transfer the SCEV 12400 // predicates. 12401 for (auto *P : TransformPreds) 12402 Preds.insert(P); 12403 12404 return AddRec; 12405 } 12406 12407 /// SCEV predicates 12408 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12409 SCEVPredicateKind Kind) 12410 : FastID(ID), Kind(Kind) {} 12411 12412 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12413 const SCEV *LHS, const SCEV *RHS) 12414 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12415 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12416 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12417 } 12418 12419 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12420 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12421 12422 if (!Op) 12423 return false; 12424 12425 return Op->LHS == LHS && Op->RHS == RHS; 12426 } 12427 12428 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12429 12430 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12431 12432 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12433 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12434 } 12435 12436 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12437 const SCEVAddRecExpr *AR, 12438 IncrementWrapFlags Flags) 12439 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12440 12441 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12442 12443 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12444 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12445 12446 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12447 } 12448 12449 bool SCEVWrapPredicate::isAlwaysTrue() const { 12450 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12451 IncrementWrapFlags IFlags = Flags; 12452 12453 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12454 IFlags = clearFlags(IFlags, IncrementNSSW); 12455 12456 return IFlags == IncrementAnyWrap; 12457 } 12458 12459 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12460 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12461 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12462 OS << "<nusw>"; 12463 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12464 OS << "<nssw>"; 12465 OS << "\n"; 12466 } 12467 12468 SCEVWrapPredicate::IncrementWrapFlags 12469 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12470 ScalarEvolution &SE) { 12471 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12472 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12473 12474 // We can safely transfer the NSW flag as NSSW. 12475 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12476 ImpliedFlags = IncrementNSSW; 12477 12478 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12479 // If the increment is positive, the SCEV NUW flag will also imply the 12480 // WrapPredicate NUSW flag. 12481 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12482 if (Step->getValue()->getValue().isNonNegative()) 12483 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12484 } 12485 12486 return ImpliedFlags; 12487 } 12488 12489 /// Union predicates don't get cached so create a dummy set ID for it. 12490 SCEVUnionPredicate::SCEVUnionPredicate() 12491 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12492 12493 bool SCEVUnionPredicate::isAlwaysTrue() const { 12494 return all_of(Preds, 12495 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12496 } 12497 12498 ArrayRef<const SCEVPredicate *> 12499 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12500 auto I = SCEVToPreds.find(Expr); 12501 if (I == SCEVToPreds.end()) 12502 return ArrayRef<const SCEVPredicate *>(); 12503 return I->second; 12504 } 12505 12506 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12507 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12508 return all_of(Set->Preds, 12509 [this](const SCEVPredicate *I) { return this->implies(I); }); 12510 12511 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12512 if (ScevPredsIt == SCEVToPreds.end()) 12513 return false; 12514 auto &SCEVPreds = ScevPredsIt->second; 12515 12516 return any_of(SCEVPreds, 12517 [N](const SCEVPredicate *I) { return I->implies(N); }); 12518 } 12519 12520 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12521 12522 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12523 for (auto Pred : Preds) 12524 Pred->print(OS, Depth); 12525 } 12526 12527 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12528 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12529 for (auto Pred : Set->Preds) 12530 add(Pred); 12531 return; 12532 } 12533 12534 if (implies(N)) 12535 return; 12536 12537 const SCEV *Key = N->getExpr(); 12538 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12539 " associated expression!"); 12540 12541 SCEVToPreds[Key].push_back(N); 12542 Preds.push_back(N); 12543 } 12544 12545 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12546 Loop &L) 12547 : SE(SE), L(L) {} 12548 12549 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12550 const SCEV *Expr = SE.getSCEV(V); 12551 RewriteEntry &Entry = RewriteMap[Expr]; 12552 12553 // If we already have an entry and the version matches, return it. 12554 if (Entry.second && Generation == Entry.first) 12555 return Entry.second; 12556 12557 // We found an entry but it's stale. Rewrite the stale entry 12558 // according to the current predicate. 12559 if (Entry.second) 12560 Expr = Entry.second; 12561 12562 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12563 Entry = {Generation, NewSCEV}; 12564 12565 return NewSCEV; 12566 } 12567 12568 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12569 if (!BackedgeCount) { 12570 SCEVUnionPredicate BackedgePred; 12571 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12572 addPredicate(BackedgePred); 12573 } 12574 return BackedgeCount; 12575 } 12576 12577 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12578 if (Preds.implies(&Pred)) 12579 return; 12580 Preds.add(&Pred); 12581 updateGeneration(); 12582 } 12583 12584 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12585 return Preds; 12586 } 12587 12588 void PredicatedScalarEvolution::updateGeneration() { 12589 // If the generation number wrapped recompute everything. 12590 if (++Generation == 0) { 12591 for (auto &II : RewriteMap) { 12592 const SCEV *Rewritten = II.second.second; 12593 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12594 } 12595 } 12596 } 12597 12598 void PredicatedScalarEvolution::setNoOverflow( 12599 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12600 const SCEV *Expr = getSCEV(V); 12601 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12602 12603 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12604 12605 // Clear the statically implied flags. 12606 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12607 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12608 12609 auto II = FlagsMap.insert({V, Flags}); 12610 if (!II.second) 12611 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12612 } 12613 12614 bool PredicatedScalarEvolution::hasNoOverflow( 12615 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12616 const SCEV *Expr = getSCEV(V); 12617 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12618 12619 Flags = SCEVWrapPredicate::clearFlags( 12620 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12621 12622 auto II = FlagsMap.find(V); 12623 12624 if (II != FlagsMap.end()) 12625 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12626 12627 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12628 } 12629 12630 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12631 const SCEV *Expr = this->getSCEV(V); 12632 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12633 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12634 12635 if (!New) 12636 return nullptr; 12637 12638 for (auto *P : NewPreds) 12639 Preds.add(P); 12640 12641 updateGeneration(); 12642 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12643 return New; 12644 } 12645 12646 PredicatedScalarEvolution::PredicatedScalarEvolution( 12647 const PredicatedScalarEvolution &Init) 12648 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12649 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12650 for (auto I : Init.FlagsMap) 12651 FlagsMap.insert(I); 12652 } 12653 12654 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12655 // For each block. 12656 for (auto *BB : L.getBlocks()) 12657 for (auto &I : *BB) { 12658 if (!SE.isSCEVable(I.getType())) 12659 continue; 12660 12661 auto *Expr = SE.getSCEV(&I); 12662 auto II = RewriteMap.find(Expr); 12663 12664 if (II == RewriteMap.end()) 12665 continue; 12666 12667 // Don't print things that are not interesting. 12668 if (II->second.second == Expr) 12669 continue; 12670 12671 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12672 OS.indent(Depth + 2) << *Expr << "\n"; 12673 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12674 } 12675 } 12676 12677 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12678 // arbitrary expressions. 12679 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12680 // 4, A / B becomes X / 8). 12681 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12682 const SCEV *&RHS) { 12683 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12684 if (Add == nullptr || Add->getNumOperands() != 2) 12685 return false; 12686 12687 const SCEV *A = Add->getOperand(1); 12688 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12689 12690 if (Mul == nullptr) 12691 return false; 12692 12693 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12694 // (SomeExpr + (-(SomeExpr / B) * B)). 12695 if (Expr == getURemExpr(A, B)) { 12696 LHS = A; 12697 RHS = B; 12698 return true; 12699 } 12700 return false; 12701 }; 12702 12703 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12704 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12705 return MatchURemWithDivisor(Mul->getOperand(1)) || 12706 MatchURemWithDivisor(Mul->getOperand(2)); 12707 12708 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12709 if (Mul->getNumOperands() == 2) 12710 return MatchURemWithDivisor(Mul->getOperand(1)) || 12711 MatchURemWithDivisor(Mul->getOperand(0)) || 12712 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12713 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12714 return false; 12715 } 12716 12717 const SCEV* ScalarEvolution::computeMaxBackedgeTakenCount(const Loop *L) { 12718 SmallVector<BasicBlock*, 16> ExitingBlocks; 12719 L->getExitingBlocks(ExitingBlocks); 12720 12721 // Form an expression for the maximum exit count possible for this loop. We 12722 // merge the max and exact information to approximate a version of 12723 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 12724 SmallVector<const SCEV*, 4> ExitCounts; 12725 for (BasicBlock *ExitingBB : ExitingBlocks) { 12726 const SCEV *ExitCount = getExitCount(L, ExitingBB); 12727 if (isa<SCEVCouldNotCompute>(ExitCount)) 12728 ExitCount = getExitCount(L, ExitingBB, 12729 ScalarEvolution::ConstantMaximum); 12730 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 12731 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 12732 "We should only have known counts for exiting blocks that " 12733 "dominate latch!"); 12734 ExitCounts.push_back(ExitCount); 12735 } 12736 } 12737 if (ExitCounts.empty()) 12738 return getCouldNotCompute(); 12739 return getUMinFromMismatchedTypes(ExitCounts); 12740 } 12741 12742 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 12743 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 12744 /// we cannot guarantee that the replacement is loop invariant in the loop of 12745 /// the AddRec. 12746 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 12747 ValueToSCEVMapTy ⤅ 12748 12749 public: 12750 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 12751 : SCEVRewriteVisitor(SE), Map(M) {} 12752 12753 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 12754 12755 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12756 auto I = Map.find(Expr->getValue()); 12757 if (I == Map.end()) 12758 return Expr; 12759 return I->second; 12760 } 12761 }; 12762 12763 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 12764 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 12765 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 12766 if (!isa<SCEVUnknown>(LHS)) { 12767 std::swap(LHS, RHS); 12768 Predicate = CmpInst::getSwappedPredicate(Predicate); 12769 } 12770 12771 // For now, limit to conditions that provide information about unknown 12772 // expressions. 12773 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 12774 if (!LHSUnknown) 12775 return; 12776 12777 // TODO: use information from more predicates. 12778 switch (Predicate) { 12779 case CmpInst::ICMP_ULT: { 12780 if (!containsAddRecurrence(RHS)) { 12781 const SCEV *Base = LHS; 12782 auto I = RewriteMap.find(LHSUnknown->getValue()); 12783 if (I != RewriteMap.end()) 12784 Base = I->second; 12785 12786 RewriteMap[LHSUnknown->getValue()] = 12787 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 12788 } 12789 break; 12790 } 12791 case CmpInst::ICMP_ULE: { 12792 if (!containsAddRecurrence(RHS)) { 12793 const SCEV *Base = LHS; 12794 auto I = RewriteMap.find(LHSUnknown->getValue()); 12795 if (I != RewriteMap.end()) 12796 Base = I->second; 12797 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 12798 } 12799 break; 12800 } 12801 case CmpInst::ICMP_EQ: 12802 if (isa<SCEVConstant>(RHS)) 12803 RewriteMap[LHSUnknown->getValue()] = RHS; 12804 break; 12805 case CmpInst::ICMP_NE: 12806 if (isa<SCEVConstant>(RHS) && 12807 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 12808 RewriteMap[LHSUnknown->getValue()] = 12809 getUMaxExpr(LHS, getOne(RHS->getType())); 12810 break; 12811 default: 12812 break; 12813 } 12814 }; 12815 // Starting at the loop predecessor, climb up the predecessor chain, as long 12816 // as there are predecessors that can be found that have unique successors 12817 // leading to the original header. 12818 // TODO: share this logic with isLoopEntryGuardedByCond. 12819 ValueToSCEVMapTy RewriteMap; 12820 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 12821 L->getLoopPredecessor(), L->getHeader()); 12822 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 12823 12824 const BranchInst *LoopEntryPredicate = 12825 dyn_cast<BranchInst>(Pair.first->getTerminator()); 12826 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 12827 continue; 12828 12829 // TODO: use information from more complex conditions, e.g. AND expressions. 12830 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 12831 if (!Cmp) 12832 continue; 12833 12834 auto Predicate = Cmp->getPredicate(); 12835 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 12836 Predicate = CmpInst::getInversePredicate(Predicate); 12837 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 12838 getSCEV(Cmp->getOperand(1)), RewriteMap); 12839 } 12840 12841 // Also collect information from assumptions dominating the loop. 12842 for (auto &AssumeVH : AC.assumptions()) { 12843 if (!AssumeVH) 12844 continue; 12845 auto *AssumeI = cast<CallInst>(AssumeVH); 12846 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 12847 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 12848 continue; 12849 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 12850 getSCEV(Cmp->getOperand(1)), RewriteMap); 12851 } 12852 12853 if (RewriteMap.empty()) 12854 return Expr; 12855 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 12856 return Rewriter.visit(Expr); 12857 } 12858