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 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumArrayLenItCounts, 143 "Number of trip counts computed with array length"); 144 STATISTIC(NumTripCountsComputed, 145 "Number of loops with predictable loop counts"); 146 STATISTIC(NumTripCountsNotComputed, 147 "Number of loops without predictable loop counts"); 148 STATISTIC(NumBruteForceTripCountsComputed, 149 "Number of loops with trip counts computed by force"); 150 151 static cl::opt<unsigned> 152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 153 cl::ZeroOrMore, 154 cl::desc("Maximum number of iterations SCEV will " 155 "symbolically execute a constant " 156 "derived loop"), 157 cl::init(100)); 158 159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 160 static cl::opt<bool> VerifySCEV( 161 "verify-scev", cl::Hidden, 162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 163 static cl::opt<bool> VerifySCEVStrict( 164 "verify-scev-strict", cl::Hidden, 165 cl::desc("Enable stricter verification with -verify-scev is passed")); 166 static cl::opt<bool> 167 VerifySCEVMap("verify-scev-maps", cl::Hidden, 168 cl::desc("Verify no dangling value in ScalarEvolution's " 169 "ExprValueMap (slow)")); 170 171 static cl::opt<bool> VerifyIR( 172 "scev-verify-ir", cl::Hidden, 173 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 174 cl::init(false)); 175 176 static cl::opt<unsigned> MulOpsInlineThreshold( 177 "scev-mulops-inline-threshold", cl::Hidden, 178 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 179 cl::init(32)); 180 181 static cl::opt<unsigned> AddOpsInlineThreshold( 182 "scev-addops-inline-threshold", cl::Hidden, 183 cl::desc("Threshold for inlining addition operands into a SCEV"), 184 cl::init(500)); 185 186 static cl::opt<unsigned> MaxSCEVCompareDepth( 187 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 188 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 189 cl::init(32)); 190 191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 192 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 193 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 194 cl::init(2)); 195 196 static cl::opt<unsigned> MaxValueCompareDepth( 197 "scalar-evolution-max-value-compare-depth", cl::Hidden, 198 cl::desc("Maximum depth of recursive value complexity comparisons"), 199 cl::init(2)); 200 201 static cl::opt<unsigned> 202 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 203 cl::desc("Maximum depth of recursive arithmetics"), 204 cl::init(32)); 205 206 static cl::opt<unsigned> MaxConstantEvolvingDepth( 207 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 208 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 209 210 static cl::opt<unsigned> 211 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 212 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 213 cl::init(8)); 214 215 static cl::opt<unsigned> 216 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 217 cl::desc("Max coefficients in AddRec during evolving"), 218 cl::init(8)); 219 220 static cl::opt<unsigned> 221 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 222 cl::desc("Size of the expression which is considered huge"), 223 cl::init(4096)); 224 225 static cl::opt<bool> 226 ClassifyExpressions("scalar-evolution-classify-expressions", 227 cl::Hidden, cl::init(true), 228 cl::desc("When printing analysis, include information on every instruction")); 229 230 static cl::opt<bool> UseExpensiveRangeSharpening( 231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 232 cl::init(false), 233 cl::desc("Use more powerful methods of sharpening expression ranges. May " 234 "be costly in terms of compile time")); 235 236 //===----------------------------------------------------------------------===// 237 // SCEV class definitions 238 //===----------------------------------------------------------------------===// 239 240 //===----------------------------------------------------------------------===// 241 // Implementation of the SCEV class. 242 // 243 244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 245 LLVM_DUMP_METHOD void SCEV::dump() const { 246 print(dbgs()); 247 dbgs() << '\n'; 248 } 249 #endif 250 251 void SCEV::print(raw_ostream &OS) const { 252 switch (getSCEVType()) { 253 case scConstant: 254 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 255 return; 256 case scPtrToInt: { 257 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 258 const SCEV *Op = PtrToInt->getOperand(); 259 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 260 << *PtrToInt->getType() << ")"; 261 return; 262 } 263 case scTruncate: { 264 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 265 const SCEV *Op = Trunc->getOperand(); 266 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 267 << *Trunc->getType() << ")"; 268 return; 269 } 270 case scZeroExtend: { 271 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 272 const SCEV *Op = ZExt->getOperand(); 273 OS << "(zext " << *Op->getType() << " " << *Op << " to " 274 << *ZExt->getType() << ")"; 275 return; 276 } 277 case scSignExtend: { 278 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 279 const SCEV *Op = SExt->getOperand(); 280 OS << "(sext " << *Op->getType() << " " << *Op << " to " 281 << *SExt->getType() << ")"; 282 return; 283 } 284 case scAddRecExpr: { 285 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 286 OS << "{" << *AR->getOperand(0); 287 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 288 OS << ",+," << *AR->getOperand(i); 289 OS << "}<"; 290 if (AR->hasNoUnsignedWrap()) 291 OS << "nuw><"; 292 if (AR->hasNoSignedWrap()) 293 OS << "nsw><"; 294 if (AR->hasNoSelfWrap() && 295 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 296 OS << "nw><"; 297 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 298 OS << ">"; 299 return; 300 } 301 case scAddExpr: 302 case scMulExpr: 303 case scUMaxExpr: 304 case scSMaxExpr: 305 case scUMinExpr: 306 case scSMinExpr: { 307 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 308 const char *OpStr = nullptr; 309 switch (NAry->getSCEVType()) { 310 case scAddExpr: OpStr = " + "; break; 311 case scMulExpr: OpStr = " * "; break; 312 case scUMaxExpr: OpStr = " umax "; break; 313 case scSMaxExpr: OpStr = " smax "; break; 314 case scUMinExpr: 315 OpStr = " umin "; 316 break; 317 case scSMinExpr: 318 OpStr = " smin "; 319 break; 320 default: 321 llvm_unreachable("There are no other nary expression types."); 322 } 323 OS << "("; 324 ListSeparator LS(OpStr); 325 for (const SCEV *Op : NAry->operands()) 326 OS << LS << *Op; 327 OS << ")"; 328 switch (NAry->getSCEVType()) { 329 case scAddExpr: 330 case scMulExpr: 331 if (NAry->hasNoUnsignedWrap()) 332 OS << "<nuw>"; 333 if (NAry->hasNoSignedWrap()) 334 OS << "<nsw>"; 335 break; 336 default: 337 // Nothing to print for other nary expressions. 338 break; 339 } 340 return; 341 } 342 case scUDivExpr: { 343 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 344 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 345 return; 346 } 347 case scUnknown: { 348 const SCEVUnknown *U = cast<SCEVUnknown>(this); 349 Type *AllocTy; 350 if (U->isSizeOf(AllocTy)) { 351 OS << "sizeof(" << *AllocTy << ")"; 352 return; 353 } 354 if (U->isAlignOf(AllocTy)) { 355 OS << "alignof(" << *AllocTy << ")"; 356 return; 357 } 358 359 Type *CTy; 360 Constant *FieldNo; 361 if (U->isOffsetOf(CTy, FieldNo)) { 362 OS << "offsetof(" << *CTy << ", "; 363 FieldNo->printAsOperand(OS, false); 364 OS << ")"; 365 return; 366 } 367 368 // Otherwise just print it normally. 369 U->getValue()->printAsOperand(OS, false); 370 return; 371 } 372 case scCouldNotCompute: 373 OS << "***COULDNOTCOMPUTE***"; 374 return; 375 } 376 llvm_unreachable("Unknown SCEV kind!"); 377 } 378 379 Type *SCEV::getType() const { 380 switch (getSCEVType()) { 381 case scConstant: 382 return cast<SCEVConstant>(this)->getType(); 383 case scPtrToInt: 384 case scTruncate: 385 case scZeroExtend: 386 case scSignExtend: 387 return cast<SCEVCastExpr>(this)->getType(); 388 case scAddRecExpr: 389 return cast<SCEVAddRecExpr>(this)->getType(); 390 case scMulExpr: 391 return cast<SCEVMulExpr>(this)->getType(); 392 case scUMaxExpr: 393 case scSMaxExpr: 394 case scUMinExpr: 395 case scSMinExpr: 396 return cast<SCEVMinMaxExpr>(this)->getType(); 397 case scAddExpr: 398 return cast<SCEVAddExpr>(this)->getType(); 399 case scUDivExpr: 400 return cast<SCEVUDivExpr>(this)->getType(); 401 case scUnknown: 402 return cast<SCEVUnknown>(this)->getType(); 403 case scCouldNotCompute: 404 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 405 } 406 llvm_unreachable("Unknown SCEV kind!"); 407 } 408 409 bool SCEV::isZero() const { 410 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 411 return SC->getValue()->isZero(); 412 return false; 413 } 414 415 bool SCEV::isOne() const { 416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 417 return SC->getValue()->isOne(); 418 return false; 419 } 420 421 bool SCEV::isAllOnesValue() const { 422 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 423 return SC->getValue()->isMinusOne(); 424 return false; 425 } 426 427 bool SCEV::isNonConstantNegative() const { 428 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 429 if (!Mul) return false; 430 431 // If there is a constant factor, it will be first. 432 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 433 if (!SC) return false; 434 435 // Return true if the value is negative, this matches things like (-42 * V). 436 return SC->getAPInt().isNegative(); 437 } 438 439 SCEVCouldNotCompute::SCEVCouldNotCompute() : 440 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 441 442 bool SCEVCouldNotCompute::classof(const SCEV *S) { 443 return S->getSCEVType() == scCouldNotCompute; 444 } 445 446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 447 FoldingSetNodeID ID; 448 ID.AddInteger(scConstant); 449 ID.AddPointer(V); 450 void *IP = nullptr; 451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 452 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 453 UniqueSCEVs.InsertNode(S, IP); 454 return S; 455 } 456 457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 458 return getConstant(ConstantInt::get(getContext(), Val)); 459 } 460 461 const SCEV * 462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 463 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 464 return getConstant(ConstantInt::get(ITy, V, isSigned)); 465 } 466 467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 468 const SCEV *op, Type *ty) 469 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 470 Operands[0] = op; 471 } 472 473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 474 Type *ITy) 475 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 476 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 477 "Must be a non-bit-width-changing pointer-to-integer cast!"); 478 } 479 480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 481 SCEVTypes SCEVTy, const SCEV *op, 482 Type *ty) 483 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 484 485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 486 Type *ty) 487 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 488 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 489 "Cannot truncate non-integer value!"); 490 } 491 492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 493 const SCEV *op, Type *ty) 494 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 495 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 496 "Cannot zero extend non-integer value!"); 497 } 498 499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 500 const SCEV *op, Type *ty) 501 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 502 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 503 "Cannot sign extend non-integer value!"); 504 } 505 506 void SCEVUnknown::deleted() { 507 // Clear this SCEVUnknown from various maps. 508 SE->forgetMemoizedResults(this); 509 510 // Remove this SCEVUnknown from the uniquing map. 511 SE->UniqueSCEVs.RemoveNode(this); 512 513 // Release the value. 514 setValPtr(nullptr); 515 } 516 517 void SCEVUnknown::allUsesReplacedWith(Value *New) { 518 // Remove this SCEVUnknown from the uniquing map. 519 SE->UniqueSCEVs.RemoveNode(this); 520 521 // Update this SCEVUnknown to point to the new value. This is needed 522 // because there may still be outstanding SCEVs which still point to 523 // this SCEVUnknown. 524 setValPtr(New); 525 } 526 527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 528 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 529 if (VCE->getOpcode() == Instruction::PtrToInt) 530 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 531 if (CE->getOpcode() == Instruction::GetElementPtr && 532 CE->getOperand(0)->isNullValue() && 533 CE->getNumOperands() == 2) 534 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 535 if (CI->isOne()) { 536 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 537 return true; 538 } 539 540 return false; 541 } 542 543 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 544 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 545 if (VCE->getOpcode() == Instruction::PtrToInt) 546 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 547 if (CE->getOpcode() == Instruction::GetElementPtr && 548 CE->getOperand(0)->isNullValue()) { 549 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 550 if (StructType *STy = dyn_cast<StructType>(Ty)) 551 if (!STy->isPacked() && 552 CE->getNumOperands() == 3 && 553 CE->getOperand(1)->isNullValue()) { 554 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 555 if (CI->isOne() && 556 STy->getNumElements() == 2 && 557 STy->getElementType(0)->isIntegerTy(1)) { 558 AllocTy = STy->getElementType(1); 559 return true; 560 } 561 } 562 } 563 564 return false; 565 } 566 567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 568 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 569 if (VCE->getOpcode() == Instruction::PtrToInt) 570 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 571 if (CE->getOpcode() == Instruction::GetElementPtr && 572 CE->getNumOperands() == 3 && 573 CE->getOperand(0)->isNullValue() && 574 CE->getOperand(1)->isNullValue()) { 575 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 576 // Ignore vector types here so that ScalarEvolutionExpander doesn't 577 // emit getelementptrs that index into vectors. 578 if (Ty->isStructTy() || Ty->isArrayTy()) { 579 CTy = Ty; 580 FieldNo = CE->getOperand(2); 581 return true; 582 } 583 } 584 585 return false; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SCEV Utilities 590 //===----------------------------------------------------------------------===// 591 592 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 593 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 594 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 595 /// have been previously deemed to be "equally complex" by this routine. It is 596 /// intended to avoid exponential time complexity in cases like: 597 /// 598 /// %a = f(%x, %y) 599 /// %b = f(%a, %a) 600 /// %c = f(%b, %b) 601 /// 602 /// %d = f(%x, %y) 603 /// %e = f(%d, %d) 604 /// %f = f(%e, %e) 605 /// 606 /// CompareValueComplexity(%f, %c) 607 /// 608 /// Since we do not continue running this routine on expression trees once we 609 /// have seen unequal values, there is no need to track them in the cache. 610 static int 611 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 612 const LoopInfo *const LI, Value *LV, Value *RV, 613 unsigned Depth) { 614 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 615 return 0; 616 617 // Order pointer values after integer values. This helps SCEVExpander form 618 // GEPs. 619 bool LIsPointer = LV->getType()->isPointerTy(), 620 RIsPointer = RV->getType()->isPointerTy(); 621 if (LIsPointer != RIsPointer) 622 return (int)LIsPointer - (int)RIsPointer; 623 624 // Compare getValueID values. 625 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 626 if (LID != RID) 627 return (int)LID - (int)RID; 628 629 // Sort arguments by their position. 630 if (const auto *LA = dyn_cast<Argument>(LV)) { 631 const auto *RA = cast<Argument>(RV); 632 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 633 return (int)LArgNo - (int)RArgNo; 634 } 635 636 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 637 const auto *RGV = cast<GlobalValue>(RV); 638 639 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 640 auto LT = GV->getLinkage(); 641 return !(GlobalValue::isPrivateLinkage(LT) || 642 GlobalValue::isInternalLinkage(LT)); 643 }; 644 645 // Use the names to distinguish the two values, but only if the 646 // names are semantically important. 647 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 648 return LGV->getName().compare(RGV->getName()); 649 } 650 651 // For instructions, compare their loop depth, and their operand count. This 652 // is pretty loose. 653 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 654 const auto *RInst = cast<Instruction>(RV); 655 656 // Compare loop depths. 657 const BasicBlock *LParent = LInst->getParent(), 658 *RParent = RInst->getParent(); 659 if (LParent != RParent) { 660 unsigned LDepth = LI->getLoopDepth(LParent), 661 RDepth = LI->getLoopDepth(RParent); 662 if (LDepth != RDepth) 663 return (int)LDepth - (int)RDepth; 664 } 665 666 // Compare the number of operands. 667 unsigned LNumOps = LInst->getNumOperands(), 668 RNumOps = RInst->getNumOperands(); 669 if (LNumOps != RNumOps) 670 return (int)LNumOps - (int)RNumOps; 671 672 for (unsigned Idx : seq(0u, LNumOps)) { 673 int Result = 674 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 675 RInst->getOperand(Idx), Depth + 1); 676 if (Result != 0) 677 return Result; 678 } 679 } 680 681 EqCacheValue.unionSets(LV, RV); 682 return 0; 683 } 684 685 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 686 // than RHS, respectively. A three-way result allows recursive comparisons to be 687 // more efficient. 688 // If the max analysis depth was reached, return None, assuming we do not know 689 // if they are equivalent for sure. 690 static Optional<int> 691 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 692 EquivalenceClasses<const Value *> &EqCacheValue, 693 const LoopInfo *const LI, const SCEV *LHS, 694 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 695 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 696 if (LHS == RHS) 697 return 0; 698 699 // Primarily, sort the SCEVs by their getSCEVType(). 700 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 701 if (LType != RType) 702 return (int)LType - (int)RType; 703 704 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 705 return 0; 706 707 if (Depth > MaxSCEVCompareDepth) 708 return None; 709 710 // Aside from the getSCEVType() ordering, the particular ordering 711 // isn't very important except that it's beneficial to be consistent, 712 // so that (a + b) and (b + a) don't end up as different expressions. 713 switch (LType) { 714 case scUnknown: { 715 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 716 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 717 718 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 719 RU->getValue(), Depth + 1); 720 if (X == 0) 721 EqCacheSCEV.unionSets(LHS, RHS); 722 return X; 723 } 724 725 case scConstant: { 726 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 727 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 728 729 // Compare constant values. 730 const APInt &LA = LC->getAPInt(); 731 const APInt &RA = RC->getAPInt(); 732 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 733 if (LBitWidth != RBitWidth) 734 return (int)LBitWidth - (int)RBitWidth; 735 return LA.ult(RA) ? -1 : 1; 736 } 737 738 case scAddRecExpr: { 739 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 740 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 741 742 // There is always a dominance between two recs that are used by one SCEV, 743 // so we can safely sort recs by loop header dominance. We require such 744 // order in getAddExpr. 745 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 746 if (LLoop != RLoop) { 747 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 748 assert(LHead != RHead && "Two loops share the same header?"); 749 if (DT.dominates(LHead, RHead)) 750 return 1; 751 else 752 assert(DT.dominates(RHead, LHead) && 753 "No dominance between recurrences used by one SCEV?"); 754 return -1; 755 } 756 757 // Addrec complexity grows with operand count. 758 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 759 if (LNumOps != RNumOps) 760 return (int)LNumOps - (int)RNumOps; 761 762 // Lexicographically compare. 763 for (unsigned i = 0; i != LNumOps; ++i) { 764 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 765 LA->getOperand(i), RA->getOperand(i), DT, 766 Depth + 1); 767 if (X != 0) 768 return X; 769 } 770 EqCacheSCEV.unionSets(LHS, RHS); 771 return 0; 772 } 773 774 case scAddExpr: 775 case scMulExpr: 776 case scSMaxExpr: 777 case scUMaxExpr: 778 case scSMinExpr: 779 case scUMinExpr: { 780 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 781 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 782 783 // Lexicographically compare n-ary expressions. 784 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 785 if (LNumOps != RNumOps) 786 return (int)LNumOps - (int)RNumOps; 787 788 for (unsigned i = 0; i != LNumOps; ++i) { 789 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 790 LC->getOperand(i), RC->getOperand(i), DT, 791 Depth + 1); 792 if (X != 0) 793 return X; 794 } 795 EqCacheSCEV.unionSets(LHS, RHS); 796 return 0; 797 } 798 799 case scUDivExpr: { 800 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 801 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 802 803 // Lexicographically compare udiv expressions. 804 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 805 RC->getLHS(), DT, Depth + 1); 806 if (X != 0) 807 return X; 808 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 809 RC->getRHS(), DT, Depth + 1); 810 if (X == 0) 811 EqCacheSCEV.unionSets(LHS, RHS); 812 return X; 813 } 814 815 case scPtrToInt: 816 case scTruncate: 817 case scZeroExtend: 818 case scSignExtend: { 819 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 820 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 821 822 // Compare cast expressions by operand. 823 auto X = 824 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 825 RC->getOperand(), DT, Depth + 1); 826 if (X == 0) 827 EqCacheSCEV.unionSets(LHS, RHS); 828 return X; 829 } 830 831 case scCouldNotCompute: 832 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 833 } 834 llvm_unreachable("Unknown SCEV kind!"); 835 } 836 837 /// Given a list of SCEV objects, order them by their complexity, and group 838 /// objects of the same complexity together by value. When this routine is 839 /// finished, we know that any duplicates in the vector are consecutive and that 840 /// complexity is monotonically increasing. 841 /// 842 /// Note that we go take special precautions to ensure that we get deterministic 843 /// results from this routine. In other words, we don't want the results of 844 /// this to depend on where the addresses of various SCEV objects happened to 845 /// land in memory. 846 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 847 LoopInfo *LI, DominatorTree &DT) { 848 if (Ops.size() < 2) return; // Noop 849 850 EquivalenceClasses<const SCEV *> EqCacheSCEV; 851 EquivalenceClasses<const Value *> EqCacheValue; 852 853 // Whether LHS has provably less complexity than RHS. 854 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 855 auto Complexity = 856 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 857 return Complexity && *Complexity < 0; 858 }; 859 if (Ops.size() == 2) { 860 // This is the common case, which also happens to be trivially simple. 861 // Special case it. 862 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 863 if (IsLessComplex(RHS, LHS)) 864 std::swap(LHS, RHS); 865 return; 866 } 867 868 // Do the rough sort by complexity. 869 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 870 return IsLessComplex(LHS, RHS); 871 }); 872 873 // Now that we are sorted by complexity, group elements of the same 874 // complexity. Note that this is, at worst, N^2, but the vector is likely to 875 // be extremely short in practice. Note that we take this approach because we 876 // do not want to depend on the addresses of the objects we are grouping. 877 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 878 const SCEV *S = Ops[i]; 879 unsigned Complexity = S->getSCEVType(); 880 881 // If there are any objects of the same complexity and same value as this 882 // one, group them. 883 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 884 if (Ops[j] == S) { // Found a duplicate. 885 // Move it to immediately after i'th element. 886 std::swap(Ops[i+1], Ops[j]); 887 ++i; // no need to rescan it. 888 if (i == e-2) return; // Done! 889 } 890 } 891 } 892 } 893 894 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 895 /// least HugeExprThreshold nodes). 896 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 897 return any_of(Ops, [](const SCEV *S) { 898 return S->getExpressionSize() >= HugeExprThreshold; 899 }); 900 } 901 902 //===----------------------------------------------------------------------===// 903 // Simple SCEV method implementations 904 //===----------------------------------------------------------------------===// 905 906 /// Compute BC(It, K). The result has width W. Assume, K > 0. 907 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 908 ScalarEvolution &SE, 909 Type *ResultTy) { 910 // Handle the simplest case efficiently. 911 if (K == 1) 912 return SE.getTruncateOrZeroExtend(It, ResultTy); 913 914 // We are using the following formula for BC(It, K): 915 // 916 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 917 // 918 // Suppose, W is the bitwidth of the return value. We must be prepared for 919 // overflow. Hence, we must assure that the result of our computation is 920 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 921 // safe in modular arithmetic. 922 // 923 // However, this code doesn't use exactly that formula; the formula it uses 924 // is something like the following, where T is the number of factors of 2 in 925 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 926 // exponentiation: 927 // 928 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 929 // 930 // This formula is trivially equivalent to the previous formula. However, 931 // this formula can be implemented much more efficiently. The trick is that 932 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 933 // arithmetic. To do exact division in modular arithmetic, all we have 934 // to do is multiply by the inverse. Therefore, this step can be done at 935 // width W. 936 // 937 // The next issue is how to safely do the division by 2^T. The way this 938 // is done is by doing the multiplication step at a width of at least W + T 939 // bits. This way, the bottom W+T bits of the product are accurate. Then, 940 // when we perform the division by 2^T (which is equivalent to a right shift 941 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 942 // truncated out after the division by 2^T. 943 // 944 // In comparison to just directly using the first formula, this technique 945 // is much more efficient; using the first formula requires W * K bits, 946 // but this formula less than W + K bits. Also, the first formula requires 947 // a division step, whereas this formula only requires multiplies and shifts. 948 // 949 // It doesn't matter whether the subtraction step is done in the calculation 950 // width or the input iteration count's width; if the subtraction overflows, 951 // the result must be zero anyway. We prefer here to do it in the width of 952 // the induction variable because it helps a lot for certain cases; CodeGen 953 // isn't smart enough to ignore the overflow, which leads to much less 954 // efficient code if the width of the subtraction is wider than the native 955 // register width. 956 // 957 // (It's possible to not widen at all by pulling out factors of 2 before 958 // the multiplication; for example, K=2 can be calculated as 959 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 960 // extra arithmetic, so it's not an obvious win, and it gets 961 // much more complicated for K > 3.) 962 963 // Protection from insane SCEVs; this bound is conservative, 964 // but it probably doesn't matter. 965 if (K > 1000) 966 return SE.getCouldNotCompute(); 967 968 unsigned W = SE.getTypeSizeInBits(ResultTy); 969 970 // Calculate K! / 2^T and T; we divide out the factors of two before 971 // multiplying for calculating K! / 2^T to avoid overflow. 972 // Other overflow doesn't matter because we only care about the bottom 973 // W bits of the result. 974 APInt OddFactorial(W, 1); 975 unsigned T = 1; 976 for (unsigned i = 3; i <= K; ++i) { 977 APInt Mult(W, i); 978 unsigned TwoFactors = Mult.countTrailingZeros(); 979 T += TwoFactors; 980 Mult.lshrInPlace(TwoFactors); 981 OddFactorial *= Mult; 982 } 983 984 // We need at least W + T bits for the multiplication step 985 unsigned CalculationBits = W + T; 986 987 // Calculate 2^T, at width T+W. 988 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 989 990 // Calculate the multiplicative inverse of K! / 2^T; 991 // this multiplication factor will perform the exact division by 992 // K! / 2^T. 993 APInt Mod = APInt::getSignedMinValue(W+1); 994 APInt MultiplyFactor = OddFactorial.zext(W+1); 995 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 996 MultiplyFactor = MultiplyFactor.trunc(W); 997 998 // Calculate the product, at width T+W 999 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1000 CalculationBits); 1001 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1002 for (unsigned i = 1; i != K; ++i) { 1003 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1004 Dividend = SE.getMulExpr(Dividend, 1005 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1006 } 1007 1008 // Divide by 2^T 1009 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1010 1011 // Truncate the result, and divide by K! / 2^T. 1012 1013 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1014 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1015 } 1016 1017 /// Return the value of this chain of recurrences at the specified iteration 1018 /// number. We can evaluate this recurrence by multiplying each element in the 1019 /// chain by the binomial coefficient corresponding to it. In other words, we 1020 /// can evaluate {A,+,B,+,C,+,D} as: 1021 /// 1022 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1023 /// 1024 /// where BC(It, k) stands for binomial coefficient. 1025 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1026 ScalarEvolution &SE) const { 1027 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1028 } 1029 1030 const SCEV * 1031 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1032 const SCEV *It, ScalarEvolution &SE) { 1033 assert(Operands.size() > 0); 1034 const SCEV *Result = Operands[0]; 1035 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1036 // The computation is correct in the face of overflow provided that the 1037 // multiplication is performed _after_ the evaluation of the binomial 1038 // coefficient. 1039 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1040 if (isa<SCEVCouldNotCompute>(Coeff)) 1041 return Coeff; 1042 1043 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1044 } 1045 return Result; 1046 } 1047 1048 //===----------------------------------------------------------------------===// 1049 // SCEV Expression folder implementations 1050 //===----------------------------------------------------------------------===// 1051 1052 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1053 unsigned Depth) { 1054 assert(Depth <= 1 && 1055 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1056 1057 // We could be called with an integer-typed operands during SCEV rewrites. 1058 // Since the operand is an integer already, just perform zext/trunc/self cast. 1059 if (!Op->getType()->isPointerTy()) 1060 return Op; 1061 1062 // What would be an ID for such a SCEV cast expression? 1063 FoldingSetNodeID ID; 1064 ID.AddInteger(scPtrToInt); 1065 ID.AddPointer(Op); 1066 1067 void *IP = nullptr; 1068 1069 // Is there already an expression for such a cast? 1070 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1071 return S; 1072 1073 // It isn't legal for optimizations to construct new ptrtoint expressions 1074 // for non-integral pointers. 1075 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1076 return getCouldNotCompute(); 1077 1078 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1079 1080 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1081 // is sufficiently wide to represent all possible pointer values. 1082 // We could theoretically teach SCEV to truncate wider pointers, but 1083 // that isn't implemented for now. 1084 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1085 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1086 return getCouldNotCompute(); 1087 1088 // If not, is this expression something we can't reduce any further? 1089 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1090 // Perform some basic constant folding. If the operand of the ptr2int cast 1091 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1092 // left as-is), but produce a zero constant. 1093 // NOTE: We could handle a more general case, but lack motivational cases. 1094 if (isa<ConstantPointerNull>(U->getValue())) 1095 return getZero(IntPtrTy); 1096 1097 // Create an explicit cast node. 1098 // We can reuse the existing insert position since if we get here, 1099 // we won't have made any changes which would invalidate it. 1100 SCEV *S = new (SCEVAllocator) 1101 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1102 UniqueSCEVs.InsertNode(S, IP); 1103 addToLoopUseLists(S); 1104 return S; 1105 } 1106 1107 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1108 "non-SCEVUnknown's."); 1109 1110 // Otherwise, we've got some expression that is more complex than just a 1111 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1112 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1113 // only, and the expressions must otherwise be integer-typed. 1114 // So sink the cast down to the SCEVUnknown's. 1115 1116 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1117 /// which computes a pointer-typed value, and rewrites the whole expression 1118 /// tree so that *all* the computations are done on integers, and the only 1119 /// pointer-typed operands in the expression are SCEVUnknown. 1120 class SCEVPtrToIntSinkingRewriter 1121 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1122 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1123 1124 public: 1125 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1126 1127 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1128 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1129 return Rewriter.visit(Scev); 1130 } 1131 1132 const SCEV *visit(const SCEV *S) { 1133 Type *STy = S->getType(); 1134 // If the expression is not pointer-typed, just keep it as-is. 1135 if (!STy->isPointerTy()) 1136 return S; 1137 // Else, recursively sink the cast down into it. 1138 return Base::visit(S); 1139 } 1140 1141 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1142 SmallVector<const SCEV *, 2> Operands; 1143 bool Changed = false; 1144 for (auto *Op : Expr->operands()) { 1145 Operands.push_back(visit(Op)); 1146 Changed |= Op != Operands.back(); 1147 } 1148 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1149 } 1150 1151 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1152 SmallVector<const SCEV *, 2> Operands; 1153 bool Changed = false; 1154 for (auto *Op : Expr->operands()) { 1155 Operands.push_back(visit(Op)); 1156 Changed |= Op != Operands.back(); 1157 } 1158 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1159 } 1160 1161 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1162 assert(Expr->getType()->isPointerTy() && 1163 "Should only reach pointer-typed SCEVUnknown's."); 1164 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1165 } 1166 }; 1167 1168 // And actually perform the cast sinking. 1169 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1170 assert(IntOp->getType()->isIntegerTy() && 1171 "We must have succeeded in sinking the cast, " 1172 "and ending up with an integer-typed expression!"); 1173 return IntOp; 1174 } 1175 1176 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1177 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1178 1179 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1180 if (isa<SCEVCouldNotCompute>(IntOp)) 1181 return IntOp; 1182 1183 return getTruncateOrZeroExtend(IntOp, Ty); 1184 } 1185 1186 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1187 unsigned Depth) { 1188 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1189 "This is not a truncating conversion!"); 1190 assert(isSCEVable(Ty) && 1191 "This is not a conversion to a SCEVable type!"); 1192 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1193 Ty = getEffectiveSCEVType(Ty); 1194 1195 FoldingSetNodeID ID; 1196 ID.AddInteger(scTruncate); 1197 ID.AddPointer(Op); 1198 ID.AddPointer(Ty); 1199 void *IP = nullptr; 1200 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1201 1202 // Fold if the operand is constant. 1203 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1204 return getConstant( 1205 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1206 1207 // trunc(trunc(x)) --> trunc(x) 1208 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1209 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1210 1211 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1212 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1213 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1214 1215 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1216 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1217 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1218 1219 if (Depth > MaxCastDepth) { 1220 SCEV *S = 1221 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1222 UniqueSCEVs.InsertNode(S, IP); 1223 addToLoopUseLists(S); 1224 return S; 1225 } 1226 1227 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1228 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1229 // if after transforming we have at most one truncate, not counting truncates 1230 // that replace other casts. 1231 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1232 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1233 SmallVector<const SCEV *, 4> Operands; 1234 unsigned numTruncs = 0; 1235 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1236 ++i) { 1237 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1238 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1239 isa<SCEVTruncateExpr>(S)) 1240 numTruncs++; 1241 Operands.push_back(S); 1242 } 1243 if (numTruncs < 2) { 1244 if (isa<SCEVAddExpr>(Op)) 1245 return getAddExpr(Operands); 1246 else if (isa<SCEVMulExpr>(Op)) 1247 return getMulExpr(Operands); 1248 else 1249 llvm_unreachable("Unexpected SCEV type for Op."); 1250 } 1251 // Although we checked in the beginning that ID is not in the cache, it is 1252 // possible that during recursion and different modification ID was inserted 1253 // into the cache. So if we find it, just return it. 1254 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1255 return S; 1256 } 1257 1258 // If the input value is a chrec scev, truncate the chrec's operands. 1259 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1260 SmallVector<const SCEV *, 4> Operands; 1261 for (const SCEV *Op : AddRec->operands()) 1262 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1263 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1264 } 1265 1266 // Return zero if truncating to known zeros. 1267 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1268 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1269 return getZero(Ty); 1270 1271 // The cast wasn't folded; create an explicit cast node. We can reuse 1272 // the existing insert position since if we get here, we won't have 1273 // made any changes which would invalidate it. 1274 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1275 Op, Ty); 1276 UniqueSCEVs.InsertNode(S, IP); 1277 addToLoopUseLists(S); 1278 return S; 1279 } 1280 1281 // Get the limit of a recurrence such that incrementing by Step cannot cause 1282 // signed overflow as long as the value of the recurrence within the 1283 // loop does not exceed this limit before incrementing. 1284 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1285 ICmpInst::Predicate *Pred, 1286 ScalarEvolution *SE) { 1287 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1288 if (SE->isKnownPositive(Step)) { 1289 *Pred = ICmpInst::ICMP_SLT; 1290 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1291 SE->getSignedRangeMax(Step)); 1292 } 1293 if (SE->isKnownNegative(Step)) { 1294 *Pred = ICmpInst::ICMP_SGT; 1295 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1296 SE->getSignedRangeMin(Step)); 1297 } 1298 return nullptr; 1299 } 1300 1301 // Get the limit of a recurrence such that incrementing by Step cannot cause 1302 // unsigned overflow as long as the value of the recurrence within the loop does 1303 // not exceed this limit before incrementing. 1304 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1305 ICmpInst::Predicate *Pred, 1306 ScalarEvolution *SE) { 1307 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1308 *Pred = ICmpInst::ICMP_ULT; 1309 1310 return SE->getConstant(APInt::getMinValue(BitWidth) - 1311 SE->getUnsignedRangeMax(Step)); 1312 } 1313 1314 namespace { 1315 1316 struct ExtendOpTraitsBase { 1317 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1318 unsigned); 1319 }; 1320 1321 // Used to make code generic over signed and unsigned overflow. 1322 template <typename ExtendOp> struct ExtendOpTraits { 1323 // Members present: 1324 // 1325 // static const SCEV::NoWrapFlags WrapType; 1326 // 1327 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1328 // 1329 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1330 // ICmpInst::Predicate *Pred, 1331 // ScalarEvolution *SE); 1332 }; 1333 1334 template <> 1335 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1336 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1337 1338 static const GetExtendExprTy GetExtendExpr; 1339 1340 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1341 ICmpInst::Predicate *Pred, 1342 ScalarEvolution *SE) { 1343 return getSignedOverflowLimitForStep(Step, Pred, SE); 1344 } 1345 }; 1346 1347 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1348 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1349 1350 template <> 1351 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1352 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1353 1354 static const GetExtendExprTy GetExtendExpr; 1355 1356 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1357 ICmpInst::Predicate *Pred, 1358 ScalarEvolution *SE) { 1359 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1360 } 1361 }; 1362 1363 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1364 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1365 1366 } // end anonymous namespace 1367 1368 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1369 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1370 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1371 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1372 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1373 // expression "Step + sext/zext(PreIncAR)" is congruent with 1374 // "sext/zext(PostIncAR)" 1375 template <typename ExtendOpTy> 1376 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1377 ScalarEvolution *SE, unsigned Depth) { 1378 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1379 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1380 1381 const Loop *L = AR->getLoop(); 1382 const SCEV *Start = AR->getStart(); 1383 const SCEV *Step = AR->getStepRecurrence(*SE); 1384 1385 // Check for a simple looking step prior to loop entry. 1386 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1387 if (!SA) 1388 return nullptr; 1389 1390 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1391 // subtraction is expensive. For this purpose, perform a quick and dirty 1392 // difference, by checking for Step in the operand list. 1393 SmallVector<const SCEV *, 4> DiffOps; 1394 for (const SCEV *Op : SA->operands()) 1395 if (Op != Step) 1396 DiffOps.push_back(Op); 1397 1398 if (DiffOps.size() == SA->getNumOperands()) 1399 return nullptr; 1400 1401 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1402 // `Step`: 1403 1404 // 1. NSW/NUW flags on the step increment. 1405 auto PreStartFlags = 1406 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1407 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1408 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1409 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1410 1411 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1412 // "S+X does not sign/unsign-overflow". 1413 // 1414 1415 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1416 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1417 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1418 return PreStart; 1419 1420 // 2. Direct overflow check on the step operation's expression. 1421 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1422 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1423 const SCEV *OperandExtendedStart = 1424 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1425 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1426 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1427 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1428 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1429 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1430 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1431 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1432 } 1433 return PreStart; 1434 } 1435 1436 // 3. Loop precondition. 1437 ICmpInst::Predicate Pred; 1438 const SCEV *OverflowLimit = 1439 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1440 1441 if (OverflowLimit && 1442 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1443 return PreStart; 1444 1445 return nullptr; 1446 } 1447 1448 // Get the normalized zero or sign extended expression for this AddRec's Start. 1449 template <typename ExtendOpTy> 1450 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1451 ScalarEvolution *SE, 1452 unsigned Depth) { 1453 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1454 1455 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1456 if (!PreStart) 1457 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1458 1459 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1460 Depth), 1461 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1462 } 1463 1464 // Try to prove away overflow by looking at "nearby" add recurrences. A 1465 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1466 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1467 // 1468 // Formally: 1469 // 1470 // {S,+,X} == {S-T,+,X} + T 1471 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1472 // 1473 // If ({S-T,+,X} + T) does not overflow ... (1) 1474 // 1475 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1476 // 1477 // If {S-T,+,X} does not overflow ... (2) 1478 // 1479 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1480 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1481 // 1482 // If (S-T)+T does not overflow ... (3) 1483 // 1484 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1485 // == {Ext(S),+,Ext(X)} == LHS 1486 // 1487 // Thus, if (1), (2) and (3) are true for some T, then 1488 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1489 // 1490 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1491 // does not overflow" restricted to the 0th iteration. Therefore we only need 1492 // to check for (1) and (2). 1493 // 1494 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1495 // is `Delta` (defined below). 1496 template <typename ExtendOpTy> 1497 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1498 const SCEV *Step, 1499 const Loop *L) { 1500 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1501 1502 // We restrict `Start` to a constant to prevent SCEV from spending too much 1503 // time here. It is correct (but more expensive) to continue with a 1504 // non-constant `Start` and do a general SCEV subtraction to compute 1505 // `PreStart` below. 1506 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1507 if (!StartC) 1508 return false; 1509 1510 APInt StartAI = StartC->getAPInt(); 1511 1512 for (unsigned Delta : {-2, -1, 1, 2}) { 1513 const SCEV *PreStart = getConstant(StartAI - Delta); 1514 1515 FoldingSetNodeID ID; 1516 ID.AddInteger(scAddRecExpr); 1517 ID.AddPointer(PreStart); 1518 ID.AddPointer(Step); 1519 ID.AddPointer(L); 1520 void *IP = nullptr; 1521 const auto *PreAR = 1522 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1523 1524 // Give up if we don't already have the add recurrence we need because 1525 // actually constructing an add recurrence is relatively expensive. 1526 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1527 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1528 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1529 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1530 DeltaS, &Pred, this); 1531 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1532 return true; 1533 } 1534 } 1535 1536 return false; 1537 } 1538 1539 // Finds an integer D for an expression (C + x + y + ...) such that the top 1540 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1541 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1542 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1543 // the (C + x + y + ...) expression is \p WholeAddExpr. 1544 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1545 const SCEVConstant *ConstantTerm, 1546 const SCEVAddExpr *WholeAddExpr) { 1547 const APInt &C = ConstantTerm->getAPInt(); 1548 const unsigned BitWidth = C.getBitWidth(); 1549 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1550 uint32_t TZ = BitWidth; 1551 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1552 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1553 if (TZ) { 1554 // Set D to be as many least significant bits of C as possible while still 1555 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1556 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1557 } 1558 return APInt(BitWidth, 0); 1559 } 1560 1561 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1562 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1563 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1564 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1565 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1566 const APInt &ConstantStart, 1567 const SCEV *Step) { 1568 const unsigned BitWidth = ConstantStart.getBitWidth(); 1569 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1570 if (TZ) 1571 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1572 : ConstantStart; 1573 return APInt(BitWidth, 0); 1574 } 1575 1576 const SCEV * 1577 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1578 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1579 "This is not an extending conversion!"); 1580 assert(isSCEVable(Ty) && 1581 "This is not a conversion to a SCEVable type!"); 1582 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1583 Ty = getEffectiveSCEVType(Ty); 1584 1585 // Fold if the operand is constant. 1586 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1587 return getConstant( 1588 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1589 1590 // zext(zext(x)) --> zext(x) 1591 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1592 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1593 1594 // Before doing any expensive analysis, check to see if we've already 1595 // computed a SCEV for this Op and Ty. 1596 FoldingSetNodeID ID; 1597 ID.AddInteger(scZeroExtend); 1598 ID.AddPointer(Op); 1599 ID.AddPointer(Ty); 1600 void *IP = nullptr; 1601 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1602 if (Depth > MaxCastDepth) { 1603 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1604 Op, Ty); 1605 UniqueSCEVs.InsertNode(S, IP); 1606 addToLoopUseLists(S); 1607 return S; 1608 } 1609 1610 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1611 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1612 // It's possible the bits taken off by the truncate were all zero bits. If 1613 // so, we should be able to simplify this further. 1614 const SCEV *X = ST->getOperand(); 1615 ConstantRange CR = getUnsignedRange(X); 1616 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1617 unsigned NewBits = getTypeSizeInBits(Ty); 1618 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1619 CR.zextOrTrunc(NewBits))) 1620 return getTruncateOrZeroExtend(X, Ty, Depth); 1621 } 1622 1623 // If the input value is a chrec scev, and we can prove that the value 1624 // did not overflow the old, smaller, value, we can zero extend all of the 1625 // operands (often constants). This allows analysis of something like 1626 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1627 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1628 if (AR->isAffine()) { 1629 const SCEV *Start = AR->getStart(); 1630 const SCEV *Step = AR->getStepRecurrence(*this); 1631 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1632 const Loop *L = AR->getLoop(); 1633 1634 if (!AR->hasNoUnsignedWrap()) { 1635 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1636 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1637 } 1638 1639 // If we have special knowledge that this addrec won't overflow, 1640 // we don't need to do any further analysis. 1641 if (AR->hasNoUnsignedWrap()) 1642 return getAddRecExpr( 1643 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1644 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1645 1646 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1647 // Note that this serves two purposes: It filters out loops that are 1648 // simply not analyzable, and it covers the case where this code is 1649 // being called from within backedge-taken count analysis, such that 1650 // attempting to ask for the backedge-taken count would likely result 1651 // in infinite recursion. In the later case, the analysis code will 1652 // cope with a conservative value, and it will take care to purge 1653 // that value once it has finished. 1654 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1655 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1656 // Manually compute the final value for AR, checking for overflow. 1657 1658 // Check whether the backedge-taken count can be losslessly casted to 1659 // the addrec's type. The count is always unsigned. 1660 const SCEV *CastedMaxBECount = 1661 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1662 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1663 CastedMaxBECount, MaxBECount->getType(), Depth); 1664 if (MaxBECount == RecastedMaxBECount) { 1665 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1666 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1667 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1668 SCEV::FlagAnyWrap, Depth + 1); 1669 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1670 SCEV::FlagAnyWrap, 1671 Depth + 1), 1672 WideTy, Depth + 1); 1673 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1674 const SCEV *WideMaxBECount = 1675 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1676 const SCEV *OperandExtendedAdd = 1677 getAddExpr(WideStart, 1678 getMulExpr(WideMaxBECount, 1679 getZeroExtendExpr(Step, WideTy, Depth + 1), 1680 SCEV::FlagAnyWrap, Depth + 1), 1681 SCEV::FlagAnyWrap, Depth + 1); 1682 if (ZAdd == OperandExtendedAdd) { 1683 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1684 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1685 // Return the expression with the addrec on the outside. 1686 return getAddRecExpr( 1687 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1688 Depth + 1), 1689 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1690 AR->getNoWrapFlags()); 1691 } 1692 // Similar to above, only this time treat the step value as signed. 1693 // This covers loops that count down. 1694 OperandExtendedAdd = 1695 getAddExpr(WideStart, 1696 getMulExpr(WideMaxBECount, 1697 getSignExtendExpr(Step, WideTy, Depth + 1), 1698 SCEV::FlagAnyWrap, Depth + 1), 1699 SCEV::FlagAnyWrap, Depth + 1); 1700 if (ZAdd == OperandExtendedAdd) { 1701 // Cache knowledge of AR NW, which is propagated to this AddRec. 1702 // Negative step causes unsigned wrap, but it still can't self-wrap. 1703 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1704 // Return the expression with the addrec on the outside. 1705 return getAddRecExpr( 1706 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1707 Depth + 1), 1708 getSignExtendExpr(Step, Ty, Depth + 1), L, 1709 AR->getNoWrapFlags()); 1710 } 1711 } 1712 } 1713 1714 // Normally, in the cases we can prove no-overflow via a 1715 // backedge guarding condition, we can also compute a backedge 1716 // taken count for the loop. The exceptions are assumptions and 1717 // guards present in the loop -- SCEV is not great at exploiting 1718 // these to compute max backedge taken counts, but can still use 1719 // these to prove lack of overflow. Use this fact to avoid 1720 // doing extra work that may not pay off. 1721 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1722 !AC.assumptions().empty()) { 1723 1724 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1725 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1726 if (AR->hasNoUnsignedWrap()) { 1727 // Same as nuw case above - duplicated here to avoid a compile time 1728 // issue. It's not clear that the order of checks does matter, but 1729 // it's one of two issue possible causes for a change which was 1730 // reverted. Be conservative for the moment. 1731 return getAddRecExpr( 1732 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1733 Depth + 1), 1734 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1735 AR->getNoWrapFlags()); 1736 } 1737 1738 // For a negative step, we can extend the operands iff doing so only 1739 // traverses values in the range zext([0,UINT_MAX]). 1740 if (isKnownNegative(Step)) { 1741 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1742 getSignedRangeMin(Step)); 1743 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1744 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1745 // Cache knowledge of AR NW, which is propagated to this 1746 // AddRec. Negative step causes unsigned wrap, but it 1747 // still can't self-wrap. 1748 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1749 // Return the expression with the addrec on the outside. 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1752 Depth + 1), 1753 getSignExtendExpr(Step, Ty, Depth + 1), L, 1754 AR->getNoWrapFlags()); 1755 } 1756 } 1757 } 1758 1759 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1760 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1761 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1762 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1763 const APInt &C = SC->getAPInt(); 1764 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1765 if (D != 0) { 1766 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1767 const SCEV *SResidual = 1768 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1769 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1770 return getAddExpr(SZExtD, SZExtR, 1771 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1772 Depth + 1); 1773 } 1774 } 1775 1776 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1777 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1778 return getAddRecExpr( 1779 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1780 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1781 } 1782 } 1783 1784 // zext(A % B) --> zext(A) % zext(B) 1785 { 1786 const SCEV *LHS; 1787 const SCEV *RHS; 1788 if (matchURem(Op, LHS, RHS)) 1789 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1790 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1791 } 1792 1793 // zext(A / B) --> zext(A) / zext(B). 1794 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1795 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1796 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1797 1798 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1799 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1800 if (SA->hasNoUnsignedWrap()) { 1801 // If the addition does not unsign overflow then we can, by definition, 1802 // commute the zero extension with the addition operation. 1803 SmallVector<const SCEV *, 4> Ops; 1804 for (const auto *Op : SA->operands()) 1805 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1806 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1807 } 1808 1809 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1810 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1811 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1812 // 1813 // Often address arithmetics contain expressions like 1814 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1815 // This transformation is useful while proving that such expressions are 1816 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1817 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1818 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1819 if (D != 0) { 1820 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1821 const SCEV *SResidual = 1822 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1823 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1824 return getAddExpr(SZExtD, SZExtR, 1825 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1826 Depth + 1); 1827 } 1828 } 1829 } 1830 1831 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1832 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1833 if (SM->hasNoUnsignedWrap()) { 1834 // If the multiply does not unsign overflow then we can, by definition, 1835 // commute the zero extension with the multiply operation. 1836 SmallVector<const SCEV *, 4> Ops; 1837 for (const auto *Op : SM->operands()) 1838 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1839 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1840 } 1841 1842 // zext(2^K * (trunc X to iN)) to iM -> 1843 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1844 // 1845 // Proof: 1846 // 1847 // zext(2^K * (trunc X to iN)) to iM 1848 // = zext((trunc X to iN) << K) to iM 1849 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1850 // (because shl removes the top K bits) 1851 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1852 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1853 // 1854 if (SM->getNumOperands() == 2) 1855 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1856 if (MulLHS->getAPInt().isPowerOf2()) 1857 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1858 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1859 MulLHS->getAPInt().logBase2(); 1860 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1861 return getMulExpr( 1862 getZeroExtendExpr(MulLHS, Ty), 1863 getZeroExtendExpr( 1864 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1865 SCEV::FlagNUW, Depth + 1); 1866 } 1867 } 1868 1869 // The cast wasn't folded; create an explicit cast node. 1870 // Recompute the insert position, as it may have been invalidated. 1871 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1872 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1873 Op, Ty); 1874 UniqueSCEVs.InsertNode(S, IP); 1875 addToLoopUseLists(S); 1876 return S; 1877 } 1878 1879 const SCEV * 1880 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1881 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1882 "This is not an extending conversion!"); 1883 assert(isSCEVable(Ty) && 1884 "This is not a conversion to a SCEVable type!"); 1885 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1886 Ty = getEffectiveSCEVType(Ty); 1887 1888 // Fold if the operand is constant. 1889 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1890 return getConstant( 1891 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1892 1893 // sext(sext(x)) --> sext(x) 1894 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1895 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1896 1897 // sext(zext(x)) --> zext(x) 1898 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1899 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1900 1901 // Before doing any expensive analysis, check to see if we've already 1902 // computed a SCEV for this Op and Ty. 1903 FoldingSetNodeID ID; 1904 ID.AddInteger(scSignExtend); 1905 ID.AddPointer(Op); 1906 ID.AddPointer(Ty); 1907 void *IP = nullptr; 1908 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1909 // Limit recursion depth. 1910 if (Depth > MaxCastDepth) { 1911 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1912 Op, Ty); 1913 UniqueSCEVs.InsertNode(S, IP); 1914 addToLoopUseLists(S); 1915 return S; 1916 } 1917 1918 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1919 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1920 // It's possible the bits taken off by the truncate were all sign bits. If 1921 // so, we should be able to simplify this further. 1922 const SCEV *X = ST->getOperand(); 1923 ConstantRange CR = getSignedRange(X); 1924 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1925 unsigned NewBits = getTypeSizeInBits(Ty); 1926 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1927 CR.sextOrTrunc(NewBits))) 1928 return getTruncateOrSignExtend(X, Ty, Depth); 1929 } 1930 1931 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1932 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1933 if (SA->hasNoSignedWrap()) { 1934 // If the addition does not sign overflow then we can, by definition, 1935 // commute the sign extension with the addition operation. 1936 SmallVector<const SCEV *, 4> Ops; 1937 for (const auto *Op : SA->operands()) 1938 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1939 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1940 } 1941 1942 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1943 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1944 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1945 // 1946 // For instance, this will bring two seemingly different expressions: 1947 // 1 + sext(5 + 20 * %x + 24 * %y) and 1948 // sext(6 + 20 * %x + 24 * %y) 1949 // to the same form: 1950 // 2 + sext(4 + 20 * %x + 24 * %y) 1951 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1952 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1953 if (D != 0) { 1954 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1955 const SCEV *SResidual = 1956 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1957 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1958 return getAddExpr(SSExtD, SSExtR, 1959 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1960 Depth + 1); 1961 } 1962 } 1963 } 1964 // If the input value is a chrec scev, and we can prove that the value 1965 // did not overflow the old, smaller, value, we can sign extend all of the 1966 // operands (often constants). This allows analysis of something like 1967 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1968 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1969 if (AR->isAffine()) { 1970 const SCEV *Start = AR->getStart(); 1971 const SCEV *Step = AR->getStepRecurrence(*this); 1972 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1973 const Loop *L = AR->getLoop(); 1974 1975 if (!AR->hasNoSignedWrap()) { 1976 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1977 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1978 } 1979 1980 // If we have special knowledge that this addrec won't overflow, 1981 // we don't need to do any further analysis. 1982 if (AR->hasNoSignedWrap()) 1983 return getAddRecExpr( 1984 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1985 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1986 1987 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1988 // Note that this serves two purposes: It filters out loops that are 1989 // simply not analyzable, and it covers the case where this code is 1990 // being called from within backedge-taken count analysis, such that 1991 // attempting to ask for the backedge-taken count would likely result 1992 // in infinite recursion. In the later case, the analysis code will 1993 // cope with a conservative value, and it will take care to purge 1994 // that value once it has finished. 1995 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1996 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1997 // Manually compute the final value for AR, checking for 1998 // overflow. 1999 2000 // Check whether the backedge-taken count can be losslessly casted to 2001 // the addrec's type. The count is always unsigned. 2002 const SCEV *CastedMaxBECount = 2003 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2004 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2005 CastedMaxBECount, MaxBECount->getType(), Depth); 2006 if (MaxBECount == RecastedMaxBECount) { 2007 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2008 // Check whether Start+Step*MaxBECount has no signed overflow. 2009 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2010 SCEV::FlagAnyWrap, Depth + 1); 2011 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2012 SCEV::FlagAnyWrap, 2013 Depth + 1), 2014 WideTy, Depth + 1); 2015 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2016 const SCEV *WideMaxBECount = 2017 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2018 const SCEV *OperandExtendedAdd = 2019 getAddExpr(WideStart, 2020 getMulExpr(WideMaxBECount, 2021 getSignExtendExpr(Step, WideTy, Depth + 1), 2022 SCEV::FlagAnyWrap, Depth + 1), 2023 SCEV::FlagAnyWrap, Depth + 1); 2024 if (SAdd == OperandExtendedAdd) { 2025 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2026 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2027 // Return the expression with the addrec on the outside. 2028 return getAddRecExpr( 2029 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2030 Depth + 1), 2031 getSignExtendExpr(Step, Ty, Depth + 1), L, 2032 AR->getNoWrapFlags()); 2033 } 2034 // Similar to above, only this time treat the step value as unsigned. 2035 // This covers loops that count up with an unsigned step. 2036 OperandExtendedAdd = 2037 getAddExpr(WideStart, 2038 getMulExpr(WideMaxBECount, 2039 getZeroExtendExpr(Step, WideTy, Depth + 1), 2040 SCEV::FlagAnyWrap, Depth + 1), 2041 SCEV::FlagAnyWrap, Depth + 1); 2042 if (SAdd == OperandExtendedAdd) { 2043 // If AR wraps around then 2044 // 2045 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2046 // => SAdd != OperandExtendedAdd 2047 // 2048 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2049 // (SAdd == OperandExtendedAdd => AR is NW) 2050 2051 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2052 2053 // Return the expression with the addrec on the outside. 2054 return getAddRecExpr( 2055 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2056 Depth + 1), 2057 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2058 AR->getNoWrapFlags()); 2059 } 2060 } 2061 } 2062 2063 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2064 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2065 if (AR->hasNoSignedWrap()) { 2066 // Same as nsw case above - duplicated here to avoid a compile time 2067 // issue. It's not clear that the order of checks does matter, but 2068 // it's one of two issue possible causes for a change which was 2069 // reverted. Be conservative for the moment. 2070 return getAddRecExpr( 2071 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2072 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2073 } 2074 2075 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2076 // if D + (C - D + Step * n) could be proven to not signed wrap 2077 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2078 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2079 const APInt &C = SC->getAPInt(); 2080 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2081 if (D != 0) { 2082 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2083 const SCEV *SResidual = 2084 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2085 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2086 return getAddExpr(SSExtD, SSExtR, 2087 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2088 Depth + 1); 2089 } 2090 } 2091 2092 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2093 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2094 return getAddRecExpr( 2095 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2096 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2097 } 2098 } 2099 2100 // If the input value is provably positive and we could not simplify 2101 // away the sext build a zext instead. 2102 if (isKnownNonNegative(Op)) 2103 return getZeroExtendExpr(Op, Ty, Depth + 1); 2104 2105 // The cast wasn't folded; create an explicit cast node. 2106 // Recompute the insert position, as it may have been invalidated. 2107 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2108 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2109 Op, Ty); 2110 UniqueSCEVs.InsertNode(S, IP); 2111 addToLoopUseLists(S); 2112 return S; 2113 } 2114 2115 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2116 /// unspecified bits out to the given type. 2117 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2118 Type *Ty) { 2119 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2120 "This is not an extending conversion!"); 2121 assert(isSCEVable(Ty) && 2122 "This is not a conversion to a SCEVable type!"); 2123 Ty = getEffectiveSCEVType(Ty); 2124 2125 // Sign-extend negative constants. 2126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2127 if (SC->getAPInt().isNegative()) 2128 return getSignExtendExpr(Op, Ty); 2129 2130 // Peel off a truncate cast. 2131 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2132 const SCEV *NewOp = T->getOperand(); 2133 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2134 return getAnyExtendExpr(NewOp, Ty); 2135 return getTruncateOrNoop(NewOp, Ty); 2136 } 2137 2138 // Next try a zext cast. If the cast is folded, use it. 2139 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2140 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2141 return ZExt; 2142 2143 // Next try a sext cast. If the cast is folded, use it. 2144 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2145 if (!isa<SCEVSignExtendExpr>(SExt)) 2146 return SExt; 2147 2148 // Force the cast to be folded into the operands of an addrec. 2149 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2150 SmallVector<const SCEV *, 4> Ops; 2151 for (const SCEV *Op : AR->operands()) 2152 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2153 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2154 } 2155 2156 // If the expression is obviously signed, use the sext cast value. 2157 if (isa<SCEVSMaxExpr>(Op)) 2158 return SExt; 2159 2160 // Absent any other information, use the zext cast value. 2161 return ZExt; 2162 } 2163 2164 /// Process the given Ops list, which is a list of operands to be added under 2165 /// the given scale, update the given map. This is a helper function for 2166 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2167 /// that would form an add expression like this: 2168 /// 2169 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2170 /// 2171 /// where A and B are constants, update the map with these values: 2172 /// 2173 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2174 /// 2175 /// and add 13 + A*B*29 to AccumulatedConstant. 2176 /// This will allow getAddRecExpr to produce this: 2177 /// 2178 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2179 /// 2180 /// This form often exposes folding opportunities that are hidden in 2181 /// the original operand list. 2182 /// 2183 /// Return true iff it appears that any interesting folding opportunities 2184 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2185 /// the common case where no interesting opportunities are present, and 2186 /// is also used as a check to avoid infinite recursion. 2187 static bool 2188 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2189 SmallVectorImpl<const SCEV *> &NewOps, 2190 APInt &AccumulatedConstant, 2191 const SCEV *const *Ops, size_t NumOperands, 2192 const APInt &Scale, 2193 ScalarEvolution &SE) { 2194 bool Interesting = false; 2195 2196 // Iterate over the add operands. They are sorted, with constants first. 2197 unsigned i = 0; 2198 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2199 ++i; 2200 // Pull a buried constant out to the outside. 2201 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2202 Interesting = true; 2203 AccumulatedConstant += Scale * C->getAPInt(); 2204 } 2205 2206 // Next comes everything else. We're especially interested in multiplies 2207 // here, but they're in the middle, so just visit the rest with one loop. 2208 for (; i != NumOperands; ++i) { 2209 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2210 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2211 APInt NewScale = 2212 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2213 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2214 // A multiplication of a constant with another add; recurse. 2215 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2216 Interesting |= 2217 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2218 Add->op_begin(), Add->getNumOperands(), 2219 NewScale, SE); 2220 } else { 2221 // A multiplication of a constant with some other value. Update 2222 // the map. 2223 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2224 const SCEV *Key = SE.getMulExpr(MulOps); 2225 auto Pair = M.insert({Key, NewScale}); 2226 if (Pair.second) { 2227 NewOps.push_back(Pair.first->first); 2228 } else { 2229 Pair.first->second += NewScale; 2230 // The map already had an entry for this value, which may indicate 2231 // a folding opportunity. 2232 Interesting = true; 2233 } 2234 } 2235 } else { 2236 // An ordinary operand. Update the map. 2237 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2238 M.insert({Ops[i], Scale}); 2239 if (Pair.second) { 2240 NewOps.push_back(Pair.first->first); 2241 } else { 2242 Pair.first->second += Scale; 2243 // The map already had an entry for this value, which may indicate 2244 // a folding opportunity. 2245 Interesting = true; 2246 } 2247 } 2248 } 2249 2250 return Interesting; 2251 } 2252 2253 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2254 const SCEV *LHS, const SCEV *RHS) { 2255 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2256 SCEV::NoWrapFlags, unsigned); 2257 switch (BinOp) { 2258 default: 2259 llvm_unreachable("Unsupported binary op"); 2260 case Instruction::Add: 2261 Operation = &ScalarEvolution::getAddExpr; 2262 break; 2263 case Instruction::Sub: 2264 Operation = &ScalarEvolution::getMinusSCEV; 2265 break; 2266 case Instruction::Mul: 2267 Operation = &ScalarEvolution::getMulExpr; 2268 break; 2269 } 2270 2271 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2272 Signed ? &ScalarEvolution::getSignExtendExpr 2273 : &ScalarEvolution::getZeroExtendExpr; 2274 2275 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2276 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2277 auto *WideTy = 2278 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2279 2280 const SCEV *A = (this->*Extension)( 2281 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2282 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2283 (this->*Extension)(RHS, WideTy, 0), 2284 SCEV::FlagAnyWrap, 0); 2285 return A == B; 2286 } 2287 2288 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2289 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2290 const OverflowingBinaryOperator *OBO) { 2291 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2292 2293 if (OBO->hasNoUnsignedWrap()) 2294 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2295 if (OBO->hasNoSignedWrap()) 2296 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2297 2298 bool Deduced = false; 2299 2300 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2301 return {Flags, Deduced}; 2302 2303 if (OBO->getOpcode() != Instruction::Add && 2304 OBO->getOpcode() != Instruction::Sub && 2305 OBO->getOpcode() != Instruction::Mul) 2306 return {Flags, Deduced}; 2307 2308 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2309 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2310 2311 if (!OBO->hasNoUnsignedWrap() && 2312 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2313 /* Signed */ false, LHS, RHS)) { 2314 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2315 Deduced = true; 2316 } 2317 2318 if (!OBO->hasNoSignedWrap() && 2319 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2320 /* Signed */ true, LHS, RHS)) { 2321 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2322 Deduced = true; 2323 } 2324 2325 return {Flags, Deduced}; 2326 } 2327 2328 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2329 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2330 // can't-overflow flags for the operation if possible. 2331 static SCEV::NoWrapFlags 2332 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2333 const ArrayRef<const SCEV *> Ops, 2334 SCEV::NoWrapFlags Flags) { 2335 using namespace std::placeholders; 2336 2337 using OBO = OverflowingBinaryOperator; 2338 2339 bool CanAnalyze = 2340 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2341 (void)CanAnalyze; 2342 assert(CanAnalyze && "don't call from other places!"); 2343 2344 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2345 SCEV::NoWrapFlags SignOrUnsignWrap = 2346 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2347 2348 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2349 auto IsKnownNonNegative = [&](const SCEV *S) { 2350 return SE->isKnownNonNegative(S); 2351 }; 2352 2353 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2354 Flags = 2355 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2356 2357 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2358 2359 if (SignOrUnsignWrap != SignOrUnsignMask && 2360 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2361 isa<SCEVConstant>(Ops[0])) { 2362 2363 auto Opcode = [&] { 2364 switch (Type) { 2365 case scAddExpr: 2366 return Instruction::Add; 2367 case scMulExpr: 2368 return Instruction::Mul; 2369 default: 2370 llvm_unreachable("Unexpected SCEV op."); 2371 } 2372 }(); 2373 2374 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2375 2376 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2377 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2378 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2379 Opcode, C, OBO::NoSignedWrap); 2380 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2381 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2382 } 2383 2384 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2385 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2386 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2387 Opcode, C, OBO::NoUnsignedWrap); 2388 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2389 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2390 } 2391 } 2392 2393 // <0,+,nonnegative><nw> is also nuw 2394 // TODO: Add corresponding nsw case 2395 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2396 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2397 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2398 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2399 2400 return Flags; 2401 } 2402 2403 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2404 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2405 } 2406 2407 /// Get a canonical add expression, or something simpler if possible. 2408 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2409 SCEV::NoWrapFlags OrigFlags, 2410 unsigned Depth) { 2411 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2412 "only nuw or nsw allowed"); 2413 assert(!Ops.empty() && "Cannot get empty add!"); 2414 if (Ops.size() == 1) return Ops[0]; 2415 #ifndef NDEBUG 2416 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2417 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2418 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2419 "SCEVAddExpr operand types don't match!"); 2420 unsigned NumPtrs = count_if( 2421 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2422 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2423 #endif 2424 2425 // Sort by complexity, this groups all similar expression types together. 2426 GroupByComplexity(Ops, &LI, DT); 2427 2428 // If there are any constants, fold them together. 2429 unsigned Idx = 0; 2430 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2431 ++Idx; 2432 assert(Idx < Ops.size()); 2433 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2434 // We found two constants, fold them together! 2435 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2436 if (Ops.size() == 2) return Ops[0]; 2437 Ops.erase(Ops.begin()+1); // Erase the folded element 2438 LHSC = cast<SCEVConstant>(Ops[0]); 2439 } 2440 2441 // If we are left with a constant zero being added, strip it off. 2442 if (LHSC->getValue()->isZero()) { 2443 Ops.erase(Ops.begin()); 2444 --Idx; 2445 } 2446 2447 if (Ops.size() == 1) return Ops[0]; 2448 } 2449 2450 // Delay expensive flag strengthening until necessary. 2451 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2452 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2453 }; 2454 2455 // Limit recursion calls depth. 2456 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2457 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2458 2459 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2460 // Don't strengthen flags if we have no new information. 2461 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2462 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2463 Add->setNoWrapFlags(ComputeFlags(Ops)); 2464 return S; 2465 } 2466 2467 // Okay, check to see if the same value occurs in the operand list more than 2468 // once. If so, merge them together into an multiply expression. Since we 2469 // sorted the list, these values are required to be adjacent. 2470 Type *Ty = Ops[0]->getType(); 2471 bool FoundMatch = false; 2472 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2473 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2474 // Scan ahead to count how many equal operands there are. 2475 unsigned Count = 2; 2476 while (i+Count != e && Ops[i+Count] == Ops[i]) 2477 ++Count; 2478 // Merge the values into a multiply. 2479 const SCEV *Scale = getConstant(Ty, Count); 2480 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2481 if (Ops.size() == Count) 2482 return Mul; 2483 Ops[i] = Mul; 2484 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2485 --i; e -= Count - 1; 2486 FoundMatch = true; 2487 } 2488 if (FoundMatch) 2489 return getAddExpr(Ops, OrigFlags, Depth + 1); 2490 2491 // Check for truncates. If all the operands are truncated from the same 2492 // type, see if factoring out the truncate would permit the result to be 2493 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2494 // if the contents of the resulting outer trunc fold to something simple. 2495 auto FindTruncSrcType = [&]() -> Type * { 2496 // We're ultimately looking to fold an addrec of truncs and muls of only 2497 // constants and truncs, so if we find any other types of SCEV 2498 // as operands of the addrec then we bail and return nullptr here. 2499 // Otherwise, we return the type of the operand of a trunc that we find. 2500 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2501 return T->getOperand()->getType(); 2502 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2503 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2504 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2505 return T->getOperand()->getType(); 2506 } 2507 return nullptr; 2508 }; 2509 if (auto *SrcType = FindTruncSrcType()) { 2510 SmallVector<const SCEV *, 8> LargeOps; 2511 bool Ok = true; 2512 // Check all the operands to see if they can be represented in the 2513 // source type of the truncate. 2514 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2515 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2516 if (T->getOperand()->getType() != SrcType) { 2517 Ok = false; 2518 break; 2519 } 2520 LargeOps.push_back(T->getOperand()); 2521 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2522 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2523 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2524 SmallVector<const SCEV *, 8> LargeMulOps; 2525 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2526 if (const SCEVTruncateExpr *T = 2527 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2528 if (T->getOperand()->getType() != SrcType) { 2529 Ok = false; 2530 break; 2531 } 2532 LargeMulOps.push_back(T->getOperand()); 2533 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2534 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2535 } else { 2536 Ok = false; 2537 break; 2538 } 2539 } 2540 if (Ok) 2541 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2542 } else { 2543 Ok = false; 2544 break; 2545 } 2546 } 2547 if (Ok) { 2548 // Evaluate the expression in the larger type. 2549 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2550 // If it folds to something simple, use it. Otherwise, don't. 2551 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2552 return getTruncateExpr(Fold, Ty); 2553 } 2554 } 2555 2556 if (Ops.size() == 2) { 2557 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2558 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2559 // C1). 2560 const SCEV *A = Ops[0]; 2561 const SCEV *B = Ops[1]; 2562 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2563 auto *C = dyn_cast<SCEVConstant>(A); 2564 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2565 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2566 auto C2 = C->getAPInt(); 2567 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2568 2569 APInt ConstAdd = C1 + C2; 2570 auto AddFlags = AddExpr->getNoWrapFlags(); 2571 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2572 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2573 ConstAdd.ule(C1)) { 2574 PreservedFlags = 2575 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2576 } 2577 2578 // Adding a constant with the same sign and small magnitude is NSW, if the 2579 // original AddExpr was NSW. 2580 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2581 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2582 ConstAdd.abs().ule(C1.abs())) { 2583 PreservedFlags = 2584 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2585 } 2586 2587 if (PreservedFlags != SCEV::FlagAnyWrap) { 2588 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2589 NewOps[0] = getConstant(ConstAdd); 2590 return getAddExpr(NewOps, PreservedFlags); 2591 } 2592 } 2593 } 2594 2595 // Skip past any other cast SCEVs. 2596 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2597 ++Idx; 2598 2599 // If there are add operands they would be next. 2600 if (Idx < Ops.size()) { 2601 bool DeletedAdd = false; 2602 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2603 // common NUW flag for expression after inlining. Other flags cannot be 2604 // preserved, because they may depend on the original order of operations. 2605 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2606 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2607 if (Ops.size() > AddOpsInlineThreshold || 2608 Add->getNumOperands() > AddOpsInlineThreshold) 2609 break; 2610 // If we have an add, expand the add operands onto the end of the operands 2611 // list. 2612 Ops.erase(Ops.begin()+Idx); 2613 Ops.append(Add->op_begin(), Add->op_end()); 2614 DeletedAdd = true; 2615 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2616 } 2617 2618 // If we deleted at least one add, we added operands to the end of the list, 2619 // and they are not necessarily sorted. Recurse to resort and resimplify 2620 // any operands we just acquired. 2621 if (DeletedAdd) 2622 return getAddExpr(Ops, CommonFlags, Depth + 1); 2623 } 2624 2625 // Skip over the add expression until we get to a multiply. 2626 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2627 ++Idx; 2628 2629 // Check to see if there are any folding opportunities present with 2630 // operands multiplied by constant values. 2631 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2632 uint64_t BitWidth = getTypeSizeInBits(Ty); 2633 DenseMap<const SCEV *, APInt> M; 2634 SmallVector<const SCEV *, 8> NewOps; 2635 APInt AccumulatedConstant(BitWidth, 0); 2636 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2637 Ops.data(), Ops.size(), 2638 APInt(BitWidth, 1), *this)) { 2639 struct APIntCompare { 2640 bool operator()(const APInt &LHS, const APInt &RHS) const { 2641 return LHS.ult(RHS); 2642 } 2643 }; 2644 2645 // Some interesting folding opportunity is present, so its worthwhile to 2646 // re-generate the operands list. Group the operands by constant scale, 2647 // to avoid multiplying by the same constant scale multiple times. 2648 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2649 for (const SCEV *NewOp : NewOps) 2650 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2651 // Re-generate the operands list. 2652 Ops.clear(); 2653 if (AccumulatedConstant != 0) 2654 Ops.push_back(getConstant(AccumulatedConstant)); 2655 for (auto &MulOp : MulOpLists) { 2656 if (MulOp.first == 1) { 2657 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2658 } else if (MulOp.first != 0) { 2659 Ops.push_back(getMulExpr( 2660 getConstant(MulOp.first), 2661 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2662 SCEV::FlagAnyWrap, Depth + 1)); 2663 } 2664 } 2665 if (Ops.empty()) 2666 return getZero(Ty); 2667 if (Ops.size() == 1) 2668 return Ops[0]; 2669 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 } 2672 2673 // If we are adding something to a multiply expression, make sure the 2674 // something is not already an operand of the multiply. If so, merge it into 2675 // the multiply. 2676 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2677 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2678 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2679 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2680 if (isa<SCEVConstant>(MulOpSCEV)) 2681 continue; 2682 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2683 if (MulOpSCEV == Ops[AddOp]) { 2684 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2685 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2686 if (Mul->getNumOperands() != 2) { 2687 // If the multiply has more than two operands, we must get the 2688 // Y*Z term. 2689 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2690 Mul->op_begin()+MulOp); 2691 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2692 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2693 } 2694 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2695 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2696 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2697 SCEV::FlagAnyWrap, Depth + 1); 2698 if (Ops.size() == 2) return OuterMul; 2699 if (AddOp < Idx) { 2700 Ops.erase(Ops.begin()+AddOp); 2701 Ops.erase(Ops.begin()+Idx-1); 2702 } else { 2703 Ops.erase(Ops.begin()+Idx); 2704 Ops.erase(Ops.begin()+AddOp-1); 2705 } 2706 Ops.push_back(OuterMul); 2707 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2708 } 2709 2710 // Check this multiply against other multiplies being added together. 2711 for (unsigned OtherMulIdx = Idx+1; 2712 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2713 ++OtherMulIdx) { 2714 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2715 // If MulOp occurs in OtherMul, we can fold the two multiplies 2716 // together. 2717 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2718 OMulOp != e; ++OMulOp) 2719 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2720 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2721 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2722 if (Mul->getNumOperands() != 2) { 2723 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2724 Mul->op_begin()+MulOp); 2725 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2726 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2727 } 2728 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2729 if (OtherMul->getNumOperands() != 2) { 2730 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2731 OtherMul->op_begin()+OMulOp); 2732 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2733 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2734 } 2735 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2736 const SCEV *InnerMulSum = 2737 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2738 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2739 SCEV::FlagAnyWrap, Depth + 1); 2740 if (Ops.size() == 2) return OuterMul; 2741 Ops.erase(Ops.begin()+Idx); 2742 Ops.erase(Ops.begin()+OtherMulIdx-1); 2743 Ops.push_back(OuterMul); 2744 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2745 } 2746 } 2747 } 2748 } 2749 2750 // If there are any add recurrences in the operands list, see if any other 2751 // added values are loop invariant. If so, we can fold them into the 2752 // recurrence. 2753 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2754 ++Idx; 2755 2756 // Scan over all recurrences, trying to fold loop invariants into them. 2757 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2758 // Scan all of the other operands to this add and add them to the vector if 2759 // they are loop invariant w.r.t. the recurrence. 2760 SmallVector<const SCEV *, 8> LIOps; 2761 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2762 const Loop *AddRecLoop = AddRec->getLoop(); 2763 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2764 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2765 LIOps.push_back(Ops[i]); 2766 Ops.erase(Ops.begin()+i); 2767 --i; --e; 2768 } 2769 2770 // If we found some loop invariants, fold them into the recurrence. 2771 if (!LIOps.empty()) { 2772 // Compute nowrap flags for the addition of the loop-invariant ops and 2773 // the addrec. Temporarily push it as an operand for that purpose. 2774 LIOps.push_back(AddRec); 2775 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2776 LIOps.pop_back(); 2777 2778 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2779 LIOps.push_back(AddRec->getStart()); 2780 2781 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2782 // This follows from the fact that the no-wrap flags on the outer add 2783 // expression are applicable on the 0th iteration, when the add recurrence 2784 // will be equal to its start value. 2785 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2786 2787 // Build the new addrec. Propagate the NUW and NSW flags if both the 2788 // outer add and the inner addrec are guaranteed to have no overflow. 2789 // Always propagate NW. 2790 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2791 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2792 2793 // If all of the other operands were loop invariant, we are done. 2794 if (Ops.size() == 1) return NewRec; 2795 2796 // Otherwise, add the folded AddRec by the non-invariant parts. 2797 for (unsigned i = 0;; ++i) 2798 if (Ops[i] == AddRec) { 2799 Ops[i] = NewRec; 2800 break; 2801 } 2802 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2803 } 2804 2805 // Okay, if there weren't any loop invariants to be folded, check to see if 2806 // there are multiple AddRec's with the same loop induction variable being 2807 // added together. If so, we can fold them. 2808 for (unsigned OtherIdx = Idx+1; 2809 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2810 ++OtherIdx) { 2811 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2812 // so that the 1st found AddRecExpr is dominated by all others. 2813 assert(DT.dominates( 2814 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2815 AddRec->getLoop()->getHeader()) && 2816 "AddRecExprs are not sorted in reverse dominance order?"); 2817 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2818 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2819 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2820 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2821 ++OtherIdx) { 2822 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2823 if (OtherAddRec->getLoop() == AddRecLoop) { 2824 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2825 i != e; ++i) { 2826 if (i >= AddRecOps.size()) { 2827 AddRecOps.append(OtherAddRec->op_begin()+i, 2828 OtherAddRec->op_end()); 2829 break; 2830 } 2831 SmallVector<const SCEV *, 2> TwoOps = { 2832 AddRecOps[i], OtherAddRec->getOperand(i)}; 2833 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2834 } 2835 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2836 } 2837 } 2838 // Step size has changed, so we cannot guarantee no self-wraparound. 2839 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2840 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2841 } 2842 } 2843 2844 // Otherwise couldn't fold anything into this recurrence. Move onto the 2845 // next one. 2846 } 2847 2848 // Okay, it looks like we really DO need an add expr. Check to see if we 2849 // already have one, otherwise create a new one. 2850 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2851 } 2852 2853 const SCEV * 2854 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2855 SCEV::NoWrapFlags Flags) { 2856 FoldingSetNodeID ID; 2857 ID.AddInteger(scAddExpr); 2858 for (const SCEV *Op : Ops) 2859 ID.AddPointer(Op); 2860 void *IP = nullptr; 2861 SCEVAddExpr *S = 2862 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2863 if (!S) { 2864 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2865 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2866 S = new (SCEVAllocator) 2867 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2868 UniqueSCEVs.InsertNode(S, IP); 2869 addToLoopUseLists(S); 2870 } 2871 S->setNoWrapFlags(Flags); 2872 return S; 2873 } 2874 2875 const SCEV * 2876 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2877 const Loop *L, SCEV::NoWrapFlags Flags) { 2878 FoldingSetNodeID ID; 2879 ID.AddInteger(scAddRecExpr); 2880 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2881 ID.AddPointer(Ops[i]); 2882 ID.AddPointer(L); 2883 void *IP = nullptr; 2884 SCEVAddRecExpr *S = 2885 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2886 if (!S) { 2887 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2888 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2889 S = new (SCEVAllocator) 2890 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2891 UniqueSCEVs.InsertNode(S, IP); 2892 addToLoopUseLists(S); 2893 } 2894 setNoWrapFlags(S, Flags); 2895 return S; 2896 } 2897 2898 const SCEV * 2899 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2900 SCEV::NoWrapFlags Flags) { 2901 FoldingSetNodeID ID; 2902 ID.AddInteger(scMulExpr); 2903 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2904 ID.AddPointer(Ops[i]); 2905 void *IP = nullptr; 2906 SCEVMulExpr *S = 2907 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2908 if (!S) { 2909 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2910 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2911 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2912 O, Ops.size()); 2913 UniqueSCEVs.InsertNode(S, IP); 2914 addToLoopUseLists(S); 2915 } 2916 S->setNoWrapFlags(Flags); 2917 return S; 2918 } 2919 2920 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2921 uint64_t k = i*j; 2922 if (j > 1 && k / j != i) Overflow = true; 2923 return k; 2924 } 2925 2926 /// Compute the result of "n choose k", the binomial coefficient. If an 2927 /// intermediate computation overflows, Overflow will be set and the return will 2928 /// be garbage. Overflow is not cleared on absence of overflow. 2929 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2930 // We use the multiplicative formula: 2931 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2932 // At each iteration, we take the n-th term of the numeral and divide by the 2933 // (k-n)th term of the denominator. This division will always produce an 2934 // integral result, and helps reduce the chance of overflow in the 2935 // intermediate computations. However, we can still overflow even when the 2936 // final result would fit. 2937 2938 if (n == 0 || n == k) return 1; 2939 if (k > n) return 0; 2940 2941 if (k > n/2) 2942 k = n-k; 2943 2944 uint64_t r = 1; 2945 for (uint64_t i = 1; i <= k; ++i) { 2946 r = umul_ov(r, n-(i-1), Overflow); 2947 r /= i; 2948 } 2949 return r; 2950 } 2951 2952 /// Determine if any of the operands in this SCEV are a constant or if 2953 /// any of the add or multiply expressions in this SCEV contain a constant. 2954 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2955 struct FindConstantInAddMulChain { 2956 bool FoundConstant = false; 2957 2958 bool follow(const SCEV *S) { 2959 FoundConstant |= isa<SCEVConstant>(S); 2960 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2961 } 2962 2963 bool isDone() const { 2964 return FoundConstant; 2965 } 2966 }; 2967 2968 FindConstantInAddMulChain F; 2969 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2970 ST.visitAll(StartExpr); 2971 return F.FoundConstant; 2972 } 2973 2974 /// Get a canonical multiply expression, or something simpler if possible. 2975 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2976 SCEV::NoWrapFlags OrigFlags, 2977 unsigned Depth) { 2978 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2979 "only nuw or nsw allowed"); 2980 assert(!Ops.empty() && "Cannot get empty mul!"); 2981 if (Ops.size() == 1) return Ops[0]; 2982 #ifndef NDEBUG 2983 Type *ETy = Ops[0]->getType(); 2984 assert(!ETy->isPointerTy()); 2985 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2986 assert(Ops[i]->getType() == ETy && 2987 "SCEVMulExpr operand types don't match!"); 2988 #endif 2989 2990 // Sort by complexity, this groups all similar expression types together. 2991 GroupByComplexity(Ops, &LI, DT); 2992 2993 // If there are any constants, fold them together. 2994 unsigned Idx = 0; 2995 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2996 ++Idx; 2997 assert(Idx < Ops.size()); 2998 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2999 // We found two constants, fold them together! 3000 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3001 if (Ops.size() == 2) return Ops[0]; 3002 Ops.erase(Ops.begin()+1); // Erase the folded element 3003 LHSC = cast<SCEVConstant>(Ops[0]); 3004 } 3005 3006 // If we have a multiply of zero, it will always be zero. 3007 if (LHSC->getValue()->isZero()) 3008 return LHSC; 3009 3010 // If we are left with a constant one being multiplied, strip it off. 3011 if (LHSC->getValue()->isOne()) { 3012 Ops.erase(Ops.begin()); 3013 --Idx; 3014 } 3015 3016 if (Ops.size() == 1) 3017 return Ops[0]; 3018 } 3019 3020 // Delay expensive flag strengthening until necessary. 3021 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3022 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3023 }; 3024 3025 // Limit recursion calls depth. 3026 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3027 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3028 3029 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3030 // Don't strengthen flags if we have no new information. 3031 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3032 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3033 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3034 return S; 3035 } 3036 3037 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3038 if (Ops.size() == 2) { 3039 // C1*(C2+V) -> C1*C2 + C1*V 3040 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3041 // If any of Add's ops are Adds or Muls with a constant, apply this 3042 // transformation as well. 3043 // 3044 // TODO: There are some cases where this transformation is not 3045 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3046 // this transformation should be narrowed down. 3047 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3048 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3049 SCEV::FlagAnyWrap, Depth + 1), 3050 getMulExpr(LHSC, Add->getOperand(1), 3051 SCEV::FlagAnyWrap, Depth + 1), 3052 SCEV::FlagAnyWrap, Depth + 1); 3053 3054 if (Ops[0]->isAllOnesValue()) { 3055 // If we have a mul by -1 of an add, try distributing the -1 among the 3056 // add operands. 3057 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3058 SmallVector<const SCEV *, 4> NewOps; 3059 bool AnyFolded = false; 3060 for (const SCEV *AddOp : Add->operands()) { 3061 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3062 Depth + 1); 3063 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3064 NewOps.push_back(Mul); 3065 } 3066 if (AnyFolded) 3067 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3068 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3069 // Negation preserves a recurrence's no self-wrap property. 3070 SmallVector<const SCEV *, 4> Operands; 3071 for (const SCEV *AddRecOp : AddRec->operands()) 3072 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3073 Depth + 1)); 3074 3075 return getAddRecExpr(Operands, AddRec->getLoop(), 3076 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3077 } 3078 } 3079 } 3080 } 3081 3082 // Skip over the add expression until we get to a multiply. 3083 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3084 ++Idx; 3085 3086 // If there are mul operands inline them all into this expression. 3087 if (Idx < Ops.size()) { 3088 bool DeletedMul = false; 3089 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3090 if (Ops.size() > MulOpsInlineThreshold) 3091 break; 3092 // If we have an mul, expand the mul operands onto the end of the 3093 // operands list. 3094 Ops.erase(Ops.begin()+Idx); 3095 Ops.append(Mul->op_begin(), Mul->op_end()); 3096 DeletedMul = true; 3097 } 3098 3099 // If we deleted at least one mul, we added operands to the end of the 3100 // list, and they are not necessarily sorted. Recurse to resort and 3101 // resimplify any operands we just acquired. 3102 if (DeletedMul) 3103 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3104 } 3105 3106 // If there are any add recurrences in the operands list, see if any other 3107 // added values are loop invariant. If so, we can fold them into the 3108 // recurrence. 3109 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3110 ++Idx; 3111 3112 // Scan over all recurrences, trying to fold loop invariants into them. 3113 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3114 // Scan all of the other operands to this mul and add them to the vector 3115 // if they are loop invariant w.r.t. the recurrence. 3116 SmallVector<const SCEV *, 8> LIOps; 3117 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3118 const Loop *AddRecLoop = AddRec->getLoop(); 3119 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3120 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3121 LIOps.push_back(Ops[i]); 3122 Ops.erase(Ops.begin()+i); 3123 --i; --e; 3124 } 3125 3126 // If we found some loop invariants, fold them into the recurrence. 3127 if (!LIOps.empty()) { 3128 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3129 SmallVector<const SCEV *, 4> NewOps; 3130 NewOps.reserve(AddRec->getNumOperands()); 3131 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3132 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3133 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3134 SCEV::FlagAnyWrap, Depth + 1)); 3135 3136 // Build the new addrec. Propagate the NUW and NSW flags if both the 3137 // outer mul and the inner addrec are guaranteed to have no overflow. 3138 // 3139 // No self-wrap cannot be guaranteed after changing the step size, but 3140 // will be inferred if either NUW or NSW is true. 3141 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3142 const SCEV *NewRec = getAddRecExpr( 3143 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3144 3145 // If all of the other operands were loop invariant, we are done. 3146 if (Ops.size() == 1) return NewRec; 3147 3148 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3149 for (unsigned i = 0;; ++i) 3150 if (Ops[i] == AddRec) { 3151 Ops[i] = NewRec; 3152 break; 3153 } 3154 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3155 } 3156 3157 // Okay, if there weren't any loop invariants to be folded, check to see 3158 // if there are multiple AddRec's with the same loop induction variable 3159 // being multiplied together. If so, we can fold them. 3160 3161 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3162 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3163 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3164 // ]]],+,...up to x=2n}. 3165 // Note that the arguments to choose() are always integers with values 3166 // known at compile time, never SCEV objects. 3167 // 3168 // The implementation avoids pointless extra computations when the two 3169 // addrec's are of different length (mathematically, it's equivalent to 3170 // an infinite stream of zeros on the right). 3171 bool OpsModified = false; 3172 for (unsigned OtherIdx = Idx+1; 3173 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3174 ++OtherIdx) { 3175 const SCEVAddRecExpr *OtherAddRec = 3176 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3177 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3178 continue; 3179 3180 // Limit max number of arguments to avoid creation of unreasonably big 3181 // SCEVAddRecs with very complex operands. 3182 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3183 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3184 continue; 3185 3186 bool Overflow = false; 3187 Type *Ty = AddRec->getType(); 3188 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3189 SmallVector<const SCEV*, 7> AddRecOps; 3190 for (int x = 0, xe = AddRec->getNumOperands() + 3191 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3192 SmallVector <const SCEV *, 7> SumOps; 3193 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3194 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3195 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3196 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3197 z < ze && !Overflow; ++z) { 3198 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3199 uint64_t Coeff; 3200 if (LargerThan64Bits) 3201 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3202 else 3203 Coeff = Coeff1*Coeff2; 3204 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3205 const SCEV *Term1 = AddRec->getOperand(y-z); 3206 const SCEV *Term2 = OtherAddRec->getOperand(z); 3207 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3208 SCEV::FlagAnyWrap, Depth + 1)); 3209 } 3210 } 3211 if (SumOps.empty()) 3212 SumOps.push_back(getZero(Ty)); 3213 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3214 } 3215 if (!Overflow) { 3216 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3217 SCEV::FlagAnyWrap); 3218 if (Ops.size() == 2) return NewAddRec; 3219 Ops[Idx] = NewAddRec; 3220 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3221 OpsModified = true; 3222 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3223 if (!AddRec) 3224 break; 3225 } 3226 } 3227 if (OpsModified) 3228 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3229 3230 // Otherwise couldn't fold anything into this recurrence. Move onto the 3231 // next one. 3232 } 3233 3234 // Okay, it looks like we really DO need an mul expr. Check to see if we 3235 // already have one, otherwise create a new one. 3236 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3237 } 3238 3239 /// Represents an unsigned remainder expression based on unsigned division. 3240 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3241 const SCEV *RHS) { 3242 assert(getEffectiveSCEVType(LHS->getType()) == 3243 getEffectiveSCEVType(RHS->getType()) && 3244 "SCEVURemExpr operand types don't match!"); 3245 3246 // Short-circuit easy cases 3247 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3248 // If constant is one, the result is trivial 3249 if (RHSC->getValue()->isOne()) 3250 return getZero(LHS->getType()); // X urem 1 --> 0 3251 3252 // If constant is a power of two, fold into a zext(trunc(LHS)). 3253 if (RHSC->getAPInt().isPowerOf2()) { 3254 Type *FullTy = LHS->getType(); 3255 Type *TruncTy = 3256 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3257 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3258 } 3259 } 3260 3261 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3262 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3263 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3264 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3265 } 3266 3267 /// Get a canonical unsigned division expression, or something simpler if 3268 /// possible. 3269 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3270 const SCEV *RHS) { 3271 assert(!LHS->getType()->isPointerTy() && 3272 "SCEVUDivExpr operand can't be pointer!"); 3273 assert(LHS->getType() == RHS->getType() && 3274 "SCEVUDivExpr operand types don't match!"); 3275 3276 FoldingSetNodeID ID; 3277 ID.AddInteger(scUDivExpr); 3278 ID.AddPointer(LHS); 3279 ID.AddPointer(RHS); 3280 void *IP = nullptr; 3281 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3282 return S; 3283 3284 // 0 udiv Y == 0 3285 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3286 if (LHSC->getValue()->isZero()) 3287 return LHS; 3288 3289 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3290 if (RHSC->getValue()->isOne()) 3291 return LHS; // X udiv 1 --> x 3292 // If the denominator is zero, the result of the udiv is undefined. Don't 3293 // try to analyze it, because the resolution chosen here may differ from 3294 // the resolution chosen in other parts of the compiler. 3295 if (!RHSC->getValue()->isZero()) { 3296 // Determine if the division can be folded into the operands of 3297 // its operands. 3298 // TODO: Generalize this to non-constants by using known-bits information. 3299 Type *Ty = LHS->getType(); 3300 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3301 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3302 // For non-power-of-two values, effectively round the value up to the 3303 // nearest power of two. 3304 if (!RHSC->getAPInt().isPowerOf2()) 3305 ++MaxShiftAmt; 3306 IntegerType *ExtTy = 3307 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3308 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3309 if (const SCEVConstant *Step = 3310 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3311 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3312 const APInt &StepInt = Step->getAPInt(); 3313 const APInt &DivInt = RHSC->getAPInt(); 3314 if (!StepInt.urem(DivInt) && 3315 getZeroExtendExpr(AR, ExtTy) == 3316 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3317 getZeroExtendExpr(Step, ExtTy), 3318 AR->getLoop(), SCEV::FlagAnyWrap)) { 3319 SmallVector<const SCEV *, 4> Operands; 3320 for (const SCEV *Op : AR->operands()) 3321 Operands.push_back(getUDivExpr(Op, RHS)); 3322 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3323 } 3324 /// Get a canonical UDivExpr for a recurrence. 3325 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3326 // We can currently only fold X%N if X is constant. 3327 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3328 if (StartC && !DivInt.urem(StepInt) && 3329 getZeroExtendExpr(AR, ExtTy) == 3330 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3331 getZeroExtendExpr(Step, ExtTy), 3332 AR->getLoop(), SCEV::FlagAnyWrap)) { 3333 const APInt &StartInt = StartC->getAPInt(); 3334 const APInt &StartRem = StartInt.urem(StepInt); 3335 if (StartRem != 0) { 3336 const SCEV *NewLHS = 3337 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3338 AR->getLoop(), SCEV::FlagNW); 3339 if (LHS != NewLHS) { 3340 LHS = NewLHS; 3341 3342 // Reset the ID to include the new LHS, and check if it is 3343 // already cached. 3344 ID.clear(); 3345 ID.AddInteger(scUDivExpr); 3346 ID.AddPointer(LHS); 3347 ID.AddPointer(RHS); 3348 IP = nullptr; 3349 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3350 return S; 3351 } 3352 } 3353 } 3354 } 3355 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3356 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3357 SmallVector<const SCEV *, 4> Operands; 3358 for (const SCEV *Op : M->operands()) 3359 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3360 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3361 // Find an operand that's safely divisible. 3362 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3363 const SCEV *Op = M->getOperand(i); 3364 const SCEV *Div = getUDivExpr(Op, RHSC); 3365 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3366 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3367 Operands[i] = Div; 3368 return getMulExpr(Operands); 3369 } 3370 } 3371 } 3372 3373 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3374 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3375 if (auto *DivisorConstant = 3376 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3377 bool Overflow = false; 3378 APInt NewRHS = 3379 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3380 if (Overflow) { 3381 return getConstant(RHSC->getType(), 0, false); 3382 } 3383 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3384 } 3385 } 3386 3387 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3388 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3389 SmallVector<const SCEV *, 4> Operands; 3390 for (const SCEV *Op : A->operands()) 3391 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3392 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3393 Operands.clear(); 3394 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3395 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3396 if (isa<SCEVUDivExpr>(Op) || 3397 getMulExpr(Op, RHS) != A->getOperand(i)) 3398 break; 3399 Operands.push_back(Op); 3400 } 3401 if (Operands.size() == A->getNumOperands()) 3402 return getAddExpr(Operands); 3403 } 3404 } 3405 3406 // Fold if both operands are constant. 3407 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3408 Constant *LHSCV = LHSC->getValue(); 3409 Constant *RHSCV = RHSC->getValue(); 3410 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3411 RHSCV))); 3412 } 3413 } 3414 } 3415 3416 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3417 // changes). Make sure we get a new one. 3418 IP = nullptr; 3419 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3420 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3421 LHS, RHS); 3422 UniqueSCEVs.InsertNode(S, IP); 3423 addToLoopUseLists(S); 3424 return S; 3425 } 3426 3427 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3428 APInt A = C1->getAPInt().abs(); 3429 APInt B = C2->getAPInt().abs(); 3430 uint32_t ABW = A.getBitWidth(); 3431 uint32_t BBW = B.getBitWidth(); 3432 3433 if (ABW > BBW) 3434 B = B.zext(ABW); 3435 else if (ABW < BBW) 3436 A = A.zext(BBW); 3437 3438 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3439 } 3440 3441 /// Get a canonical unsigned division expression, or something simpler if 3442 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3443 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3444 /// it's not exact because the udiv may be clearing bits. 3445 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3446 const SCEV *RHS) { 3447 // TODO: we could try to find factors in all sorts of things, but for now we 3448 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3449 // end of this file for inspiration. 3450 3451 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3452 if (!Mul || !Mul->hasNoUnsignedWrap()) 3453 return getUDivExpr(LHS, RHS); 3454 3455 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3456 // If the mulexpr multiplies by a constant, then that constant must be the 3457 // first element of the mulexpr. 3458 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3459 if (LHSCst == RHSCst) { 3460 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3461 return getMulExpr(Operands); 3462 } 3463 3464 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3465 // that there's a factor provided by one of the other terms. We need to 3466 // check. 3467 APInt Factor = gcd(LHSCst, RHSCst); 3468 if (!Factor.isIntN(1)) { 3469 LHSCst = 3470 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3471 RHSCst = 3472 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3473 SmallVector<const SCEV *, 2> Operands; 3474 Operands.push_back(LHSCst); 3475 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3476 LHS = getMulExpr(Operands); 3477 RHS = RHSCst; 3478 Mul = dyn_cast<SCEVMulExpr>(LHS); 3479 if (!Mul) 3480 return getUDivExactExpr(LHS, RHS); 3481 } 3482 } 3483 } 3484 3485 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3486 if (Mul->getOperand(i) == RHS) { 3487 SmallVector<const SCEV *, 2> Operands; 3488 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3489 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3490 return getMulExpr(Operands); 3491 } 3492 } 3493 3494 return getUDivExpr(LHS, RHS); 3495 } 3496 3497 /// Get an add recurrence expression for the specified loop. Simplify the 3498 /// expression as much as possible. 3499 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3500 const Loop *L, 3501 SCEV::NoWrapFlags Flags) { 3502 SmallVector<const SCEV *, 4> Operands; 3503 Operands.push_back(Start); 3504 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3505 if (StepChrec->getLoop() == L) { 3506 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3507 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3508 } 3509 3510 Operands.push_back(Step); 3511 return getAddRecExpr(Operands, L, Flags); 3512 } 3513 3514 /// Get an add recurrence expression for the specified loop. Simplify the 3515 /// expression as much as possible. 3516 const SCEV * 3517 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3518 const Loop *L, SCEV::NoWrapFlags Flags) { 3519 if (Operands.size() == 1) return Operands[0]; 3520 #ifndef NDEBUG 3521 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3522 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3523 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3524 "SCEVAddRecExpr operand types don't match!"); 3525 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3526 } 3527 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3528 assert(isLoopInvariant(Operands[i], L) && 3529 "SCEVAddRecExpr operand is not loop-invariant!"); 3530 #endif 3531 3532 if (Operands.back()->isZero()) { 3533 Operands.pop_back(); 3534 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3535 } 3536 3537 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3538 // use that information to infer NUW and NSW flags. However, computing a 3539 // BE count requires calling getAddRecExpr, so we may not yet have a 3540 // meaningful BE count at this point (and if we don't, we'd be stuck 3541 // with a SCEVCouldNotCompute as the cached BE count). 3542 3543 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3544 3545 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3546 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3547 const Loop *NestedLoop = NestedAR->getLoop(); 3548 if (L->contains(NestedLoop) 3549 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3550 : (!NestedLoop->contains(L) && 3551 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3552 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3553 Operands[0] = NestedAR->getStart(); 3554 // AddRecs require their operands be loop-invariant with respect to their 3555 // loops. Don't perform this transformation if it would break this 3556 // requirement. 3557 bool AllInvariant = all_of( 3558 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3559 3560 if (AllInvariant) { 3561 // Create a recurrence for the outer loop with the same step size. 3562 // 3563 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3564 // inner recurrence has the same property. 3565 SCEV::NoWrapFlags OuterFlags = 3566 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3567 3568 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3569 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3570 return isLoopInvariant(Op, NestedLoop); 3571 }); 3572 3573 if (AllInvariant) { 3574 // Ok, both add recurrences are valid after the transformation. 3575 // 3576 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3577 // the outer recurrence has the same property. 3578 SCEV::NoWrapFlags InnerFlags = 3579 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3580 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3581 } 3582 } 3583 // Reset Operands to its original state. 3584 Operands[0] = NestedAR; 3585 } 3586 } 3587 3588 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3589 // already have one, otherwise create a new one. 3590 return getOrCreateAddRecExpr(Operands, L, Flags); 3591 } 3592 3593 const SCEV * 3594 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3595 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3596 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3597 // getSCEV(Base)->getType() has the same address space as Base->getType() 3598 // because SCEV::getType() preserves the address space. 3599 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3600 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3601 // instruction to its SCEV, because the Instruction may be guarded by control 3602 // flow and the no-overflow bits may not be valid for the expression in any 3603 // context. This can be fixed similarly to how these flags are handled for 3604 // adds. 3605 SCEV::NoWrapFlags OffsetWrap = 3606 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3607 3608 Type *CurTy = GEP->getType(); 3609 bool FirstIter = true; 3610 SmallVector<const SCEV *, 4> Offsets; 3611 for (const SCEV *IndexExpr : IndexExprs) { 3612 // Compute the (potentially symbolic) offset in bytes for this index. 3613 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3614 // For a struct, add the member offset. 3615 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3616 unsigned FieldNo = Index->getZExtValue(); 3617 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3618 Offsets.push_back(FieldOffset); 3619 3620 // Update CurTy to the type of the field at Index. 3621 CurTy = STy->getTypeAtIndex(Index); 3622 } else { 3623 // Update CurTy to its element type. 3624 if (FirstIter) { 3625 assert(isa<PointerType>(CurTy) && 3626 "The first index of a GEP indexes a pointer"); 3627 CurTy = GEP->getSourceElementType(); 3628 FirstIter = false; 3629 } else { 3630 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3631 } 3632 // For an array, add the element offset, explicitly scaled. 3633 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3634 // Getelementptr indices are signed. 3635 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3636 3637 // Multiply the index by the element size to compute the element offset. 3638 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3639 Offsets.push_back(LocalOffset); 3640 } 3641 } 3642 3643 // Handle degenerate case of GEP without offsets. 3644 if (Offsets.empty()) 3645 return BaseExpr; 3646 3647 // Add the offsets together, assuming nsw if inbounds. 3648 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3649 // Add the base address and the offset. We cannot use the nsw flag, as the 3650 // base address is unsigned. However, if we know that the offset is 3651 // non-negative, we can use nuw. 3652 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3653 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3654 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3655 assert(BaseExpr->getType() == GEPExpr->getType() && 3656 "GEP should not change type mid-flight."); 3657 return GEPExpr; 3658 } 3659 3660 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3661 ArrayRef<const SCEV *> Ops) { 3662 FoldingSetNodeID ID; 3663 ID.AddInteger(SCEVType); 3664 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3665 ID.AddPointer(Ops[i]); 3666 void *IP = nullptr; 3667 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3668 } 3669 3670 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3671 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3672 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3673 } 3674 3675 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3676 SmallVectorImpl<const SCEV *> &Ops) { 3677 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3678 if (Ops.size() == 1) return Ops[0]; 3679 #ifndef NDEBUG 3680 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3681 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3682 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3683 "Operand types don't match!"); 3684 assert(Ops[0]->getType()->isPointerTy() == 3685 Ops[i]->getType()->isPointerTy() && 3686 "min/max should be consistently pointerish"); 3687 } 3688 #endif 3689 3690 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3691 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3692 3693 // Sort by complexity, this groups all similar expression types together. 3694 GroupByComplexity(Ops, &LI, DT); 3695 3696 // Check if we have created the same expression before. 3697 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3698 return S; 3699 } 3700 3701 // If there are any constants, fold them together. 3702 unsigned Idx = 0; 3703 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3704 ++Idx; 3705 assert(Idx < Ops.size()); 3706 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3707 if (Kind == scSMaxExpr) 3708 return APIntOps::smax(LHS, RHS); 3709 else if (Kind == scSMinExpr) 3710 return APIntOps::smin(LHS, RHS); 3711 else if (Kind == scUMaxExpr) 3712 return APIntOps::umax(LHS, RHS); 3713 else if (Kind == scUMinExpr) 3714 return APIntOps::umin(LHS, RHS); 3715 llvm_unreachable("Unknown SCEV min/max opcode"); 3716 }; 3717 3718 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3719 // We found two constants, fold them together! 3720 ConstantInt *Fold = ConstantInt::get( 3721 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3722 Ops[0] = getConstant(Fold); 3723 Ops.erase(Ops.begin()+1); // Erase the folded element 3724 if (Ops.size() == 1) return Ops[0]; 3725 LHSC = cast<SCEVConstant>(Ops[0]); 3726 } 3727 3728 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3729 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3730 3731 if (IsMax ? IsMinV : IsMaxV) { 3732 // If we are left with a constant minimum(/maximum)-int, strip it off. 3733 Ops.erase(Ops.begin()); 3734 --Idx; 3735 } else if (IsMax ? IsMaxV : IsMinV) { 3736 // If we have a max(/min) with a constant maximum(/minimum)-int, 3737 // it will always be the extremum. 3738 return LHSC; 3739 } 3740 3741 if (Ops.size() == 1) return Ops[0]; 3742 } 3743 3744 // Find the first operation of the same kind 3745 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3746 ++Idx; 3747 3748 // Check to see if one of the operands is of the same kind. If so, expand its 3749 // operands onto our operand list, and recurse to simplify. 3750 if (Idx < Ops.size()) { 3751 bool DeletedAny = false; 3752 while (Ops[Idx]->getSCEVType() == Kind) { 3753 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3754 Ops.erase(Ops.begin()+Idx); 3755 Ops.append(SMME->op_begin(), SMME->op_end()); 3756 DeletedAny = true; 3757 } 3758 3759 if (DeletedAny) 3760 return getMinMaxExpr(Kind, Ops); 3761 } 3762 3763 // Okay, check to see if the same value occurs in the operand list twice. If 3764 // so, delete one. Since we sorted the list, these values are required to 3765 // be adjacent. 3766 llvm::CmpInst::Predicate GEPred = 3767 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3768 llvm::CmpInst::Predicate LEPred = 3769 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3770 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3771 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3772 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3773 if (Ops[i] == Ops[i + 1] || 3774 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3775 // X op Y op Y --> X op Y 3776 // X op Y --> X, if we know X, Y are ordered appropriately 3777 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3778 --i; 3779 --e; 3780 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3781 Ops[i + 1])) { 3782 // X op Y --> Y, if we know X, Y are ordered appropriately 3783 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3784 --i; 3785 --e; 3786 } 3787 } 3788 3789 if (Ops.size() == 1) return Ops[0]; 3790 3791 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3792 3793 // Okay, it looks like we really DO need an expr. Check to see if we 3794 // already have one, otherwise create a new one. 3795 FoldingSetNodeID ID; 3796 ID.AddInteger(Kind); 3797 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3798 ID.AddPointer(Ops[i]); 3799 void *IP = nullptr; 3800 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3801 if (ExistingSCEV) 3802 return ExistingSCEV; 3803 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3804 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3805 SCEV *S = new (SCEVAllocator) 3806 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3807 3808 UniqueSCEVs.InsertNode(S, IP); 3809 addToLoopUseLists(S); 3810 return S; 3811 } 3812 3813 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3814 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3815 return getSMaxExpr(Ops); 3816 } 3817 3818 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3819 return getMinMaxExpr(scSMaxExpr, Ops); 3820 } 3821 3822 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3823 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3824 return getUMaxExpr(Ops); 3825 } 3826 3827 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3828 return getMinMaxExpr(scUMaxExpr, Ops); 3829 } 3830 3831 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3832 const SCEV *RHS) { 3833 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3834 return getSMinExpr(Ops); 3835 } 3836 3837 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3838 return getMinMaxExpr(scSMinExpr, Ops); 3839 } 3840 3841 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3842 const SCEV *RHS) { 3843 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3844 return getUMinExpr(Ops); 3845 } 3846 3847 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3848 return getMinMaxExpr(scUMinExpr, Ops); 3849 } 3850 3851 const SCEV * 3852 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3853 ScalableVectorType *ScalableTy) { 3854 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3855 Constant *One = ConstantInt::get(IntTy, 1); 3856 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3857 // Note that the expression we created is the final expression, we don't 3858 // want to simplify it any further Also, if we call a normal getSCEV(), 3859 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3860 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3861 } 3862 3863 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3864 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3865 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3866 // We can bypass creating a target-independent constant expression and then 3867 // folding it back into a ConstantInt. This is just a compile-time 3868 // optimization. 3869 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3870 } 3871 3872 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3873 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3874 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3875 // We can bypass creating a target-independent constant expression and then 3876 // folding it back into a ConstantInt. This is just a compile-time 3877 // optimization. 3878 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3879 } 3880 3881 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3882 StructType *STy, 3883 unsigned FieldNo) { 3884 // We can bypass creating a target-independent constant expression and then 3885 // folding it back into a ConstantInt. This is just a compile-time 3886 // optimization. 3887 return getConstant( 3888 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3889 } 3890 3891 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3892 // Don't attempt to do anything other than create a SCEVUnknown object 3893 // here. createSCEV only calls getUnknown after checking for all other 3894 // interesting possibilities, and any other code that calls getUnknown 3895 // is doing so in order to hide a value from SCEV canonicalization. 3896 3897 FoldingSetNodeID ID; 3898 ID.AddInteger(scUnknown); 3899 ID.AddPointer(V); 3900 void *IP = nullptr; 3901 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3902 assert(cast<SCEVUnknown>(S)->getValue() == V && 3903 "Stale SCEVUnknown in uniquing map!"); 3904 return S; 3905 } 3906 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3907 FirstUnknown); 3908 FirstUnknown = cast<SCEVUnknown>(S); 3909 UniqueSCEVs.InsertNode(S, IP); 3910 return S; 3911 } 3912 3913 //===----------------------------------------------------------------------===// 3914 // Basic SCEV Analysis and PHI Idiom Recognition Code 3915 // 3916 3917 /// Test if values of the given type are analyzable within the SCEV 3918 /// framework. This primarily includes integer types, and it can optionally 3919 /// include pointer types if the ScalarEvolution class has access to 3920 /// target-specific information. 3921 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3922 // Integers and pointers are always SCEVable. 3923 return Ty->isIntOrPtrTy(); 3924 } 3925 3926 /// Return the size in bits of the specified type, for which isSCEVable must 3927 /// return true. 3928 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3929 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3930 if (Ty->isPointerTy()) 3931 return getDataLayout().getIndexTypeSizeInBits(Ty); 3932 return getDataLayout().getTypeSizeInBits(Ty); 3933 } 3934 3935 /// Return a type with the same bitwidth as the given type and which represents 3936 /// how SCEV will treat the given type, for which isSCEVable must return 3937 /// true. For pointer types, this is the pointer index sized integer type. 3938 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3939 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3940 3941 if (Ty->isIntegerTy()) 3942 return Ty; 3943 3944 // The only other support type is pointer. 3945 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3946 return getDataLayout().getIndexType(Ty); 3947 } 3948 3949 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3950 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3951 } 3952 3953 const SCEV *ScalarEvolution::getCouldNotCompute() { 3954 return CouldNotCompute.get(); 3955 } 3956 3957 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3958 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3959 auto *SU = dyn_cast<SCEVUnknown>(S); 3960 return SU && SU->getValue() == nullptr; 3961 }); 3962 3963 return !ContainsNulls; 3964 } 3965 3966 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3967 HasRecMapType::iterator I = HasRecMap.find(S); 3968 if (I != HasRecMap.end()) 3969 return I->second; 3970 3971 bool FoundAddRec = 3972 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3973 HasRecMap.insert({S, FoundAddRec}); 3974 return FoundAddRec; 3975 } 3976 3977 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3978 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3979 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3980 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3981 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3982 if (!Add) 3983 return {S, nullptr}; 3984 3985 if (Add->getNumOperands() != 2) 3986 return {S, nullptr}; 3987 3988 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3989 if (!ConstOp) 3990 return {S, nullptr}; 3991 3992 return {Add->getOperand(1), ConstOp->getValue()}; 3993 } 3994 3995 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3996 /// by the value and offset from any ValueOffsetPair in the set. 3997 ScalarEvolution::ValueOffsetPairSetVector * 3998 ScalarEvolution::getSCEVValues(const SCEV *S) { 3999 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4000 if (SI == ExprValueMap.end()) 4001 return nullptr; 4002 #ifndef NDEBUG 4003 if (VerifySCEVMap) { 4004 // Check there is no dangling Value in the set returned. 4005 for (const auto &VE : SI->second) 4006 assert(ValueExprMap.count(VE.first)); 4007 } 4008 #endif 4009 return &SI->second; 4010 } 4011 4012 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4013 /// cannot be used separately. eraseValueFromMap should be used to remove 4014 /// V from ValueExprMap and ExprValueMap at the same time. 4015 void ScalarEvolution::eraseValueFromMap(Value *V) { 4016 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4017 if (I != ValueExprMap.end()) { 4018 const SCEV *S = I->second; 4019 // Remove {V, 0} from the set of ExprValueMap[S] 4020 if (auto *SV = getSCEVValues(S)) 4021 SV->remove({V, nullptr}); 4022 4023 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4024 const SCEV *Stripped; 4025 ConstantInt *Offset; 4026 std::tie(Stripped, Offset) = splitAddExpr(S); 4027 if (Offset != nullptr) { 4028 if (auto *SV = getSCEVValues(Stripped)) 4029 SV->remove({V, Offset}); 4030 } 4031 ValueExprMap.erase(V); 4032 } 4033 } 4034 4035 /// Check whether value has nuw/nsw/exact set but SCEV does not. 4036 /// TODO: In reality it is better to check the poison recursively 4037 /// but this is better than nothing. 4038 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 4039 if (auto *I = dyn_cast<Instruction>(V)) { 4040 if (isa<OverflowingBinaryOperator>(I)) { 4041 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 4042 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 4043 return true; 4044 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 4045 return true; 4046 } 4047 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 4048 return true; 4049 } 4050 return false; 4051 } 4052 4053 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4054 /// create a new one. 4055 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4056 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4057 4058 const SCEV *S = getExistingSCEV(V); 4059 if (S == nullptr) { 4060 S = createSCEV(V); 4061 // During PHI resolution, it is possible to create two SCEVs for the same 4062 // V, so it is needed to double check whether V->S is inserted into 4063 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4064 std::pair<ValueExprMapType::iterator, bool> Pair = 4065 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4066 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 4067 ExprValueMap[S].insert({V, nullptr}); 4068 4069 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4070 // ExprValueMap. 4071 const SCEV *Stripped = S; 4072 ConstantInt *Offset = nullptr; 4073 std::tie(Stripped, Offset) = splitAddExpr(S); 4074 // If stripped is SCEVUnknown, don't bother to save 4075 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4076 // increase the complexity of the expansion code. 4077 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4078 // because it may generate add/sub instead of GEP in SCEV expansion. 4079 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4080 !isa<GetElementPtrInst>(V)) 4081 ExprValueMap[Stripped].insert({V, Offset}); 4082 } 4083 } 4084 return S; 4085 } 4086 4087 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4088 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4089 4090 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4091 if (I != ValueExprMap.end()) { 4092 const SCEV *S = I->second; 4093 if (checkValidity(S)) 4094 return S; 4095 eraseValueFromMap(V); 4096 forgetMemoizedResults(S); 4097 } 4098 return nullptr; 4099 } 4100 4101 /// Return a SCEV corresponding to -V = -1*V 4102 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4103 SCEV::NoWrapFlags Flags) { 4104 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4105 return getConstant( 4106 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4107 4108 Type *Ty = V->getType(); 4109 Ty = getEffectiveSCEVType(Ty); 4110 return getMulExpr(V, getMinusOne(Ty), Flags); 4111 } 4112 4113 /// If Expr computes ~A, return A else return nullptr 4114 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4115 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4116 if (!Add || Add->getNumOperands() != 2 || 4117 !Add->getOperand(0)->isAllOnesValue()) 4118 return nullptr; 4119 4120 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4121 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4122 !AddRHS->getOperand(0)->isAllOnesValue()) 4123 return nullptr; 4124 4125 return AddRHS->getOperand(1); 4126 } 4127 4128 /// Return a SCEV corresponding to ~V = -1-V 4129 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4130 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4131 return getConstant( 4132 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4133 4134 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4135 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4136 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4137 SmallVector<const SCEV *, 2> MatchedOperands; 4138 for (const SCEV *Operand : MME->operands()) { 4139 const SCEV *Matched = MatchNotExpr(Operand); 4140 if (!Matched) 4141 return (const SCEV *)nullptr; 4142 MatchedOperands.push_back(Matched); 4143 } 4144 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4145 MatchedOperands); 4146 }; 4147 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4148 return Replaced; 4149 } 4150 4151 Type *Ty = V->getType(); 4152 Ty = getEffectiveSCEVType(Ty); 4153 return getMinusSCEV(getMinusOne(Ty), V); 4154 } 4155 4156 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4157 assert(P->getType()->isPointerTy()); 4158 4159 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4160 // The base of an AddRec is the first operand. 4161 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4162 Ops[0] = removePointerBase(Ops[0]); 4163 // Don't try to transfer nowrap flags for now. We could in some cases 4164 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4165 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4166 } 4167 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4168 // The base of an Add is the pointer operand. 4169 SmallVector<const SCEV *> Ops{Add->operands()}; 4170 const SCEV **PtrOp = nullptr; 4171 for (const SCEV *&AddOp : Ops) { 4172 if (AddOp->getType()->isPointerTy()) { 4173 assert(!PtrOp && "Cannot have multiple pointer ops"); 4174 PtrOp = &AddOp; 4175 } 4176 } 4177 *PtrOp = removePointerBase(*PtrOp); 4178 // Don't try to transfer nowrap flags for now. We could in some cases 4179 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4180 return getAddExpr(Ops); 4181 } 4182 // Any other expression must be a pointer base. 4183 return getZero(P->getType()); 4184 } 4185 4186 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4187 SCEV::NoWrapFlags Flags, 4188 unsigned Depth) { 4189 // Fast path: X - X --> 0. 4190 if (LHS == RHS) 4191 return getZero(LHS->getType()); 4192 4193 // If we subtract two pointers with different pointer bases, bail. 4194 // Eventually, we're going to add an assertion to getMulExpr that we 4195 // can't multiply by a pointer. 4196 if (RHS->getType()->isPointerTy()) { 4197 if (!LHS->getType()->isPointerTy() || 4198 getPointerBase(LHS) != getPointerBase(RHS)) 4199 return getCouldNotCompute(); 4200 LHS = removePointerBase(LHS); 4201 RHS = removePointerBase(RHS); 4202 } 4203 4204 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4205 // makes it so that we cannot make much use of NUW. 4206 auto AddFlags = SCEV::FlagAnyWrap; 4207 const bool RHSIsNotMinSigned = 4208 !getSignedRangeMin(RHS).isMinSignedValue(); 4209 if (hasFlags(Flags, SCEV::FlagNSW)) { 4210 // Let M be the minimum representable signed value. Then (-1)*RHS 4211 // signed-wraps if and only if RHS is M. That can happen even for 4212 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4213 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4214 // (-1)*RHS, we need to prove that RHS != M. 4215 // 4216 // If LHS is non-negative and we know that LHS - RHS does not 4217 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4218 // either by proving that RHS > M or that LHS >= 0. 4219 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4220 AddFlags = SCEV::FlagNSW; 4221 } 4222 } 4223 4224 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4225 // RHS is NSW and LHS >= 0. 4226 // 4227 // The difficulty here is that the NSW flag may have been proven 4228 // relative to a loop that is to be found in a recurrence in LHS and 4229 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4230 // larger scope than intended. 4231 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4232 4233 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4234 } 4235 4236 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4237 unsigned Depth) { 4238 Type *SrcTy = V->getType(); 4239 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4240 "Cannot truncate or zero extend with non-integer arguments!"); 4241 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4242 return V; // No conversion 4243 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4244 return getTruncateExpr(V, Ty, Depth); 4245 return getZeroExtendExpr(V, Ty, Depth); 4246 } 4247 4248 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4249 unsigned Depth) { 4250 Type *SrcTy = V->getType(); 4251 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4252 "Cannot truncate or zero extend with non-integer arguments!"); 4253 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4254 return V; // No conversion 4255 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4256 return getTruncateExpr(V, Ty, Depth); 4257 return getSignExtendExpr(V, Ty, Depth); 4258 } 4259 4260 const SCEV * 4261 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4262 Type *SrcTy = V->getType(); 4263 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4264 "Cannot noop or zero extend with non-integer arguments!"); 4265 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4266 "getNoopOrZeroExtend cannot truncate!"); 4267 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4268 return V; // No conversion 4269 return getZeroExtendExpr(V, Ty); 4270 } 4271 4272 const SCEV * 4273 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4274 Type *SrcTy = V->getType(); 4275 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4276 "Cannot noop or sign extend with non-integer arguments!"); 4277 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4278 "getNoopOrSignExtend cannot truncate!"); 4279 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4280 return V; // No conversion 4281 return getSignExtendExpr(V, Ty); 4282 } 4283 4284 const SCEV * 4285 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4286 Type *SrcTy = V->getType(); 4287 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4288 "Cannot noop or any extend with non-integer arguments!"); 4289 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4290 "getNoopOrAnyExtend cannot truncate!"); 4291 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4292 return V; // No conversion 4293 return getAnyExtendExpr(V, Ty); 4294 } 4295 4296 const SCEV * 4297 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4298 Type *SrcTy = V->getType(); 4299 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4300 "Cannot truncate or noop with non-integer arguments!"); 4301 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4302 "getTruncateOrNoop cannot extend!"); 4303 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4304 return V; // No conversion 4305 return getTruncateExpr(V, Ty); 4306 } 4307 4308 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4309 const SCEV *RHS) { 4310 const SCEV *PromotedLHS = LHS; 4311 const SCEV *PromotedRHS = RHS; 4312 4313 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4314 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4315 else 4316 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4317 4318 return getUMaxExpr(PromotedLHS, PromotedRHS); 4319 } 4320 4321 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4322 const SCEV *RHS) { 4323 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4324 return getUMinFromMismatchedTypes(Ops); 4325 } 4326 4327 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4328 SmallVectorImpl<const SCEV *> &Ops) { 4329 assert(!Ops.empty() && "At least one operand must be!"); 4330 // Trivial case. 4331 if (Ops.size() == 1) 4332 return Ops[0]; 4333 4334 // Find the max type first. 4335 Type *MaxType = nullptr; 4336 for (auto *S : Ops) 4337 if (MaxType) 4338 MaxType = getWiderType(MaxType, S->getType()); 4339 else 4340 MaxType = S->getType(); 4341 assert(MaxType && "Failed to find maximum type!"); 4342 4343 // Extend all ops to max type. 4344 SmallVector<const SCEV *, 2> PromotedOps; 4345 for (auto *S : Ops) 4346 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4347 4348 // Generate umin. 4349 return getUMinExpr(PromotedOps); 4350 } 4351 4352 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4353 // A pointer operand may evaluate to a nonpointer expression, such as null. 4354 if (!V->getType()->isPointerTy()) 4355 return V; 4356 4357 while (true) { 4358 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4359 V = AddRec->getStart(); 4360 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4361 const SCEV *PtrOp = nullptr; 4362 for (const SCEV *AddOp : Add->operands()) { 4363 if (AddOp->getType()->isPointerTy()) { 4364 assert(!PtrOp && "Cannot have multiple pointer ops"); 4365 PtrOp = AddOp; 4366 } 4367 } 4368 assert(PtrOp && "Must have pointer op"); 4369 V = PtrOp; 4370 } else // Not something we can look further into. 4371 return V; 4372 } 4373 } 4374 4375 /// Push users of the given Instruction onto the given Worklist. 4376 static void 4377 PushDefUseChildren(Instruction *I, 4378 SmallVectorImpl<Instruction *> &Worklist) { 4379 // Push the def-use children onto the Worklist stack. 4380 for (User *U : I->users()) 4381 Worklist.push_back(cast<Instruction>(U)); 4382 } 4383 4384 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4385 SmallVector<Instruction *, 16> Worklist; 4386 PushDefUseChildren(PN, Worklist); 4387 4388 SmallPtrSet<Instruction *, 8> Visited; 4389 Visited.insert(PN); 4390 while (!Worklist.empty()) { 4391 Instruction *I = Worklist.pop_back_val(); 4392 if (!Visited.insert(I).second) 4393 continue; 4394 4395 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4396 if (It != ValueExprMap.end()) { 4397 const SCEV *Old = It->second; 4398 4399 // Short-circuit the def-use traversal if the symbolic name 4400 // ceases to appear in expressions. 4401 if (Old != SymName && !hasOperand(Old, SymName)) 4402 continue; 4403 4404 // SCEVUnknown for a PHI either means that it has an unrecognized 4405 // structure, it's a PHI that's in the progress of being computed 4406 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4407 // additional loop trip count information isn't going to change anything. 4408 // In the second case, createNodeForPHI will perform the necessary 4409 // updates on its own when it gets to that point. In the third, we do 4410 // want to forget the SCEVUnknown. 4411 if (!isa<PHINode>(I) || 4412 !isa<SCEVUnknown>(Old) || 4413 (I != PN && Old == SymName)) { 4414 eraseValueFromMap(It->first); 4415 forgetMemoizedResults(Old); 4416 } 4417 } 4418 4419 PushDefUseChildren(I, Worklist); 4420 } 4421 } 4422 4423 namespace { 4424 4425 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4426 /// expression in case its Loop is L. If it is not L then 4427 /// if IgnoreOtherLoops is true then use AddRec itself 4428 /// otherwise rewrite cannot be done. 4429 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4430 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4431 public: 4432 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4433 bool IgnoreOtherLoops = true) { 4434 SCEVInitRewriter Rewriter(L, SE); 4435 const SCEV *Result = Rewriter.visit(S); 4436 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4437 return SE.getCouldNotCompute(); 4438 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4439 ? SE.getCouldNotCompute() 4440 : Result; 4441 } 4442 4443 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4444 if (!SE.isLoopInvariant(Expr, L)) 4445 SeenLoopVariantSCEVUnknown = true; 4446 return Expr; 4447 } 4448 4449 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4450 // Only re-write AddRecExprs for this loop. 4451 if (Expr->getLoop() == L) 4452 return Expr->getStart(); 4453 SeenOtherLoops = true; 4454 return Expr; 4455 } 4456 4457 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4458 4459 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4460 4461 private: 4462 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4463 : SCEVRewriteVisitor(SE), L(L) {} 4464 4465 const Loop *L; 4466 bool SeenLoopVariantSCEVUnknown = false; 4467 bool SeenOtherLoops = false; 4468 }; 4469 4470 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4471 /// increment expression in case its Loop is L. If it is not L then 4472 /// use AddRec itself. 4473 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4474 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4475 public: 4476 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4477 SCEVPostIncRewriter Rewriter(L, SE); 4478 const SCEV *Result = Rewriter.visit(S); 4479 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4480 ? SE.getCouldNotCompute() 4481 : Result; 4482 } 4483 4484 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4485 if (!SE.isLoopInvariant(Expr, L)) 4486 SeenLoopVariantSCEVUnknown = true; 4487 return Expr; 4488 } 4489 4490 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4491 // Only re-write AddRecExprs for this loop. 4492 if (Expr->getLoop() == L) 4493 return Expr->getPostIncExpr(SE); 4494 SeenOtherLoops = true; 4495 return Expr; 4496 } 4497 4498 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4499 4500 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4501 4502 private: 4503 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4504 : SCEVRewriteVisitor(SE), L(L) {} 4505 4506 const Loop *L; 4507 bool SeenLoopVariantSCEVUnknown = false; 4508 bool SeenOtherLoops = false; 4509 }; 4510 4511 /// This class evaluates the compare condition by matching it against the 4512 /// condition of loop latch. If there is a match we assume a true value 4513 /// for the condition while building SCEV nodes. 4514 class SCEVBackedgeConditionFolder 4515 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4516 public: 4517 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4518 ScalarEvolution &SE) { 4519 bool IsPosBECond = false; 4520 Value *BECond = nullptr; 4521 if (BasicBlock *Latch = L->getLoopLatch()) { 4522 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4523 if (BI && BI->isConditional()) { 4524 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4525 "Both outgoing branches should not target same header!"); 4526 BECond = BI->getCondition(); 4527 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4528 } else { 4529 return S; 4530 } 4531 } 4532 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4533 return Rewriter.visit(S); 4534 } 4535 4536 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4537 const SCEV *Result = Expr; 4538 bool InvariantF = SE.isLoopInvariant(Expr, L); 4539 4540 if (!InvariantF) { 4541 Instruction *I = cast<Instruction>(Expr->getValue()); 4542 switch (I->getOpcode()) { 4543 case Instruction::Select: { 4544 SelectInst *SI = cast<SelectInst>(I); 4545 Optional<const SCEV *> Res = 4546 compareWithBackedgeCondition(SI->getCondition()); 4547 if (Res.hasValue()) { 4548 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4549 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4550 } 4551 break; 4552 } 4553 default: { 4554 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4555 if (Res.hasValue()) 4556 Result = Res.getValue(); 4557 break; 4558 } 4559 } 4560 } 4561 return Result; 4562 } 4563 4564 private: 4565 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4566 bool IsPosBECond, ScalarEvolution &SE) 4567 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4568 IsPositiveBECond(IsPosBECond) {} 4569 4570 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4571 4572 const Loop *L; 4573 /// Loop back condition. 4574 Value *BackedgeCond = nullptr; 4575 /// Set to true if loop back is on positive branch condition. 4576 bool IsPositiveBECond; 4577 }; 4578 4579 Optional<const SCEV *> 4580 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4581 4582 // If value matches the backedge condition for loop latch, 4583 // then return a constant evolution node based on loopback 4584 // branch taken. 4585 if (BackedgeCond == IC) 4586 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4587 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4588 return None; 4589 } 4590 4591 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4592 public: 4593 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4594 ScalarEvolution &SE) { 4595 SCEVShiftRewriter Rewriter(L, SE); 4596 const SCEV *Result = Rewriter.visit(S); 4597 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4598 } 4599 4600 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4601 // Only allow AddRecExprs for this loop. 4602 if (!SE.isLoopInvariant(Expr, L)) 4603 Valid = false; 4604 return Expr; 4605 } 4606 4607 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4608 if (Expr->getLoop() == L && Expr->isAffine()) 4609 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4610 Valid = false; 4611 return Expr; 4612 } 4613 4614 bool isValid() { return Valid; } 4615 4616 private: 4617 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4618 : SCEVRewriteVisitor(SE), L(L) {} 4619 4620 const Loop *L; 4621 bool Valid = true; 4622 }; 4623 4624 } // end anonymous namespace 4625 4626 SCEV::NoWrapFlags 4627 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4628 if (!AR->isAffine()) 4629 return SCEV::FlagAnyWrap; 4630 4631 using OBO = OverflowingBinaryOperator; 4632 4633 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4634 4635 if (!AR->hasNoSignedWrap()) { 4636 ConstantRange AddRecRange = getSignedRange(AR); 4637 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4638 4639 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4640 Instruction::Add, IncRange, OBO::NoSignedWrap); 4641 if (NSWRegion.contains(AddRecRange)) 4642 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4643 } 4644 4645 if (!AR->hasNoUnsignedWrap()) { 4646 ConstantRange AddRecRange = getUnsignedRange(AR); 4647 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4648 4649 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4650 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4651 if (NUWRegion.contains(AddRecRange)) 4652 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4653 } 4654 4655 return Result; 4656 } 4657 4658 SCEV::NoWrapFlags 4659 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4660 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4661 4662 if (AR->hasNoSignedWrap()) 4663 return Result; 4664 4665 if (!AR->isAffine()) 4666 return Result; 4667 4668 const SCEV *Step = AR->getStepRecurrence(*this); 4669 const Loop *L = AR->getLoop(); 4670 4671 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4672 // Note that this serves two purposes: It filters out loops that are 4673 // simply not analyzable, and it covers the case where this code is 4674 // being called from within backedge-taken count analysis, such that 4675 // attempting to ask for the backedge-taken count would likely result 4676 // in infinite recursion. In the later case, the analysis code will 4677 // cope with a conservative value, and it will take care to purge 4678 // that value once it has finished. 4679 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4680 4681 // Normally, in the cases we can prove no-overflow via a 4682 // backedge guarding condition, we can also compute a backedge 4683 // taken count for the loop. The exceptions are assumptions and 4684 // guards present in the loop -- SCEV is not great at exploiting 4685 // these to compute max backedge taken counts, but can still use 4686 // these to prove lack of overflow. Use this fact to avoid 4687 // doing extra work that may not pay off. 4688 4689 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4690 AC.assumptions().empty()) 4691 return Result; 4692 4693 // If the backedge is guarded by a comparison with the pre-inc value the 4694 // addrec is safe. Also, if the entry is guarded by a comparison with the 4695 // start value and the backedge is guarded by a comparison with the post-inc 4696 // value, the addrec is safe. 4697 ICmpInst::Predicate Pred; 4698 const SCEV *OverflowLimit = 4699 getSignedOverflowLimitForStep(Step, &Pred, this); 4700 if (OverflowLimit && 4701 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4702 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4703 Result = setFlags(Result, SCEV::FlagNSW); 4704 } 4705 return Result; 4706 } 4707 SCEV::NoWrapFlags 4708 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4709 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4710 4711 if (AR->hasNoUnsignedWrap()) 4712 return Result; 4713 4714 if (!AR->isAffine()) 4715 return Result; 4716 4717 const SCEV *Step = AR->getStepRecurrence(*this); 4718 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4719 const Loop *L = AR->getLoop(); 4720 4721 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4722 // Note that this serves two purposes: It filters out loops that are 4723 // simply not analyzable, and it covers the case where this code is 4724 // being called from within backedge-taken count analysis, such that 4725 // attempting to ask for the backedge-taken count would likely result 4726 // in infinite recursion. In the later case, the analysis code will 4727 // cope with a conservative value, and it will take care to purge 4728 // that value once it has finished. 4729 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4730 4731 // Normally, in the cases we can prove no-overflow via a 4732 // backedge guarding condition, we can also compute a backedge 4733 // taken count for the loop. The exceptions are assumptions and 4734 // guards present in the loop -- SCEV is not great at exploiting 4735 // these to compute max backedge taken counts, but can still use 4736 // these to prove lack of overflow. Use this fact to avoid 4737 // doing extra work that may not pay off. 4738 4739 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4740 AC.assumptions().empty()) 4741 return Result; 4742 4743 // If the backedge is guarded by a comparison with the pre-inc value the 4744 // addrec is safe. Also, if the entry is guarded by a comparison with the 4745 // start value and the backedge is guarded by a comparison with the post-inc 4746 // value, the addrec is safe. 4747 if (isKnownPositive(Step)) { 4748 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4749 getUnsignedRangeMax(Step)); 4750 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4751 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4752 Result = setFlags(Result, SCEV::FlagNUW); 4753 } 4754 } 4755 4756 return Result; 4757 } 4758 4759 namespace { 4760 4761 /// Represents an abstract binary operation. This may exist as a 4762 /// normal instruction or constant expression, or may have been 4763 /// derived from an expression tree. 4764 struct BinaryOp { 4765 unsigned Opcode; 4766 Value *LHS; 4767 Value *RHS; 4768 bool IsNSW = false; 4769 bool IsNUW = false; 4770 4771 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4772 /// constant expression. 4773 Operator *Op = nullptr; 4774 4775 explicit BinaryOp(Operator *Op) 4776 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4777 Op(Op) { 4778 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4779 IsNSW = OBO->hasNoSignedWrap(); 4780 IsNUW = OBO->hasNoUnsignedWrap(); 4781 } 4782 } 4783 4784 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4785 bool IsNUW = false) 4786 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4787 }; 4788 4789 } // end anonymous namespace 4790 4791 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4792 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4793 auto *Op = dyn_cast<Operator>(V); 4794 if (!Op) 4795 return None; 4796 4797 // Implementation detail: all the cleverness here should happen without 4798 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4799 // SCEV expressions when possible, and we should not break that. 4800 4801 switch (Op->getOpcode()) { 4802 case Instruction::Add: 4803 case Instruction::Sub: 4804 case Instruction::Mul: 4805 case Instruction::UDiv: 4806 case Instruction::URem: 4807 case Instruction::And: 4808 case Instruction::Or: 4809 case Instruction::AShr: 4810 case Instruction::Shl: 4811 return BinaryOp(Op); 4812 4813 case Instruction::Xor: 4814 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4815 // If the RHS of the xor is a signmask, then this is just an add. 4816 // Instcombine turns add of signmask into xor as a strength reduction step. 4817 if (RHSC->getValue().isSignMask()) 4818 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4819 return BinaryOp(Op); 4820 4821 case Instruction::LShr: 4822 // Turn logical shift right of a constant into a unsigned divide. 4823 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4824 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4825 4826 // If the shift count is not less than the bitwidth, the result of 4827 // the shift is undefined. Don't try to analyze it, because the 4828 // resolution chosen here may differ from the resolution chosen in 4829 // other parts of the compiler. 4830 if (SA->getValue().ult(BitWidth)) { 4831 Constant *X = 4832 ConstantInt::get(SA->getContext(), 4833 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4834 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4835 } 4836 } 4837 return BinaryOp(Op); 4838 4839 case Instruction::ExtractValue: { 4840 auto *EVI = cast<ExtractValueInst>(Op); 4841 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4842 break; 4843 4844 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4845 if (!WO) 4846 break; 4847 4848 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4849 bool Signed = WO->isSigned(); 4850 // TODO: Should add nuw/nsw flags for mul as well. 4851 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4852 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4853 4854 // Now that we know that all uses of the arithmetic-result component of 4855 // CI are guarded by the overflow check, we can go ahead and pretend 4856 // that the arithmetic is non-overflowing. 4857 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4858 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4859 } 4860 4861 default: 4862 break; 4863 } 4864 4865 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4866 // semantics as a Sub, return a binary sub expression. 4867 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4868 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4869 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4870 4871 return None; 4872 } 4873 4874 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4875 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4876 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4877 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4878 /// follows one of the following patterns: 4879 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4880 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4881 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4882 /// we return the type of the truncation operation, and indicate whether the 4883 /// truncated type should be treated as signed/unsigned by setting 4884 /// \p Signed to true/false, respectively. 4885 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4886 bool &Signed, ScalarEvolution &SE) { 4887 // The case where Op == SymbolicPHI (that is, with no type conversions on 4888 // the way) is handled by the regular add recurrence creating logic and 4889 // would have already been triggered in createAddRecForPHI. Reaching it here 4890 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4891 // because one of the other operands of the SCEVAddExpr updating this PHI is 4892 // not invariant). 4893 // 4894 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4895 // this case predicates that allow us to prove that Op == SymbolicPHI will 4896 // be added. 4897 if (Op == SymbolicPHI) 4898 return nullptr; 4899 4900 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4901 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4902 if (SourceBits != NewBits) 4903 return nullptr; 4904 4905 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4906 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4907 if (!SExt && !ZExt) 4908 return nullptr; 4909 const SCEVTruncateExpr *Trunc = 4910 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4911 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4912 if (!Trunc) 4913 return nullptr; 4914 const SCEV *X = Trunc->getOperand(); 4915 if (X != SymbolicPHI) 4916 return nullptr; 4917 Signed = SExt != nullptr; 4918 return Trunc->getType(); 4919 } 4920 4921 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4922 if (!PN->getType()->isIntegerTy()) 4923 return nullptr; 4924 const Loop *L = LI.getLoopFor(PN->getParent()); 4925 if (!L || L->getHeader() != PN->getParent()) 4926 return nullptr; 4927 return L; 4928 } 4929 4930 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4931 // computation that updates the phi follows the following pattern: 4932 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4933 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4934 // If so, try to see if it can be rewritten as an AddRecExpr under some 4935 // Predicates. If successful, return them as a pair. Also cache the results 4936 // of the analysis. 4937 // 4938 // Example usage scenario: 4939 // Say the Rewriter is called for the following SCEV: 4940 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4941 // where: 4942 // %X = phi i64 (%Start, %BEValue) 4943 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4944 // and call this function with %SymbolicPHI = %X. 4945 // 4946 // The analysis will find that the value coming around the backedge has 4947 // the following SCEV: 4948 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4949 // Upon concluding that this matches the desired pattern, the function 4950 // will return the pair {NewAddRec, SmallPredsVec} where: 4951 // NewAddRec = {%Start,+,%Step} 4952 // SmallPredsVec = {P1, P2, P3} as follows: 4953 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4954 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4955 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4956 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4957 // under the predicates {P1,P2,P3}. 4958 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4959 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4960 // 4961 // TODO's: 4962 // 4963 // 1) Extend the Induction descriptor to also support inductions that involve 4964 // casts: When needed (namely, when we are called in the context of the 4965 // vectorizer induction analysis), a Set of cast instructions will be 4966 // populated by this method, and provided back to isInductionPHI. This is 4967 // needed to allow the vectorizer to properly record them to be ignored by 4968 // the cost model and to avoid vectorizing them (otherwise these casts, 4969 // which are redundant under the runtime overflow checks, will be 4970 // vectorized, which can be costly). 4971 // 4972 // 2) Support additional induction/PHISCEV patterns: We also want to support 4973 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4974 // after the induction update operation (the induction increment): 4975 // 4976 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4977 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4978 // 4979 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4980 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4981 // 4982 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4983 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4984 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4985 SmallVector<const SCEVPredicate *, 3> Predicates; 4986 4987 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4988 // return an AddRec expression under some predicate. 4989 4990 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4991 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4992 assert(L && "Expecting an integer loop header phi"); 4993 4994 // The loop may have multiple entrances or multiple exits; we can analyze 4995 // this phi as an addrec if it has a unique entry value and a unique 4996 // backedge value. 4997 Value *BEValueV = nullptr, *StartValueV = nullptr; 4998 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4999 Value *V = PN->getIncomingValue(i); 5000 if (L->contains(PN->getIncomingBlock(i))) { 5001 if (!BEValueV) { 5002 BEValueV = V; 5003 } else if (BEValueV != V) { 5004 BEValueV = nullptr; 5005 break; 5006 } 5007 } else if (!StartValueV) { 5008 StartValueV = V; 5009 } else if (StartValueV != V) { 5010 StartValueV = nullptr; 5011 break; 5012 } 5013 } 5014 if (!BEValueV || !StartValueV) 5015 return None; 5016 5017 const SCEV *BEValue = getSCEV(BEValueV); 5018 5019 // If the value coming around the backedge is an add with the symbolic 5020 // value we just inserted, possibly with casts that we can ignore under 5021 // an appropriate runtime guard, then we found a simple induction variable! 5022 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5023 if (!Add) 5024 return None; 5025 5026 // If there is a single occurrence of the symbolic value, possibly 5027 // casted, replace it with a recurrence. 5028 unsigned FoundIndex = Add->getNumOperands(); 5029 Type *TruncTy = nullptr; 5030 bool Signed; 5031 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5032 if ((TruncTy = 5033 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5034 if (FoundIndex == e) { 5035 FoundIndex = i; 5036 break; 5037 } 5038 5039 if (FoundIndex == Add->getNumOperands()) 5040 return None; 5041 5042 // Create an add with everything but the specified operand. 5043 SmallVector<const SCEV *, 8> Ops; 5044 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5045 if (i != FoundIndex) 5046 Ops.push_back(Add->getOperand(i)); 5047 const SCEV *Accum = getAddExpr(Ops); 5048 5049 // The runtime checks will not be valid if the step amount is 5050 // varying inside the loop. 5051 if (!isLoopInvariant(Accum, L)) 5052 return None; 5053 5054 // *** Part2: Create the predicates 5055 5056 // Analysis was successful: we have a phi-with-cast pattern for which we 5057 // can return an AddRec expression under the following predicates: 5058 // 5059 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5060 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5061 // P2: An Equal predicate that guarantees that 5062 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5063 // P3: An Equal predicate that guarantees that 5064 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5065 // 5066 // As we next prove, the above predicates guarantee that: 5067 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5068 // 5069 // 5070 // More formally, we want to prove that: 5071 // Expr(i+1) = Start + (i+1) * Accum 5072 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5073 // 5074 // Given that: 5075 // 1) Expr(0) = Start 5076 // 2) Expr(1) = Start + Accum 5077 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5078 // 3) Induction hypothesis (step i): 5079 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5080 // 5081 // Proof: 5082 // Expr(i+1) = 5083 // = Start + (i+1)*Accum 5084 // = (Start + i*Accum) + Accum 5085 // = Expr(i) + Accum 5086 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5087 // :: from step i 5088 // 5089 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5090 // 5091 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5092 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5093 // + Accum :: from P3 5094 // 5095 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5096 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5097 // 5098 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5099 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5100 // 5101 // By induction, the same applies to all iterations 1<=i<n: 5102 // 5103 5104 // Create a truncated addrec for which we will add a no overflow check (P1). 5105 const SCEV *StartVal = getSCEV(StartValueV); 5106 const SCEV *PHISCEV = 5107 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5108 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5109 5110 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5111 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5112 // will be constant. 5113 // 5114 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5115 // add P1. 5116 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5117 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5118 Signed ? SCEVWrapPredicate::IncrementNSSW 5119 : SCEVWrapPredicate::IncrementNUSW; 5120 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5121 Predicates.push_back(AddRecPred); 5122 } 5123 5124 // Create the Equal Predicates P2,P3: 5125 5126 // It is possible that the predicates P2 and/or P3 are computable at 5127 // compile time due to StartVal and/or Accum being constants. 5128 // If either one is, then we can check that now and escape if either P2 5129 // or P3 is false. 5130 5131 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5132 // for each of StartVal and Accum 5133 auto getExtendedExpr = [&](const SCEV *Expr, 5134 bool CreateSignExtend) -> const SCEV * { 5135 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5136 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5137 const SCEV *ExtendedExpr = 5138 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5139 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5140 return ExtendedExpr; 5141 }; 5142 5143 // Given: 5144 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5145 // = getExtendedExpr(Expr) 5146 // Determine whether the predicate P: Expr == ExtendedExpr 5147 // is known to be false at compile time 5148 auto PredIsKnownFalse = [&](const SCEV *Expr, 5149 const SCEV *ExtendedExpr) -> bool { 5150 return Expr != ExtendedExpr && 5151 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5152 }; 5153 5154 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5155 if (PredIsKnownFalse(StartVal, StartExtended)) { 5156 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5157 return None; 5158 } 5159 5160 // The Step is always Signed (because the overflow checks are either 5161 // NSSW or NUSW) 5162 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5163 if (PredIsKnownFalse(Accum, AccumExtended)) { 5164 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5165 return None; 5166 } 5167 5168 auto AppendPredicate = [&](const SCEV *Expr, 5169 const SCEV *ExtendedExpr) -> void { 5170 if (Expr != ExtendedExpr && 5171 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5172 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5173 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5174 Predicates.push_back(Pred); 5175 } 5176 }; 5177 5178 AppendPredicate(StartVal, StartExtended); 5179 AppendPredicate(Accum, AccumExtended); 5180 5181 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5182 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5183 // into NewAR if it will also add the runtime overflow checks specified in 5184 // Predicates. 5185 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5186 5187 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5188 std::make_pair(NewAR, Predicates); 5189 // Remember the result of the analysis for this SCEV at this locayyytion. 5190 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5191 return PredRewrite; 5192 } 5193 5194 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5195 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5196 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5197 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5198 if (!L) 5199 return None; 5200 5201 // Check to see if we already analyzed this PHI. 5202 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5203 if (I != PredicatedSCEVRewrites.end()) { 5204 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5205 I->second; 5206 // Analysis was done before and failed to create an AddRec: 5207 if (Rewrite.first == SymbolicPHI) 5208 return None; 5209 // Analysis was done before and succeeded to create an AddRec under 5210 // a predicate: 5211 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5212 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5213 return Rewrite; 5214 } 5215 5216 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5217 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5218 5219 // Record in the cache that the analysis failed 5220 if (!Rewrite) { 5221 SmallVector<const SCEVPredicate *, 3> Predicates; 5222 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5223 return None; 5224 } 5225 5226 return Rewrite; 5227 } 5228 5229 // FIXME: This utility is currently required because the Rewriter currently 5230 // does not rewrite this expression: 5231 // {0, +, (sext ix (trunc iy to ix) to iy)} 5232 // into {0, +, %step}, 5233 // even when the following Equal predicate exists: 5234 // "%step == (sext ix (trunc iy to ix) to iy)". 5235 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5236 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5237 if (AR1 == AR2) 5238 return true; 5239 5240 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5241 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5242 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5243 return false; 5244 return true; 5245 }; 5246 5247 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5248 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5249 return false; 5250 return true; 5251 } 5252 5253 /// A helper function for createAddRecFromPHI to handle simple cases. 5254 /// 5255 /// This function tries to find an AddRec expression for the simplest (yet most 5256 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5257 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5258 /// technique for finding the AddRec expression. 5259 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5260 Value *BEValueV, 5261 Value *StartValueV) { 5262 const Loop *L = LI.getLoopFor(PN->getParent()); 5263 assert(L && L->getHeader() == PN->getParent()); 5264 assert(BEValueV && StartValueV); 5265 5266 auto BO = MatchBinaryOp(BEValueV, DT); 5267 if (!BO) 5268 return nullptr; 5269 5270 if (BO->Opcode != Instruction::Add) 5271 return nullptr; 5272 5273 const SCEV *Accum = nullptr; 5274 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5275 Accum = getSCEV(BO->RHS); 5276 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5277 Accum = getSCEV(BO->LHS); 5278 5279 if (!Accum) 5280 return nullptr; 5281 5282 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5283 if (BO->IsNUW) 5284 Flags = setFlags(Flags, SCEV::FlagNUW); 5285 if (BO->IsNSW) 5286 Flags = setFlags(Flags, SCEV::FlagNSW); 5287 5288 const SCEV *StartVal = getSCEV(StartValueV); 5289 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5290 5291 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5292 5293 // We can add Flags to the post-inc expression only if we 5294 // know that it is *undefined behavior* for BEValueV to 5295 // overflow. 5296 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5297 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5298 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5299 5300 return PHISCEV; 5301 } 5302 5303 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5304 const Loop *L = LI.getLoopFor(PN->getParent()); 5305 if (!L || L->getHeader() != PN->getParent()) 5306 return nullptr; 5307 5308 // The loop may have multiple entrances or multiple exits; we can analyze 5309 // this phi as an addrec if it has a unique entry value and a unique 5310 // backedge value. 5311 Value *BEValueV = nullptr, *StartValueV = nullptr; 5312 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5313 Value *V = PN->getIncomingValue(i); 5314 if (L->contains(PN->getIncomingBlock(i))) { 5315 if (!BEValueV) { 5316 BEValueV = V; 5317 } else if (BEValueV != V) { 5318 BEValueV = nullptr; 5319 break; 5320 } 5321 } else if (!StartValueV) { 5322 StartValueV = V; 5323 } else if (StartValueV != V) { 5324 StartValueV = nullptr; 5325 break; 5326 } 5327 } 5328 if (!BEValueV || !StartValueV) 5329 return nullptr; 5330 5331 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5332 "PHI node already processed?"); 5333 5334 // First, try to find AddRec expression without creating a fictituos symbolic 5335 // value for PN. 5336 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5337 return S; 5338 5339 // Handle PHI node value symbolically. 5340 const SCEV *SymbolicName = getUnknown(PN); 5341 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5342 5343 // Using this symbolic name for the PHI, analyze the value coming around 5344 // the back-edge. 5345 const SCEV *BEValue = getSCEV(BEValueV); 5346 5347 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5348 // has a special value for the first iteration of the loop. 5349 5350 // If the value coming around the backedge is an add with the symbolic 5351 // value we just inserted, then we found a simple induction variable! 5352 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5353 // If there is a single occurrence of the symbolic value, replace it 5354 // with a recurrence. 5355 unsigned FoundIndex = Add->getNumOperands(); 5356 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5357 if (Add->getOperand(i) == SymbolicName) 5358 if (FoundIndex == e) { 5359 FoundIndex = i; 5360 break; 5361 } 5362 5363 if (FoundIndex != Add->getNumOperands()) { 5364 // Create an add with everything but the specified operand. 5365 SmallVector<const SCEV *, 8> Ops; 5366 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5367 if (i != FoundIndex) 5368 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5369 L, *this)); 5370 const SCEV *Accum = getAddExpr(Ops); 5371 5372 // This is not a valid addrec if the step amount is varying each 5373 // loop iteration, but is not itself an addrec in this loop. 5374 if (isLoopInvariant(Accum, L) || 5375 (isa<SCEVAddRecExpr>(Accum) && 5376 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5377 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5378 5379 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5380 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5381 if (BO->IsNUW) 5382 Flags = setFlags(Flags, SCEV::FlagNUW); 5383 if (BO->IsNSW) 5384 Flags = setFlags(Flags, SCEV::FlagNSW); 5385 } 5386 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5387 // If the increment is an inbounds GEP, then we know the address 5388 // space cannot be wrapped around. We cannot make any guarantee 5389 // about signed or unsigned overflow because pointers are 5390 // unsigned but we may have a negative index from the base 5391 // pointer. We can guarantee that no unsigned wrap occurs if the 5392 // indices form a positive value. 5393 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5394 Flags = setFlags(Flags, SCEV::FlagNW); 5395 5396 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5397 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5398 Flags = setFlags(Flags, SCEV::FlagNUW); 5399 } 5400 5401 // We cannot transfer nuw and nsw flags from subtraction 5402 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5403 // for instance. 5404 } 5405 5406 const SCEV *StartVal = getSCEV(StartValueV); 5407 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5408 5409 // Okay, for the entire analysis of this edge we assumed the PHI 5410 // to be symbolic. We now need to go back and purge all of the 5411 // entries for the scalars that use the symbolic expression. 5412 forgetSymbolicName(PN, SymbolicName); 5413 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5414 5415 // We can add Flags to the post-inc expression only if we 5416 // know that it is *undefined behavior* for BEValueV to 5417 // overflow. 5418 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5419 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5420 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5421 5422 return PHISCEV; 5423 } 5424 } 5425 } else { 5426 // Otherwise, this could be a loop like this: 5427 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5428 // In this case, j = {1,+,1} and BEValue is j. 5429 // Because the other in-value of i (0) fits the evolution of BEValue 5430 // i really is an addrec evolution. 5431 // 5432 // We can generalize this saying that i is the shifted value of BEValue 5433 // by one iteration: 5434 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5435 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5436 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5437 if (Shifted != getCouldNotCompute() && 5438 Start != getCouldNotCompute()) { 5439 const SCEV *StartVal = getSCEV(StartValueV); 5440 if (Start == StartVal) { 5441 // Okay, for the entire analysis of this edge we assumed the PHI 5442 // to be symbolic. We now need to go back and purge all of the 5443 // entries for the scalars that use the symbolic expression. 5444 forgetSymbolicName(PN, SymbolicName); 5445 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5446 return Shifted; 5447 } 5448 } 5449 } 5450 5451 // Remove the temporary PHI node SCEV that has been inserted while intending 5452 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5453 // as it will prevent later (possibly simpler) SCEV expressions to be added 5454 // to the ValueExprMap. 5455 eraseValueFromMap(PN); 5456 5457 return nullptr; 5458 } 5459 5460 // Checks if the SCEV S is available at BB. S is considered available at BB 5461 // if S can be materialized at BB without introducing a fault. 5462 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5463 BasicBlock *BB) { 5464 struct CheckAvailable { 5465 bool TraversalDone = false; 5466 bool Available = true; 5467 5468 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5469 BasicBlock *BB = nullptr; 5470 DominatorTree &DT; 5471 5472 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5473 : L(L), BB(BB), DT(DT) {} 5474 5475 bool setUnavailable() { 5476 TraversalDone = true; 5477 Available = false; 5478 return false; 5479 } 5480 5481 bool follow(const SCEV *S) { 5482 switch (S->getSCEVType()) { 5483 case scConstant: 5484 case scPtrToInt: 5485 case scTruncate: 5486 case scZeroExtend: 5487 case scSignExtend: 5488 case scAddExpr: 5489 case scMulExpr: 5490 case scUMaxExpr: 5491 case scSMaxExpr: 5492 case scUMinExpr: 5493 case scSMinExpr: 5494 // These expressions are available if their operand(s) is/are. 5495 return true; 5496 5497 case scAddRecExpr: { 5498 // We allow add recurrences that are on the loop BB is in, or some 5499 // outer loop. This guarantees availability because the value of the 5500 // add recurrence at BB is simply the "current" value of the induction 5501 // variable. We can relax this in the future; for instance an add 5502 // recurrence on a sibling dominating loop is also available at BB. 5503 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5504 if (L && (ARLoop == L || ARLoop->contains(L))) 5505 return true; 5506 5507 return setUnavailable(); 5508 } 5509 5510 case scUnknown: { 5511 // For SCEVUnknown, we check for simple dominance. 5512 const auto *SU = cast<SCEVUnknown>(S); 5513 Value *V = SU->getValue(); 5514 5515 if (isa<Argument>(V)) 5516 return false; 5517 5518 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5519 return false; 5520 5521 return setUnavailable(); 5522 } 5523 5524 case scUDivExpr: 5525 case scCouldNotCompute: 5526 // We do not try to smart about these at all. 5527 return setUnavailable(); 5528 } 5529 llvm_unreachable("Unknown SCEV kind!"); 5530 } 5531 5532 bool isDone() { return TraversalDone; } 5533 }; 5534 5535 CheckAvailable CA(L, BB, DT); 5536 SCEVTraversal<CheckAvailable> ST(CA); 5537 5538 ST.visitAll(S); 5539 return CA.Available; 5540 } 5541 5542 // Try to match a control flow sequence that branches out at BI and merges back 5543 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5544 // match. 5545 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5546 Value *&C, Value *&LHS, Value *&RHS) { 5547 C = BI->getCondition(); 5548 5549 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5550 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5551 5552 if (!LeftEdge.isSingleEdge()) 5553 return false; 5554 5555 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5556 5557 Use &LeftUse = Merge->getOperandUse(0); 5558 Use &RightUse = Merge->getOperandUse(1); 5559 5560 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5561 LHS = LeftUse; 5562 RHS = RightUse; 5563 return true; 5564 } 5565 5566 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5567 LHS = RightUse; 5568 RHS = LeftUse; 5569 return true; 5570 } 5571 5572 return false; 5573 } 5574 5575 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5576 auto IsReachable = 5577 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5578 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5579 const Loop *L = LI.getLoopFor(PN->getParent()); 5580 5581 // We don't want to break LCSSA, even in a SCEV expression tree. 5582 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5583 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5584 return nullptr; 5585 5586 // Try to match 5587 // 5588 // br %cond, label %left, label %right 5589 // left: 5590 // br label %merge 5591 // right: 5592 // br label %merge 5593 // merge: 5594 // V = phi [ %x, %left ], [ %y, %right ] 5595 // 5596 // as "select %cond, %x, %y" 5597 5598 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5599 assert(IDom && "At least the entry block should dominate PN"); 5600 5601 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5602 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5603 5604 if (BI && BI->isConditional() && 5605 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5606 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5607 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5608 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5609 } 5610 5611 return nullptr; 5612 } 5613 5614 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5615 if (const SCEV *S = createAddRecFromPHI(PN)) 5616 return S; 5617 5618 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5619 return S; 5620 5621 // If the PHI has a single incoming value, follow that value, unless the 5622 // PHI's incoming blocks are in a different loop, in which case doing so 5623 // risks breaking LCSSA form. Instcombine would normally zap these, but 5624 // it doesn't have DominatorTree information, so it may miss cases. 5625 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5626 if (LI.replacementPreservesLCSSAForm(PN, V)) 5627 return getSCEV(V); 5628 5629 // If it's not a loop phi, we can't handle it yet. 5630 return getUnknown(PN); 5631 } 5632 5633 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5634 Value *Cond, 5635 Value *TrueVal, 5636 Value *FalseVal) { 5637 // Handle "constant" branch or select. This can occur for instance when a 5638 // loop pass transforms an inner loop and moves on to process the outer loop. 5639 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5640 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5641 5642 // Try to match some simple smax or umax patterns. 5643 auto *ICI = dyn_cast<ICmpInst>(Cond); 5644 if (!ICI) 5645 return getUnknown(I); 5646 5647 Value *LHS = ICI->getOperand(0); 5648 Value *RHS = ICI->getOperand(1); 5649 5650 switch (ICI->getPredicate()) { 5651 case ICmpInst::ICMP_SLT: 5652 case ICmpInst::ICMP_SLE: 5653 case ICmpInst::ICMP_ULT: 5654 case ICmpInst::ICMP_ULE: 5655 std::swap(LHS, RHS); 5656 LLVM_FALLTHROUGH; 5657 case ICmpInst::ICMP_SGT: 5658 case ICmpInst::ICMP_SGE: 5659 case ICmpInst::ICMP_UGT: 5660 case ICmpInst::ICMP_UGE: 5661 // a > b ? a+x : b+x -> max(a, b)+x 5662 // a > b ? b+x : a+x -> min(a, b)+x 5663 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5664 bool Signed = ICI->isSigned(); 5665 const SCEV *LA = getSCEV(TrueVal); 5666 const SCEV *RA = getSCEV(FalseVal); 5667 const SCEV *LS = getSCEV(LHS); 5668 const SCEV *RS = getSCEV(RHS); 5669 if (LA->getType()->isPointerTy()) { 5670 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5671 // Need to make sure we can't produce weird expressions involving 5672 // negated pointers. 5673 if (LA == LS && RA == RS) 5674 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5675 if (LA == RS && RA == LS) 5676 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5677 } 5678 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5679 if (Op->getType()->isPointerTy()) { 5680 Op = getLosslessPtrToIntExpr(Op); 5681 if (isa<SCEVCouldNotCompute>(Op)) 5682 return Op; 5683 } 5684 if (Signed) 5685 Op = getNoopOrSignExtend(Op, I->getType()); 5686 else 5687 Op = getNoopOrZeroExtend(Op, I->getType()); 5688 return Op; 5689 }; 5690 LS = CoerceOperand(LS); 5691 RS = CoerceOperand(RS); 5692 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5693 break; 5694 const SCEV *LDiff = getMinusSCEV(LA, LS); 5695 const SCEV *RDiff = getMinusSCEV(RA, RS); 5696 if (LDiff == RDiff) 5697 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5698 LDiff); 5699 LDiff = getMinusSCEV(LA, RS); 5700 RDiff = getMinusSCEV(RA, LS); 5701 if (LDiff == RDiff) 5702 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5703 LDiff); 5704 } 5705 break; 5706 case ICmpInst::ICMP_NE: 5707 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5708 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5709 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5710 const SCEV *One = getOne(I->getType()); 5711 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5712 const SCEV *LA = getSCEV(TrueVal); 5713 const SCEV *RA = getSCEV(FalseVal); 5714 const SCEV *LDiff = getMinusSCEV(LA, LS); 5715 const SCEV *RDiff = getMinusSCEV(RA, One); 5716 if (LDiff == RDiff) 5717 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5718 } 5719 break; 5720 case ICmpInst::ICMP_EQ: 5721 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5722 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5723 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5724 const SCEV *One = getOne(I->getType()); 5725 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5726 const SCEV *LA = getSCEV(TrueVal); 5727 const SCEV *RA = getSCEV(FalseVal); 5728 const SCEV *LDiff = getMinusSCEV(LA, One); 5729 const SCEV *RDiff = getMinusSCEV(RA, LS); 5730 if (LDiff == RDiff) 5731 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5732 } 5733 break; 5734 default: 5735 break; 5736 } 5737 5738 return getUnknown(I); 5739 } 5740 5741 /// Expand GEP instructions into add and multiply operations. This allows them 5742 /// to be analyzed by regular SCEV code. 5743 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5744 // Don't attempt to analyze GEPs over unsized objects. 5745 if (!GEP->getSourceElementType()->isSized()) 5746 return getUnknown(GEP); 5747 5748 SmallVector<const SCEV *, 4> IndexExprs; 5749 for (Value *Index : GEP->indices()) 5750 IndexExprs.push_back(getSCEV(Index)); 5751 return getGEPExpr(GEP, IndexExprs); 5752 } 5753 5754 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5755 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5756 return C->getAPInt().countTrailingZeros(); 5757 5758 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5759 return GetMinTrailingZeros(I->getOperand()); 5760 5761 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5762 return std::min(GetMinTrailingZeros(T->getOperand()), 5763 (uint32_t)getTypeSizeInBits(T->getType())); 5764 5765 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5766 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5767 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5768 ? getTypeSizeInBits(E->getType()) 5769 : OpRes; 5770 } 5771 5772 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5773 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5774 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5775 ? getTypeSizeInBits(E->getType()) 5776 : OpRes; 5777 } 5778 5779 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5780 // The result is the min of all operands results. 5781 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5782 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5783 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5784 return MinOpRes; 5785 } 5786 5787 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5788 // The result is the sum of all operands results. 5789 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5790 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5791 for (unsigned i = 1, e = M->getNumOperands(); 5792 SumOpRes != BitWidth && i != e; ++i) 5793 SumOpRes = 5794 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5795 return SumOpRes; 5796 } 5797 5798 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5799 // The result is the min of all operands results. 5800 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5801 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5802 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5803 return MinOpRes; 5804 } 5805 5806 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5807 // The result is the min of all operands results. 5808 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5809 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5810 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5811 return MinOpRes; 5812 } 5813 5814 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5815 // The result is the min of all operands results. 5816 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5817 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5818 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5819 return MinOpRes; 5820 } 5821 5822 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5823 // For a SCEVUnknown, ask ValueTracking. 5824 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5825 return Known.countMinTrailingZeros(); 5826 } 5827 5828 // SCEVUDivExpr 5829 return 0; 5830 } 5831 5832 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5833 auto I = MinTrailingZerosCache.find(S); 5834 if (I != MinTrailingZerosCache.end()) 5835 return I->second; 5836 5837 uint32_t Result = GetMinTrailingZerosImpl(S); 5838 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5839 assert(InsertPair.second && "Should insert a new key"); 5840 return InsertPair.first->second; 5841 } 5842 5843 /// Helper method to assign a range to V from metadata present in the IR. 5844 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5845 if (Instruction *I = dyn_cast<Instruction>(V)) 5846 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5847 return getConstantRangeFromMetadata(*MD); 5848 5849 return None; 5850 } 5851 5852 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5853 SCEV::NoWrapFlags Flags) { 5854 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5855 AddRec->setNoWrapFlags(Flags); 5856 UnsignedRanges.erase(AddRec); 5857 SignedRanges.erase(AddRec); 5858 } 5859 } 5860 5861 ConstantRange ScalarEvolution:: 5862 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5863 const DataLayout &DL = getDataLayout(); 5864 5865 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5866 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5867 5868 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5869 // use information about the trip count to improve our available range. Note 5870 // that the trip count independent cases are already handled by known bits. 5871 // WARNING: The definition of recurrence used here is subtly different than 5872 // the one used by AddRec (and thus most of this file). Step is allowed to 5873 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5874 // and other addrecs in the same loop (for non-affine addrecs). The code 5875 // below intentionally handles the case where step is not loop invariant. 5876 auto *P = dyn_cast<PHINode>(U->getValue()); 5877 if (!P) 5878 return FullSet; 5879 5880 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5881 // even the values that are not available in these blocks may come from them, 5882 // and this leads to false-positive recurrence test. 5883 for (auto *Pred : predecessors(P->getParent())) 5884 if (!DT.isReachableFromEntry(Pred)) 5885 return FullSet; 5886 5887 BinaryOperator *BO; 5888 Value *Start, *Step; 5889 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5890 return FullSet; 5891 5892 // If we found a recurrence in reachable code, we must be in a loop. Note 5893 // that BO might be in some subloop of L, and that's completely okay. 5894 auto *L = LI.getLoopFor(P->getParent()); 5895 assert(L && L->getHeader() == P->getParent()); 5896 if (!L->contains(BO->getParent())) 5897 // NOTE: This bailout should be an assert instead. However, asserting 5898 // the condition here exposes a case where LoopFusion is querying SCEV 5899 // with malformed loop information during the midst of the transform. 5900 // There doesn't appear to be an obvious fix, so for the moment bailout 5901 // until the caller issue can be fixed. PR49566 tracks the bug. 5902 return FullSet; 5903 5904 // TODO: Extend to other opcodes such as mul, and div 5905 switch (BO->getOpcode()) { 5906 default: 5907 return FullSet; 5908 case Instruction::AShr: 5909 case Instruction::LShr: 5910 case Instruction::Shl: 5911 break; 5912 }; 5913 5914 if (BO->getOperand(0) != P) 5915 // TODO: Handle the power function forms some day. 5916 return FullSet; 5917 5918 unsigned TC = getSmallConstantMaxTripCount(L); 5919 if (!TC || TC >= BitWidth) 5920 return FullSet; 5921 5922 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5923 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5924 assert(KnownStart.getBitWidth() == BitWidth && 5925 KnownStep.getBitWidth() == BitWidth); 5926 5927 // Compute total shift amount, being careful of overflow and bitwidths. 5928 auto MaxShiftAmt = KnownStep.getMaxValue(); 5929 APInt TCAP(BitWidth, TC-1); 5930 bool Overflow = false; 5931 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5932 if (Overflow) 5933 return FullSet; 5934 5935 switch (BO->getOpcode()) { 5936 default: 5937 llvm_unreachable("filtered out above"); 5938 case Instruction::AShr: { 5939 // For each ashr, three cases: 5940 // shift = 0 => unchanged value 5941 // saturation => 0 or -1 5942 // other => a value closer to zero (of the same sign) 5943 // Thus, the end value is closer to zero than the start. 5944 auto KnownEnd = KnownBits::ashr(KnownStart, 5945 KnownBits::makeConstant(TotalShift)); 5946 if (KnownStart.isNonNegative()) 5947 // Analogous to lshr (simply not yet canonicalized) 5948 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5949 KnownStart.getMaxValue() + 1); 5950 if (KnownStart.isNegative()) 5951 // End >=u Start && End <=s Start 5952 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5953 KnownEnd.getMaxValue() + 1); 5954 break; 5955 } 5956 case Instruction::LShr: { 5957 // For each lshr, three cases: 5958 // shift = 0 => unchanged value 5959 // saturation => 0 5960 // other => a smaller positive number 5961 // Thus, the low end of the unsigned range is the last value produced. 5962 auto KnownEnd = KnownBits::lshr(KnownStart, 5963 KnownBits::makeConstant(TotalShift)); 5964 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5965 KnownStart.getMaxValue() + 1); 5966 } 5967 case Instruction::Shl: { 5968 // Iff no bits are shifted out, value increases on every shift. 5969 auto KnownEnd = KnownBits::shl(KnownStart, 5970 KnownBits::makeConstant(TotalShift)); 5971 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5972 return ConstantRange(KnownStart.getMinValue(), 5973 KnownEnd.getMaxValue() + 1); 5974 break; 5975 } 5976 }; 5977 return FullSet; 5978 } 5979 5980 /// Determine the range for a particular SCEV. If SignHint is 5981 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5982 /// with a "cleaner" unsigned (resp. signed) representation. 5983 const ConstantRange & 5984 ScalarEvolution::getRangeRef(const SCEV *S, 5985 ScalarEvolution::RangeSignHint SignHint) { 5986 DenseMap<const SCEV *, ConstantRange> &Cache = 5987 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5988 : SignedRanges; 5989 ConstantRange::PreferredRangeType RangeType = 5990 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5991 ? ConstantRange::Unsigned : ConstantRange::Signed; 5992 5993 // See if we've computed this range already. 5994 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5995 if (I != Cache.end()) 5996 return I->second; 5997 5998 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5999 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6000 6001 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6002 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6003 using OBO = OverflowingBinaryOperator; 6004 6005 // If the value has known zeros, the maximum value will have those known zeros 6006 // as well. 6007 uint32_t TZ = GetMinTrailingZeros(S); 6008 if (TZ != 0) { 6009 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6010 ConservativeResult = 6011 ConstantRange(APInt::getMinValue(BitWidth), 6012 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6013 else 6014 ConservativeResult = ConstantRange( 6015 APInt::getSignedMinValue(BitWidth), 6016 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6017 } 6018 6019 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6020 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6021 unsigned WrapType = OBO::AnyWrap; 6022 if (Add->hasNoSignedWrap()) 6023 WrapType |= OBO::NoSignedWrap; 6024 if (Add->hasNoUnsignedWrap()) 6025 WrapType |= OBO::NoUnsignedWrap; 6026 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6027 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6028 WrapType, RangeType); 6029 return setRange(Add, SignHint, 6030 ConservativeResult.intersectWith(X, RangeType)); 6031 } 6032 6033 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6034 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6035 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6036 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6037 return setRange(Mul, SignHint, 6038 ConservativeResult.intersectWith(X, RangeType)); 6039 } 6040 6041 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6042 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6043 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6044 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6045 return setRange(SMax, SignHint, 6046 ConservativeResult.intersectWith(X, RangeType)); 6047 } 6048 6049 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6050 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6051 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6052 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6053 return setRange(UMax, SignHint, 6054 ConservativeResult.intersectWith(X, RangeType)); 6055 } 6056 6057 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6058 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6059 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6060 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6061 return setRange(SMin, SignHint, 6062 ConservativeResult.intersectWith(X, RangeType)); 6063 } 6064 6065 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6066 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6067 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6068 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6069 return setRange(UMin, SignHint, 6070 ConservativeResult.intersectWith(X, RangeType)); 6071 } 6072 6073 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6074 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6075 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6076 return setRange(UDiv, SignHint, 6077 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6078 } 6079 6080 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6081 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6082 return setRange(ZExt, SignHint, 6083 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6084 RangeType)); 6085 } 6086 6087 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6088 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6089 return setRange(SExt, SignHint, 6090 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6091 RangeType)); 6092 } 6093 6094 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6095 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6096 return setRange(PtrToInt, SignHint, X); 6097 } 6098 6099 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6100 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6101 return setRange(Trunc, SignHint, 6102 ConservativeResult.intersectWith(X.truncate(BitWidth), 6103 RangeType)); 6104 } 6105 6106 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6107 // If there's no unsigned wrap, the value will never be less than its 6108 // initial value. 6109 if (AddRec->hasNoUnsignedWrap()) { 6110 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6111 if (!UnsignedMinValue.isNullValue()) 6112 ConservativeResult = ConservativeResult.intersectWith( 6113 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6114 } 6115 6116 // If there's no signed wrap, and all the operands except initial value have 6117 // the same sign or zero, the value won't ever be: 6118 // 1: smaller than initial value if operands are non negative, 6119 // 2: bigger than initial value if operands are non positive. 6120 // For both cases, value can not cross signed min/max boundary. 6121 if (AddRec->hasNoSignedWrap()) { 6122 bool AllNonNeg = true; 6123 bool AllNonPos = true; 6124 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6125 if (!isKnownNonNegative(AddRec->getOperand(i))) 6126 AllNonNeg = false; 6127 if (!isKnownNonPositive(AddRec->getOperand(i))) 6128 AllNonPos = false; 6129 } 6130 if (AllNonNeg) 6131 ConservativeResult = ConservativeResult.intersectWith( 6132 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6133 APInt::getSignedMinValue(BitWidth)), 6134 RangeType); 6135 else if (AllNonPos) 6136 ConservativeResult = ConservativeResult.intersectWith( 6137 ConstantRange::getNonEmpty( 6138 APInt::getSignedMinValue(BitWidth), 6139 getSignedRangeMax(AddRec->getStart()) + 1), 6140 RangeType); 6141 } 6142 6143 // TODO: non-affine addrec 6144 if (AddRec->isAffine()) { 6145 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6146 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6147 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6148 auto RangeFromAffine = getRangeForAffineAR( 6149 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6150 BitWidth); 6151 ConservativeResult = 6152 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6153 6154 auto RangeFromFactoring = getRangeViaFactoring( 6155 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6156 BitWidth); 6157 ConservativeResult = 6158 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6159 } 6160 6161 // Now try symbolic BE count and more powerful methods. 6162 if (UseExpensiveRangeSharpening) { 6163 const SCEV *SymbolicMaxBECount = 6164 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6165 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6166 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6167 AddRec->hasNoSelfWrap()) { 6168 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6169 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6170 ConservativeResult = 6171 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6172 } 6173 } 6174 } 6175 6176 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6177 } 6178 6179 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6180 6181 // Check if the IR explicitly contains !range metadata. 6182 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6183 if (MDRange.hasValue()) 6184 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6185 RangeType); 6186 6187 // Use facts about recurrences in the underlying IR. Note that add 6188 // recurrences are AddRecExprs and thus don't hit this path. This 6189 // primarily handles shift recurrences. 6190 auto CR = getRangeForUnknownRecurrence(U); 6191 ConservativeResult = ConservativeResult.intersectWith(CR); 6192 6193 // See if ValueTracking can give us a useful range. 6194 const DataLayout &DL = getDataLayout(); 6195 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6196 if (Known.getBitWidth() != BitWidth) 6197 Known = Known.zextOrTrunc(BitWidth); 6198 6199 // ValueTracking may be able to compute a tighter result for the number of 6200 // sign bits than for the value of those sign bits. 6201 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6202 if (U->getType()->isPointerTy()) { 6203 // If the pointer size is larger than the index size type, this can cause 6204 // NS to be larger than BitWidth. So compensate for this. 6205 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6206 int ptrIdxDiff = ptrSize - BitWidth; 6207 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6208 NS -= ptrIdxDiff; 6209 } 6210 6211 if (NS > 1) { 6212 // If we know any of the sign bits, we know all of the sign bits. 6213 if (!Known.Zero.getHiBits(NS).isNullValue()) 6214 Known.Zero.setHighBits(NS); 6215 if (!Known.One.getHiBits(NS).isNullValue()) 6216 Known.One.setHighBits(NS); 6217 } 6218 6219 if (Known.getMinValue() != Known.getMaxValue() + 1) 6220 ConservativeResult = ConservativeResult.intersectWith( 6221 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6222 RangeType); 6223 if (NS > 1) 6224 ConservativeResult = ConservativeResult.intersectWith( 6225 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6226 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6227 RangeType); 6228 6229 // A range of Phi is a subset of union of all ranges of its input. 6230 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6231 // Make sure that we do not run over cycled Phis. 6232 if (PendingPhiRanges.insert(Phi).second) { 6233 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6234 for (auto &Op : Phi->operands()) { 6235 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6236 RangeFromOps = RangeFromOps.unionWith(OpRange); 6237 // No point to continue if we already have a full set. 6238 if (RangeFromOps.isFullSet()) 6239 break; 6240 } 6241 ConservativeResult = 6242 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6243 bool Erased = PendingPhiRanges.erase(Phi); 6244 assert(Erased && "Failed to erase Phi properly?"); 6245 (void) Erased; 6246 } 6247 } 6248 6249 return setRange(U, SignHint, std::move(ConservativeResult)); 6250 } 6251 6252 return setRange(S, SignHint, std::move(ConservativeResult)); 6253 } 6254 6255 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6256 // values that the expression can take. Initially, the expression has a value 6257 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6258 // argument defines if we treat Step as signed or unsigned. 6259 static ConstantRange getRangeForAffineARHelper(APInt Step, 6260 const ConstantRange &StartRange, 6261 const APInt &MaxBECount, 6262 unsigned BitWidth, bool Signed) { 6263 // If either Step or MaxBECount is 0, then the expression won't change, and we 6264 // just need to return the initial range. 6265 if (Step == 0 || MaxBECount == 0) 6266 return StartRange; 6267 6268 // If we don't know anything about the initial value (i.e. StartRange is 6269 // FullRange), then we don't know anything about the final range either. 6270 // Return FullRange. 6271 if (StartRange.isFullSet()) 6272 return ConstantRange::getFull(BitWidth); 6273 6274 // If Step is signed and negative, then we use its absolute value, but we also 6275 // note that we're moving in the opposite direction. 6276 bool Descending = Signed && Step.isNegative(); 6277 6278 if (Signed) 6279 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6280 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6281 // This equations hold true due to the well-defined wrap-around behavior of 6282 // APInt. 6283 Step = Step.abs(); 6284 6285 // Check if Offset is more than full span of BitWidth. If it is, the 6286 // expression is guaranteed to overflow. 6287 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6288 return ConstantRange::getFull(BitWidth); 6289 6290 // Offset is by how much the expression can change. Checks above guarantee no 6291 // overflow here. 6292 APInt Offset = Step * MaxBECount; 6293 6294 // Minimum value of the final range will match the minimal value of StartRange 6295 // if the expression is increasing and will be decreased by Offset otherwise. 6296 // Maximum value of the final range will match the maximal value of StartRange 6297 // if the expression is decreasing and will be increased by Offset otherwise. 6298 APInt StartLower = StartRange.getLower(); 6299 APInt StartUpper = StartRange.getUpper() - 1; 6300 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6301 : (StartUpper + std::move(Offset)); 6302 6303 // It's possible that the new minimum/maximum value will fall into the initial 6304 // range (due to wrap around). This means that the expression can take any 6305 // value in this bitwidth, and we have to return full range. 6306 if (StartRange.contains(MovedBoundary)) 6307 return ConstantRange::getFull(BitWidth); 6308 6309 APInt NewLower = 6310 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6311 APInt NewUpper = 6312 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6313 NewUpper += 1; 6314 6315 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6316 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6317 } 6318 6319 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6320 const SCEV *Step, 6321 const SCEV *MaxBECount, 6322 unsigned BitWidth) { 6323 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6324 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6325 "Precondition!"); 6326 6327 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6328 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6329 6330 // First, consider step signed. 6331 ConstantRange StartSRange = getSignedRange(Start); 6332 ConstantRange StepSRange = getSignedRange(Step); 6333 6334 // If Step can be both positive and negative, we need to find ranges for the 6335 // maximum absolute step values in both directions and union them. 6336 ConstantRange SR = 6337 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6338 MaxBECountValue, BitWidth, /* Signed = */ true); 6339 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6340 StartSRange, MaxBECountValue, 6341 BitWidth, /* Signed = */ true)); 6342 6343 // Next, consider step unsigned. 6344 ConstantRange UR = getRangeForAffineARHelper( 6345 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6346 MaxBECountValue, BitWidth, /* Signed = */ false); 6347 6348 // Finally, intersect signed and unsigned ranges. 6349 return SR.intersectWith(UR, ConstantRange::Smallest); 6350 } 6351 6352 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6353 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6354 ScalarEvolution::RangeSignHint SignHint) { 6355 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6356 assert(AddRec->hasNoSelfWrap() && 6357 "This only works for non-self-wrapping AddRecs!"); 6358 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6359 const SCEV *Step = AddRec->getStepRecurrence(*this); 6360 // Only deal with constant step to save compile time. 6361 if (!isa<SCEVConstant>(Step)) 6362 return ConstantRange::getFull(BitWidth); 6363 // Let's make sure that we can prove that we do not self-wrap during 6364 // MaxBECount iterations. We need this because MaxBECount is a maximum 6365 // iteration count estimate, and we might infer nw from some exit for which we 6366 // do not know max exit count (or any other side reasoning). 6367 // TODO: Turn into assert at some point. 6368 if (getTypeSizeInBits(MaxBECount->getType()) > 6369 getTypeSizeInBits(AddRec->getType())) 6370 return ConstantRange::getFull(BitWidth); 6371 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6372 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6373 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6374 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6375 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6376 MaxItersWithoutWrap)) 6377 return ConstantRange::getFull(BitWidth); 6378 6379 ICmpInst::Predicate LEPred = 6380 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6381 ICmpInst::Predicate GEPred = 6382 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6383 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6384 6385 // We know that there is no self-wrap. Let's take Start and End values and 6386 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6387 // the iteration. They either lie inside the range [Min(Start, End), 6388 // Max(Start, End)] or outside it: 6389 // 6390 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6391 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6392 // 6393 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6394 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6395 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6396 // Start <= End and step is positive, or Start >= End and step is negative. 6397 const SCEV *Start = AddRec->getStart(); 6398 ConstantRange StartRange = getRangeRef(Start, SignHint); 6399 ConstantRange EndRange = getRangeRef(End, SignHint); 6400 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6401 // If they already cover full iteration space, we will know nothing useful 6402 // even if we prove what we want to prove. 6403 if (RangeBetween.isFullSet()) 6404 return RangeBetween; 6405 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6406 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6407 : RangeBetween.isWrappedSet(); 6408 if (IsWrappedSet) 6409 return ConstantRange::getFull(BitWidth); 6410 6411 if (isKnownPositive(Step) && 6412 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6413 return RangeBetween; 6414 else if (isKnownNegative(Step) && 6415 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6416 return RangeBetween; 6417 return ConstantRange::getFull(BitWidth); 6418 } 6419 6420 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6421 const SCEV *Step, 6422 const SCEV *MaxBECount, 6423 unsigned BitWidth) { 6424 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6425 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6426 6427 struct SelectPattern { 6428 Value *Condition = nullptr; 6429 APInt TrueValue; 6430 APInt FalseValue; 6431 6432 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6433 const SCEV *S) { 6434 Optional<unsigned> CastOp; 6435 APInt Offset(BitWidth, 0); 6436 6437 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6438 "Should be!"); 6439 6440 // Peel off a constant offset: 6441 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6442 // In the future we could consider being smarter here and handle 6443 // {Start+Step,+,Step} too. 6444 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6445 return; 6446 6447 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6448 S = SA->getOperand(1); 6449 } 6450 6451 // Peel off a cast operation 6452 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6453 CastOp = SCast->getSCEVType(); 6454 S = SCast->getOperand(); 6455 } 6456 6457 using namespace llvm::PatternMatch; 6458 6459 auto *SU = dyn_cast<SCEVUnknown>(S); 6460 const APInt *TrueVal, *FalseVal; 6461 if (!SU || 6462 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6463 m_APInt(FalseVal)))) { 6464 Condition = nullptr; 6465 return; 6466 } 6467 6468 TrueValue = *TrueVal; 6469 FalseValue = *FalseVal; 6470 6471 // Re-apply the cast we peeled off earlier 6472 if (CastOp.hasValue()) 6473 switch (*CastOp) { 6474 default: 6475 llvm_unreachable("Unknown SCEV cast type!"); 6476 6477 case scTruncate: 6478 TrueValue = TrueValue.trunc(BitWidth); 6479 FalseValue = FalseValue.trunc(BitWidth); 6480 break; 6481 case scZeroExtend: 6482 TrueValue = TrueValue.zext(BitWidth); 6483 FalseValue = FalseValue.zext(BitWidth); 6484 break; 6485 case scSignExtend: 6486 TrueValue = TrueValue.sext(BitWidth); 6487 FalseValue = FalseValue.sext(BitWidth); 6488 break; 6489 } 6490 6491 // Re-apply the constant offset we peeled off earlier 6492 TrueValue += Offset; 6493 FalseValue += Offset; 6494 } 6495 6496 bool isRecognized() { return Condition != nullptr; } 6497 }; 6498 6499 SelectPattern StartPattern(*this, BitWidth, Start); 6500 if (!StartPattern.isRecognized()) 6501 return ConstantRange::getFull(BitWidth); 6502 6503 SelectPattern StepPattern(*this, BitWidth, Step); 6504 if (!StepPattern.isRecognized()) 6505 return ConstantRange::getFull(BitWidth); 6506 6507 if (StartPattern.Condition != StepPattern.Condition) { 6508 // We don't handle this case today; but we could, by considering four 6509 // possibilities below instead of two. I'm not sure if there are cases where 6510 // that will help over what getRange already does, though. 6511 return ConstantRange::getFull(BitWidth); 6512 } 6513 6514 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6515 // construct arbitrary general SCEV expressions here. This function is called 6516 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6517 // say) can end up caching a suboptimal value. 6518 6519 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6520 // C2352 and C2512 (otherwise it isn't needed). 6521 6522 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6523 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6524 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6525 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6526 6527 ConstantRange TrueRange = 6528 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6529 ConstantRange FalseRange = 6530 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6531 6532 return TrueRange.unionWith(FalseRange); 6533 } 6534 6535 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6536 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6537 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6538 6539 // Return early if there are no flags to propagate to the SCEV. 6540 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6541 if (BinOp->hasNoUnsignedWrap()) 6542 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6543 if (BinOp->hasNoSignedWrap()) 6544 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6545 if (Flags == SCEV::FlagAnyWrap) 6546 return SCEV::FlagAnyWrap; 6547 6548 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6549 } 6550 6551 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6552 // Here we check that I is in the header of the innermost loop containing I, 6553 // since we only deal with instructions in the loop header. The actual loop we 6554 // need to check later will come from an add recurrence, but getting that 6555 // requires computing the SCEV of the operands, which can be expensive. This 6556 // check we can do cheaply to rule out some cases early. 6557 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6558 if (InnermostContainingLoop == nullptr || 6559 InnermostContainingLoop->getHeader() != I->getParent()) 6560 return false; 6561 6562 // Only proceed if we can prove that I does not yield poison. 6563 if (!programUndefinedIfPoison(I)) 6564 return false; 6565 6566 // At this point we know that if I is executed, then it does not wrap 6567 // according to at least one of NSW or NUW. If I is not executed, then we do 6568 // not know if the calculation that I represents would wrap. Multiple 6569 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6570 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6571 // derived from other instructions that map to the same SCEV. We cannot make 6572 // that guarantee for cases where I is not executed. So we need to find the 6573 // loop that I is considered in relation to and prove that I is executed for 6574 // every iteration of that loop. That implies that the value that I 6575 // calculates does not wrap anywhere in the loop, so then we can apply the 6576 // flags to the SCEV. 6577 // 6578 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6579 // from different loops, so that we know which loop to prove that I is 6580 // executed in. 6581 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6582 // I could be an extractvalue from a call to an overflow intrinsic. 6583 // TODO: We can do better here in some cases. 6584 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6585 return false; 6586 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6587 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6588 bool AllOtherOpsLoopInvariant = true; 6589 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6590 ++OtherOpIndex) { 6591 if (OtherOpIndex != OpIndex) { 6592 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6593 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6594 AllOtherOpsLoopInvariant = false; 6595 break; 6596 } 6597 } 6598 } 6599 if (AllOtherOpsLoopInvariant && 6600 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6601 return true; 6602 } 6603 } 6604 return false; 6605 } 6606 6607 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6608 // If we know that \c I can never be poison period, then that's enough. 6609 if (isSCEVExprNeverPoison(I)) 6610 return true; 6611 6612 // For an add recurrence specifically, we assume that infinite loops without 6613 // side effects are undefined behavior, and then reason as follows: 6614 // 6615 // If the add recurrence is poison in any iteration, it is poison on all 6616 // future iterations (since incrementing poison yields poison). If the result 6617 // of the add recurrence is fed into the loop latch condition and the loop 6618 // does not contain any throws or exiting blocks other than the latch, we now 6619 // have the ability to "choose" whether the backedge is taken or not (by 6620 // choosing a sufficiently evil value for the poison feeding into the branch) 6621 // for every iteration including and after the one in which \p I first became 6622 // poison. There are two possibilities (let's call the iteration in which \p 6623 // I first became poison as K): 6624 // 6625 // 1. In the set of iterations including and after K, the loop body executes 6626 // no side effects. In this case executing the backege an infinte number 6627 // of times will yield undefined behavior. 6628 // 6629 // 2. In the set of iterations including and after K, the loop body executes 6630 // at least one side effect. In this case, that specific instance of side 6631 // effect is control dependent on poison, which also yields undefined 6632 // behavior. 6633 6634 auto *ExitingBB = L->getExitingBlock(); 6635 auto *LatchBB = L->getLoopLatch(); 6636 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6637 return false; 6638 6639 SmallPtrSet<const Instruction *, 16> Pushed; 6640 SmallVector<const Instruction *, 8> PoisonStack; 6641 6642 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6643 // things that are known to be poison under that assumption go on the 6644 // PoisonStack. 6645 Pushed.insert(I); 6646 PoisonStack.push_back(I); 6647 6648 bool LatchControlDependentOnPoison = false; 6649 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6650 const Instruction *Poison = PoisonStack.pop_back_val(); 6651 6652 for (auto *PoisonUser : Poison->users()) { 6653 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6654 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6655 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6656 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6657 assert(BI->isConditional() && "Only possibility!"); 6658 if (BI->getParent() == LatchBB) { 6659 LatchControlDependentOnPoison = true; 6660 break; 6661 } 6662 } 6663 } 6664 } 6665 6666 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6667 } 6668 6669 ScalarEvolution::LoopProperties 6670 ScalarEvolution::getLoopProperties(const Loop *L) { 6671 using LoopProperties = ScalarEvolution::LoopProperties; 6672 6673 auto Itr = LoopPropertiesCache.find(L); 6674 if (Itr == LoopPropertiesCache.end()) { 6675 auto HasSideEffects = [](Instruction *I) { 6676 if (auto *SI = dyn_cast<StoreInst>(I)) 6677 return !SI->isSimple(); 6678 6679 return I->mayThrow() || I->mayWriteToMemory(); 6680 }; 6681 6682 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6683 /*HasNoSideEffects*/ true}; 6684 6685 for (auto *BB : L->getBlocks()) 6686 for (auto &I : *BB) { 6687 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6688 LP.HasNoAbnormalExits = false; 6689 if (HasSideEffects(&I)) 6690 LP.HasNoSideEffects = false; 6691 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6692 break; // We're already as pessimistic as we can get. 6693 } 6694 6695 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6696 assert(InsertPair.second && "We just checked!"); 6697 Itr = InsertPair.first; 6698 } 6699 6700 return Itr->second; 6701 } 6702 6703 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6704 // A mustprogress loop without side effects must be finite. 6705 // TODO: The check used here is very conservative. It's only *specific* 6706 // side effects which are well defined in infinite loops. 6707 return isMustProgress(L) && loopHasNoSideEffects(L); 6708 } 6709 6710 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6711 if (!isSCEVable(V->getType())) 6712 return getUnknown(V); 6713 6714 if (Instruction *I = dyn_cast<Instruction>(V)) { 6715 // Don't attempt to analyze instructions in blocks that aren't 6716 // reachable. Such instructions don't matter, and they aren't required 6717 // to obey basic rules for definitions dominating uses which this 6718 // analysis depends on. 6719 if (!DT.isReachableFromEntry(I->getParent())) 6720 return getUnknown(UndefValue::get(V->getType())); 6721 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6722 return getConstant(CI); 6723 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6724 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6725 else if (!isa<ConstantExpr>(V)) 6726 return getUnknown(V); 6727 6728 Operator *U = cast<Operator>(V); 6729 if (auto BO = MatchBinaryOp(U, DT)) { 6730 switch (BO->Opcode) { 6731 case Instruction::Add: { 6732 // The simple thing to do would be to just call getSCEV on both operands 6733 // and call getAddExpr with the result. However if we're looking at a 6734 // bunch of things all added together, this can be quite inefficient, 6735 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6736 // Instead, gather up all the operands and make a single getAddExpr call. 6737 // LLVM IR canonical form means we need only traverse the left operands. 6738 SmallVector<const SCEV *, 4> AddOps; 6739 do { 6740 if (BO->Op) { 6741 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6742 AddOps.push_back(OpSCEV); 6743 break; 6744 } 6745 6746 // If a NUW or NSW flag can be applied to the SCEV for this 6747 // addition, then compute the SCEV for this addition by itself 6748 // with a separate call to getAddExpr. We need to do that 6749 // instead of pushing the operands of the addition onto AddOps, 6750 // since the flags are only known to apply to this particular 6751 // addition - they may not apply to other additions that can be 6752 // formed with operands from AddOps. 6753 const SCEV *RHS = getSCEV(BO->RHS); 6754 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6755 if (Flags != SCEV::FlagAnyWrap) { 6756 const SCEV *LHS = getSCEV(BO->LHS); 6757 if (BO->Opcode == Instruction::Sub) 6758 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6759 else 6760 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6761 break; 6762 } 6763 } 6764 6765 if (BO->Opcode == Instruction::Sub) 6766 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6767 else 6768 AddOps.push_back(getSCEV(BO->RHS)); 6769 6770 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6771 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6772 NewBO->Opcode != Instruction::Sub)) { 6773 AddOps.push_back(getSCEV(BO->LHS)); 6774 break; 6775 } 6776 BO = NewBO; 6777 } while (true); 6778 6779 return getAddExpr(AddOps); 6780 } 6781 6782 case Instruction::Mul: { 6783 SmallVector<const SCEV *, 4> MulOps; 6784 do { 6785 if (BO->Op) { 6786 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6787 MulOps.push_back(OpSCEV); 6788 break; 6789 } 6790 6791 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6792 if (Flags != SCEV::FlagAnyWrap) { 6793 MulOps.push_back( 6794 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6795 break; 6796 } 6797 } 6798 6799 MulOps.push_back(getSCEV(BO->RHS)); 6800 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6801 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6802 MulOps.push_back(getSCEV(BO->LHS)); 6803 break; 6804 } 6805 BO = NewBO; 6806 } while (true); 6807 6808 return getMulExpr(MulOps); 6809 } 6810 case Instruction::UDiv: 6811 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6812 case Instruction::URem: 6813 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6814 case Instruction::Sub: { 6815 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6816 if (BO->Op) 6817 Flags = getNoWrapFlagsFromUB(BO->Op); 6818 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6819 } 6820 case Instruction::And: 6821 // For an expression like x&255 that merely masks off the high bits, 6822 // use zext(trunc(x)) as the SCEV expression. 6823 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6824 if (CI->isZero()) 6825 return getSCEV(BO->RHS); 6826 if (CI->isMinusOne()) 6827 return getSCEV(BO->LHS); 6828 const APInt &A = CI->getValue(); 6829 6830 // Instcombine's ShrinkDemandedConstant may strip bits out of 6831 // constants, obscuring what would otherwise be a low-bits mask. 6832 // Use computeKnownBits to compute what ShrinkDemandedConstant 6833 // knew about to reconstruct a low-bits mask value. 6834 unsigned LZ = A.countLeadingZeros(); 6835 unsigned TZ = A.countTrailingZeros(); 6836 unsigned BitWidth = A.getBitWidth(); 6837 KnownBits Known(BitWidth); 6838 computeKnownBits(BO->LHS, Known, getDataLayout(), 6839 0, &AC, nullptr, &DT); 6840 6841 APInt EffectiveMask = 6842 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6843 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6844 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6845 const SCEV *LHS = getSCEV(BO->LHS); 6846 const SCEV *ShiftedLHS = nullptr; 6847 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6848 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6849 // For an expression like (x * 8) & 8, simplify the multiply. 6850 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6851 unsigned GCD = std::min(MulZeros, TZ); 6852 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6853 SmallVector<const SCEV*, 4> MulOps; 6854 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6855 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6856 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6857 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6858 } 6859 } 6860 if (!ShiftedLHS) 6861 ShiftedLHS = getUDivExpr(LHS, MulCount); 6862 return getMulExpr( 6863 getZeroExtendExpr( 6864 getTruncateExpr(ShiftedLHS, 6865 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6866 BO->LHS->getType()), 6867 MulCount); 6868 } 6869 } 6870 break; 6871 6872 case Instruction::Or: 6873 // If the RHS of the Or is a constant, we may have something like: 6874 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6875 // optimizations will transparently handle this case. 6876 // 6877 // In order for this transformation to be safe, the LHS must be of the 6878 // form X*(2^n) and the Or constant must be less than 2^n. 6879 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6880 const SCEV *LHS = getSCEV(BO->LHS); 6881 const APInt &CIVal = CI->getValue(); 6882 if (GetMinTrailingZeros(LHS) >= 6883 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6884 // Build a plain add SCEV. 6885 return getAddExpr(LHS, getSCEV(CI), 6886 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6887 } 6888 } 6889 break; 6890 6891 case Instruction::Xor: 6892 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6893 // If the RHS of xor is -1, then this is a not operation. 6894 if (CI->isMinusOne()) 6895 return getNotSCEV(getSCEV(BO->LHS)); 6896 6897 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6898 // This is a variant of the check for xor with -1, and it handles 6899 // the case where instcombine has trimmed non-demanded bits out 6900 // of an xor with -1. 6901 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6902 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6903 if (LBO->getOpcode() == Instruction::And && 6904 LCI->getValue() == CI->getValue()) 6905 if (const SCEVZeroExtendExpr *Z = 6906 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6907 Type *UTy = BO->LHS->getType(); 6908 const SCEV *Z0 = Z->getOperand(); 6909 Type *Z0Ty = Z0->getType(); 6910 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6911 6912 // If C is a low-bits mask, the zero extend is serving to 6913 // mask off the high bits. Complement the operand and 6914 // re-apply the zext. 6915 if (CI->getValue().isMask(Z0TySize)) 6916 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6917 6918 // If C is a single bit, it may be in the sign-bit position 6919 // before the zero-extend. In this case, represent the xor 6920 // using an add, which is equivalent, and re-apply the zext. 6921 APInt Trunc = CI->getValue().trunc(Z0TySize); 6922 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6923 Trunc.isSignMask()) 6924 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6925 UTy); 6926 } 6927 } 6928 break; 6929 6930 case Instruction::Shl: 6931 // Turn shift left of a constant amount into a multiply. 6932 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6933 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6934 6935 // If the shift count is not less than the bitwidth, the result of 6936 // the shift is undefined. Don't try to analyze it, because the 6937 // resolution chosen here may differ from the resolution chosen in 6938 // other parts of the compiler. 6939 if (SA->getValue().uge(BitWidth)) 6940 break; 6941 6942 // We can safely preserve the nuw flag in all cases. It's also safe to 6943 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6944 // requires special handling. It can be preserved as long as we're not 6945 // left shifting by bitwidth - 1. 6946 auto Flags = SCEV::FlagAnyWrap; 6947 if (BO->Op) { 6948 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6949 if ((MulFlags & SCEV::FlagNSW) && 6950 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6951 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6952 if (MulFlags & SCEV::FlagNUW) 6953 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6954 } 6955 6956 Constant *X = ConstantInt::get( 6957 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6958 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6959 } 6960 break; 6961 6962 case Instruction::AShr: { 6963 // AShr X, C, where C is a constant. 6964 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6965 if (!CI) 6966 break; 6967 6968 Type *OuterTy = BO->LHS->getType(); 6969 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6970 // If the shift count is not less than the bitwidth, the result of 6971 // the shift is undefined. Don't try to analyze it, because the 6972 // resolution chosen here may differ from the resolution chosen in 6973 // other parts of the compiler. 6974 if (CI->getValue().uge(BitWidth)) 6975 break; 6976 6977 if (CI->isZero()) 6978 return getSCEV(BO->LHS); // shift by zero --> noop 6979 6980 uint64_t AShrAmt = CI->getZExtValue(); 6981 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6982 6983 Operator *L = dyn_cast<Operator>(BO->LHS); 6984 if (L && L->getOpcode() == Instruction::Shl) { 6985 // X = Shl A, n 6986 // Y = AShr X, m 6987 // Both n and m are constant. 6988 6989 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6990 if (L->getOperand(1) == BO->RHS) 6991 // For a two-shift sext-inreg, i.e. n = m, 6992 // use sext(trunc(x)) as the SCEV expression. 6993 return getSignExtendExpr( 6994 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6995 6996 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6997 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6998 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6999 if (ShlAmt > AShrAmt) { 7000 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7001 // expression. We already checked that ShlAmt < BitWidth, so 7002 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7003 // ShlAmt - AShrAmt < Amt. 7004 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7005 ShlAmt - AShrAmt); 7006 return getSignExtendExpr( 7007 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7008 getConstant(Mul)), OuterTy); 7009 } 7010 } 7011 } 7012 break; 7013 } 7014 } 7015 } 7016 7017 switch (U->getOpcode()) { 7018 case Instruction::Trunc: 7019 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7020 7021 case Instruction::ZExt: 7022 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7023 7024 case Instruction::SExt: 7025 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7026 // The NSW flag of a subtract does not always survive the conversion to 7027 // A + (-1)*B. By pushing sign extension onto its operands we are much 7028 // more likely to preserve NSW and allow later AddRec optimisations. 7029 // 7030 // NOTE: This is effectively duplicating this logic from getSignExtend: 7031 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7032 // but by that point the NSW information has potentially been lost. 7033 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7034 Type *Ty = U->getType(); 7035 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7036 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7037 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7038 } 7039 } 7040 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7041 7042 case Instruction::BitCast: 7043 // BitCasts are no-op casts so we just eliminate the cast. 7044 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7045 return getSCEV(U->getOperand(0)); 7046 break; 7047 7048 case Instruction::PtrToInt: { 7049 // Pointer to integer cast is straight-forward, so do model it. 7050 const SCEV *Op = getSCEV(U->getOperand(0)); 7051 Type *DstIntTy = U->getType(); 7052 // But only if effective SCEV (integer) type is wide enough to represent 7053 // all possible pointer values. 7054 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7055 if (isa<SCEVCouldNotCompute>(IntOp)) 7056 return getUnknown(V); 7057 return IntOp; 7058 } 7059 case Instruction::IntToPtr: 7060 // Just don't deal with inttoptr casts. 7061 return getUnknown(V); 7062 7063 case Instruction::SDiv: 7064 // If both operands are non-negative, this is just an udiv. 7065 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7066 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7067 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7068 break; 7069 7070 case Instruction::SRem: 7071 // If both operands are non-negative, this is just an urem. 7072 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7073 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7074 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7075 break; 7076 7077 case Instruction::GetElementPtr: 7078 return createNodeForGEP(cast<GEPOperator>(U)); 7079 7080 case Instruction::PHI: 7081 return createNodeForPHI(cast<PHINode>(U)); 7082 7083 case Instruction::Select: 7084 // U can also be a select constant expr, which let fall through. Since 7085 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7086 // constant expressions cannot have instructions as operands, we'd have 7087 // returned getUnknown for a select constant expressions anyway. 7088 if (isa<Instruction>(U)) 7089 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7090 U->getOperand(1), U->getOperand(2)); 7091 break; 7092 7093 case Instruction::Call: 7094 case Instruction::Invoke: 7095 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7096 return getSCEV(RV); 7097 7098 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7099 switch (II->getIntrinsicID()) { 7100 case Intrinsic::abs: 7101 return getAbsExpr( 7102 getSCEV(II->getArgOperand(0)), 7103 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7104 case Intrinsic::umax: 7105 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7106 getSCEV(II->getArgOperand(1))); 7107 case Intrinsic::umin: 7108 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7109 getSCEV(II->getArgOperand(1))); 7110 case Intrinsic::smax: 7111 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7112 getSCEV(II->getArgOperand(1))); 7113 case Intrinsic::smin: 7114 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7115 getSCEV(II->getArgOperand(1))); 7116 case Intrinsic::usub_sat: { 7117 const SCEV *X = getSCEV(II->getArgOperand(0)); 7118 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7119 const SCEV *ClampedY = getUMinExpr(X, Y); 7120 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7121 } 7122 case Intrinsic::uadd_sat: { 7123 const SCEV *X = getSCEV(II->getArgOperand(0)); 7124 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7125 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7126 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7127 } 7128 case Intrinsic::start_loop_iterations: 7129 // A start_loop_iterations is just equivalent to the first operand for 7130 // SCEV purposes. 7131 return getSCEV(II->getArgOperand(0)); 7132 default: 7133 break; 7134 } 7135 } 7136 break; 7137 } 7138 7139 return getUnknown(V); 7140 } 7141 7142 //===----------------------------------------------------------------------===// 7143 // Iteration Count Computation Code 7144 // 7145 7146 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7147 // Get the trip count from the BE count by adding 1. Overflow, results 7148 // in zero which means "unknown". 7149 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7150 } 7151 7152 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7153 if (!ExitCount) 7154 return 0; 7155 7156 ConstantInt *ExitConst = ExitCount->getValue(); 7157 7158 // Guard against huge trip counts. 7159 if (ExitConst->getValue().getActiveBits() > 32) 7160 return 0; 7161 7162 // In case of integer overflow, this returns 0, which is correct. 7163 return ((unsigned)ExitConst->getZExtValue()) + 1; 7164 } 7165 7166 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7167 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7168 return getConstantTripCount(ExitCount); 7169 } 7170 7171 unsigned 7172 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7173 const BasicBlock *ExitingBlock) { 7174 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7175 assert(L->isLoopExiting(ExitingBlock) && 7176 "Exiting block must actually branch out of the loop!"); 7177 const SCEVConstant *ExitCount = 7178 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7179 return getConstantTripCount(ExitCount); 7180 } 7181 7182 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7183 const auto *MaxExitCount = 7184 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7185 return getConstantTripCount(MaxExitCount); 7186 } 7187 7188 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7189 SmallVector<BasicBlock *, 8> ExitingBlocks; 7190 L->getExitingBlocks(ExitingBlocks); 7191 7192 Optional<unsigned> Res = None; 7193 for (auto *ExitingBB : ExitingBlocks) { 7194 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7195 if (!Res) 7196 Res = Multiple; 7197 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7198 } 7199 return Res.getValueOr(1); 7200 } 7201 7202 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7203 const SCEV *ExitCount) { 7204 if (ExitCount == getCouldNotCompute()) 7205 return 1; 7206 7207 // Get the trip count 7208 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7209 7210 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7211 if (!TC) 7212 // Attempt to factor more general cases. Returns the greatest power of 7213 // two divisor. If overflow happens, the trip count expression is still 7214 // divisible by the greatest power of 2 divisor returned. 7215 return 1U << std::min((uint32_t)31, 7216 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7217 7218 ConstantInt *Result = TC->getValue(); 7219 7220 // Guard against huge trip counts (this requires checking 7221 // for zero to handle the case where the trip count == -1 and the 7222 // addition wraps). 7223 if (!Result || Result->getValue().getActiveBits() > 32 || 7224 Result->getValue().getActiveBits() == 0) 7225 return 1; 7226 7227 return (unsigned)Result->getZExtValue(); 7228 } 7229 7230 /// Returns the largest constant divisor of the trip count of this loop as a 7231 /// normal unsigned value, if possible. This means that the actual trip count is 7232 /// always a multiple of the returned value (don't forget the trip count could 7233 /// very well be zero as well!). 7234 /// 7235 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7236 /// multiple of a constant (which is also the case if the trip count is simply 7237 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7238 /// if the trip count is very large (>= 2^32). 7239 /// 7240 /// As explained in the comments for getSmallConstantTripCount, this assumes 7241 /// that control exits the loop via ExitingBlock. 7242 unsigned 7243 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7244 const BasicBlock *ExitingBlock) { 7245 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7246 assert(L->isLoopExiting(ExitingBlock) && 7247 "Exiting block must actually branch out of the loop!"); 7248 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7249 return getSmallConstantTripMultiple(L, ExitCount); 7250 } 7251 7252 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7253 const BasicBlock *ExitingBlock, 7254 ExitCountKind Kind) { 7255 switch (Kind) { 7256 case Exact: 7257 case SymbolicMaximum: 7258 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7259 case ConstantMaximum: 7260 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7261 }; 7262 llvm_unreachable("Invalid ExitCountKind!"); 7263 } 7264 7265 const SCEV * 7266 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7267 SCEVUnionPredicate &Preds) { 7268 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7269 } 7270 7271 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7272 ExitCountKind Kind) { 7273 switch (Kind) { 7274 case Exact: 7275 return getBackedgeTakenInfo(L).getExact(L, this); 7276 case ConstantMaximum: 7277 return getBackedgeTakenInfo(L).getConstantMax(this); 7278 case SymbolicMaximum: 7279 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7280 }; 7281 llvm_unreachable("Invalid ExitCountKind!"); 7282 } 7283 7284 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7285 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7286 } 7287 7288 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7289 static void 7290 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7291 BasicBlock *Header = L->getHeader(); 7292 7293 // Push all Loop-header PHIs onto the Worklist stack. 7294 for (PHINode &PN : Header->phis()) 7295 Worklist.push_back(&PN); 7296 } 7297 7298 const ScalarEvolution::BackedgeTakenInfo & 7299 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7300 auto &BTI = getBackedgeTakenInfo(L); 7301 if (BTI.hasFullInfo()) 7302 return BTI; 7303 7304 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7305 7306 if (!Pair.second) 7307 return Pair.first->second; 7308 7309 BackedgeTakenInfo Result = 7310 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7311 7312 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7313 } 7314 7315 ScalarEvolution::BackedgeTakenInfo & 7316 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7317 // Initially insert an invalid entry for this loop. If the insertion 7318 // succeeds, proceed to actually compute a backedge-taken count and 7319 // update the value. The temporary CouldNotCompute value tells SCEV 7320 // code elsewhere that it shouldn't attempt to request a new 7321 // backedge-taken count, which could result in infinite recursion. 7322 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7323 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7324 if (!Pair.second) 7325 return Pair.first->second; 7326 7327 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7328 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7329 // must be cleared in this scope. 7330 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7331 7332 // In product build, there are no usage of statistic. 7333 (void)NumTripCountsComputed; 7334 (void)NumTripCountsNotComputed; 7335 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7336 const SCEV *BEExact = Result.getExact(L, this); 7337 if (BEExact != getCouldNotCompute()) { 7338 assert(isLoopInvariant(BEExact, L) && 7339 isLoopInvariant(Result.getConstantMax(this), L) && 7340 "Computed backedge-taken count isn't loop invariant for loop!"); 7341 ++NumTripCountsComputed; 7342 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7343 isa<PHINode>(L->getHeader()->begin())) { 7344 // Only count loops that have phi nodes as not being computable. 7345 ++NumTripCountsNotComputed; 7346 } 7347 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7348 7349 // Now that we know more about the trip count for this loop, forget any 7350 // existing SCEV values for PHI nodes in this loop since they are only 7351 // conservative estimates made without the benefit of trip count 7352 // information. This is similar to the code in forgetLoop, except that 7353 // it handles SCEVUnknown PHI nodes specially. 7354 if (Result.hasAnyInfo()) { 7355 SmallVector<Instruction *, 16> Worklist; 7356 PushLoopPHIs(L, Worklist); 7357 7358 SmallPtrSet<Instruction *, 8> Discovered; 7359 while (!Worklist.empty()) { 7360 Instruction *I = Worklist.pop_back_val(); 7361 7362 ValueExprMapType::iterator It = 7363 ValueExprMap.find_as(static_cast<Value *>(I)); 7364 if (It != ValueExprMap.end()) { 7365 const SCEV *Old = It->second; 7366 7367 // SCEVUnknown for a PHI either means that it has an unrecognized 7368 // structure, or it's a PHI that's in the progress of being computed 7369 // by createNodeForPHI. In the former case, additional loop trip 7370 // count information isn't going to change anything. In the later 7371 // case, createNodeForPHI will perform the necessary updates on its 7372 // own when it gets to that point. 7373 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7374 eraseValueFromMap(It->first); 7375 forgetMemoizedResults(Old); 7376 } 7377 if (PHINode *PN = dyn_cast<PHINode>(I)) 7378 ConstantEvolutionLoopExitValue.erase(PN); 7379 } 7380 7381 // Since we don't need to invalidate anything for correctness and we're 7382 // only invalidating to make SCEV's results more precise, we get to stop 7383 // early to avoid invalidating too much. This is especially important in 7384 // cases like: 7385 // 7386 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7387 // loop0: 7388 // %pn0 = phi 7389 // ... 7390 // loop1: 7391 // %pn1 = phi 7392 // ... 7393 // 7394 // where both loop0 and loop1's backedge taken count uses the SCEV 7395 // expression for %v. If we don't have the early stop below then in cases 7396 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7397 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7398 // count for loop1, effectively nullifying SCEV's trip count cache. 7399 for (auto *U : I->users()) 7400 if (auto *I = dyn_cast<Instruction>(U)) { 7401 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7402 if (LoopForUser && L->contains(LoopForUser) && 7403 Discovered.insert(I).second) 7404 Worklist.push_back(I); 7405 } 7406 } 7407 } 7408 7409 // Re-lookup the insert position, since the call to 7410 // computeBackedgeTakenCount above could result in a 7411 // recusive call to getBackedgeTakenInfo (on a different 7412 // loop), which would invalidate the iterator computed 7413 // earlier. 7414 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7415 } 7416 7417 void ScalarEvolution::forgetAllLoops() { 7418 // This method is intended to forget all info about loops. It should 7419 // invalidate caches as if the following happened: 7420 // - The trip counts of all loops have changed arbitrarily 7421 // - Every llvm::Value has been updated in place to produce a different 7422 // result. 7423 BackedgeTakenCounts.clear(); 7424 PredicatedBackedgeTakenCounts.clear(); 7425 LoopPropertiesCache.clear(); 7426 ConstantEvolutionLoopExitValue.clear(); 7427 ValueExprMap.clear(); 7428 ValuesAtScopes.clear(); 7429 LoopDispositions.clear(); 7430 BlockDispositions.clear(); 7431 UnsignedRanges.clear(); 7432 SignedRanges.clear(); 7433 ExprValueMap.clear(); 7434 HasRecMap.clear(); 7435 MinTrailingZerosCache.clear(); 7436 PredicatedSCEVRewrites.clear(); 7437 } 7438 7439 void ScalarEvolution::forgetLoop(const Loop *L) { 7440 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7441 SmallVector<Instruction *, 32> Worklist; 7442 SmallPtrSet<Instruction *, 16> Visited; 7443 7444 // Iterate over all the loops and sub-loops to drop SCEV information. 7445 while (!LoopWorklist.empty()) { 7446 auto *CurrL = LoopWorklist.pop_back_val(); 7447 7448 // Drop any stored trip count value. 7449 BackedgeTakenCounts.erase(CurrL); 7450 PredicatedBackedgeTakenCounts.erase(CurrL); 7451 7452 // Drop information about predicated SCEV rewrites for this loop. 7453 for (auto I = PredicatedSCEVRewrites.begin(); 7454 I != PredicatedSCEVRewrites.end();) { 7455 std::pair<const SCEV *, const Loop *> Entry = I->first; 7456 if (Entry.second == CurrL) 7457 PredicatedSCEVRewrites.erase(I++); 7458 else 7459 ++I; 7460 } 7461 7462 auto LoopUsersItr = LoopUsers.find(CurrL); 7463 if (LoopUsersItr != LoopUsers.end()) { 7464 for (auto *S : LoopUsersItr->second) 7465 forgetMemoizedResults(S); 7466 LoopUsers.erase(LoopUsersItr); 7467 } 7468 7469 // Drop information about expressions based on loop-header PHIs. 7470 PushLoopPHIs(CurrL, Worklist); 7471 7472 while (!Worklist.empty()) { 7473 Instruction *I = Worklist.pop_back_val(); 7474 if (!Visited.insert(I).second) 7475 continue; 7476 7477 ValueExprMapType::iterator It = 7478 ValueExprMap.find_as(static_cast<Value *>(I)); 7479 if (It != ValueExprMap.end()) { 7480 eraseValueFromMap(It->first); 7481 forgetMemoizedResults(It->second); 7482 if (PHINode *PN = dyn_cast<PHINode>(I)) 7483 ConstantEvolutionLoopExitValue.erase(PN); 7484 } 7485 7486 PushDefUseChildren(I, Worklist); 7487 } 7488 7489 LoopPropertiesCache.erase(CurrL); 7490 // Forget all contained loops too, to avoid dangling entries in the 7491 // ValuesAtScopes map. 7492 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7493 } 7494 } 7495 7496 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7497 while (Loop *Parent = L->getParentLoop()) 7498 L = Parent; 7499 forgetLoop(L); 7500 } 7501 7502 void ScalarEvolution::forgetValue(Value *V) { 7503 Instruction *I = dyn_cast<Instruction>(V); 7504 if (!I) return; 7505 7506 // Drop information about expressions based on loop-header PHIs. 7507 SmallVector<Instruction *, 16> Worklist; 7508 Worklist.push_back(I); 7509 7510 SmallPtrSet<Instruction *, 8> Visited; 7511 while (!Worklist.empty()) { 7512 I = Worklist.pop_back_val(); 7513 if (!Visited.insert(I).second) 7514 continue; 7515 7516 ValueExprMapType::iterator It = 7517 ValueExprMap.find_as(static_cast<Value *>(I)); 7518 if (It != ValueExprMap.end()) { 7519 eraseValueFromMap(It->first); 7520 forgetMemoizedResults(It->second); 7521 if (PHINode *PN = dyn_cast<PHINode>(I)) 7522 ConstantEvolutionLoopExitValue.erase(PN); 7523 } 7524 7525 PushDefUseChildren(I, Worklist); 7526 } 7527 } 7528 7529 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7530 LoopDispositions.clear(); 7531 } 7532 7533 /// Get the exact loop backedge taken count considering all loop exits. A 7534 /// computable result can only be returned for loops with all exiting blocks 7535 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7536 /// is never skipped. This is a valid assumption as long as the loop exits via 7537 /// that test. For precise results, it is the caller's responsibility to specify 7538 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7539 const SCEV * 7540 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7541 SCEVUnionPredicate *Preds) const { 7542 // If any exits were not computable, the loop is not computable. 7543 if (!isComplete() || ExitNotTaken.empty()) 7544 return SE->getCouldNotCompute(); 7545 7546 const BasicBlock *Latch = L->getLoopLatch(); 7547 // All exiting blocks we have collected must dominate the only backedge. 7548 if (!Latch) 7549 return SE->getCouldNotCompute(); 7550 7551 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7552 // count is simply a minimum out of all these calculated exit counts. 7553 SmallVector<const SCEV *, 2> Ops; 7554 for (auto &ENT : ExitNotTaken) { 7555 const SCEV *BECount = ENT.ExactNotTaken; 7556 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7557 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7558 "We should only have known counts for exiting blocks that dominate " 7559 "latch!"); 7560 7561 Ops.push_back(BECount); 7562 7563 if (Preds && !ENT.hasAlwaysTruePredicate()) 7564 Preds->add(ENT.Predicate.get()); 7565 7566 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7567 "Predicate should be always true!"); 7568 } 7569 7570 return SE->getUMinFromMismatchedTypes(Ops); 7571 } 7572 7573 /// Get the exact not taken count for this loop exit. 7574 const SCEV * 7575 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7576 ScalarEvolution *SE) const { 7577 for (auto &ENT : ExitNotTaken) 7578 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7579 return ENT.ExactNotTaken; 7580 7581 return SE->getCouldNotCompute(); 7582 } 7583 7584 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7585 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7586 for (auto &ENT : ExitNotTaken) 7587 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7588 return ENT.MaxNotTaken; 7589 7590 return SE->getCouldNotCompute(); 7591 } 7592 7593 /// getConstantMax - Get the constant max backedge taken count for the loop. 7594 const SCEV * 7595 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7596 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7597 return !ENT.hasAlwaysTruePredicate(); 7598 }; 7599 7600 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7601 return SE->getCouldNotCompute(); 7602 7603 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7604 isa<SCEVConstant>(getConstantMax())) && 7605 "No point in having a non-constant max backedge taken count!"); 7606 return getConstantMax(); 7607 } 7608 7609 const SCEV * 7610 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7611 ScalarEvolution *SE) { 7612 if (!SymbolicMax) 7613 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7614 return SymbolicMax; 7615 } 7616 7617 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7618 ScalarEvolution *SE) const { 7619 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7620 return !ENT.hasAlwaysTruePredicate(); 7621 }; 7622 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7623 } 7624 7625 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7626 return Operands.contains(S); 7627 } 7628 7629 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7630 : ExitLimit(E, E, false, None) { 7631 } 7632 7633 ScalarEvolution::ExitLimit::ExitLimit( 7634 const SCEV *E, const SCEV *M, bool MaxOrZero, 7635 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7636 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7637 // If we prove the max count is zero, so is the symbolic bound. This happens 7638 // in practice due to differences in a) how context sensitive we've chosen 7639 // to be and b) how we reason about bounds impied by UB. 7640 if (MaxNotTaken->isZero()) 7641 ExactNotTaken = MaxNotTaken; 7642 7643 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7644 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7645 "Exact is not allowed to be less precise than Max"); 7646 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7647 isa<SCEVConstant>(MaxNotTaken)) && 7648 "No point in having a non-constant max backedge taken count!"); 7649 for (auto *PredSet : PredSetList) 7650 for (auto *P : *PredSet) 7651 addPredicate(P); 7652 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7653 "Backedge count should be int"); 7654 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7655 "Max backedge count should be int"); 7656 } 7657 7658 ScalarEvolution::ExitLimit::ExitLimit( 7659 const SCEV *E, const SCEV *M, bool MaxOrZero, 7660 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7661 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7662 } 7663 7664 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7665 bool MaxOrZero) 7666 : ExitLimit(E, M, MaxOrZero, None) { 7667 } 7668 7669 class SCEVRecordOperands { 7670 SmallPtrSetImpl<const SCEV *> &Operands; 7671 7672 public: 7673 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7674 : Operands(Operands) {} 7675 bool follow(const SCEV *S) { 7676 Operands.insert(S); 7677 return true; 7678 } 7679 bool isDone() { return false; } 7680 }; 7681 7682 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7683 /// computable exit into a persistent ExitNotTakenInfo array. 7684 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7685 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7686 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7687 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7688 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7689 7690 ExitNotTaken.reserve(ExitCounts.size()); 7691 std::transform( 7692 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7693 [&](const EdgeExitInfo &EEI) { 7694 BasicBlock *ExitBB = EEI.first; 7695 const ExitLimit &EL = EEI.second; 7696 if (EL.Predicates.empty()) 7697 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7698 nullptr); 7699 7700 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7701 for (auto *Pred : EL.Predicates) 7702 Predicate->add(Pred); 7703 7704 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7705 std::move(Predicate)); 7706 }); 7707 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7708 isa<SCEVConstant>(ConstantMax)) && 7709 "No point in having a non-constant max backedge taken count!"); 7710 7711 SCEVRecordOperands RecordOperands(Operands); 7712 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7713 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7714 ST.visitAll(ConstantMax); 7715 for (auto &ENT : ExitNotTaken) 7716 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7717 ST.visitAll(ENT.ExactNotTaken); 7718 } 7719 7720 /// Compute the number of times the backedge of the specified loop will execute. 7721 ScalarEvolution::BackedgeTakenInfo 7722 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7723 bool AllowPredicates) { 7724 SmallVector<BasicBlock *, 8> ExitingBlocks; 7725 L->getExitingBlocks(ExitingBlocks); 7726 7727 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7728 7729 SmallVector<EdgeExitInfo, 4> ExitCounts; 7730 bool CouldComputeBECount = true; 7731 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7732 const SCEV *MustExitMaxBECount = nullptr; 7733 const SCEV *MayExitMaxBECount = nullptr; 7734 bool MustExitMaxOrZero = false; 7735 7736 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7737 // and compute maxBECount. 7738 // Do a union of all the predicates here. 7739 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7740 BasicBlock *ExitBB = ExitingBlocks[i]; 7741 7742 // We canonicalize untaken exits to br (constant), ignore them so that 7743 // proving an exit untaken doesn't negatively impact our ability to reason 7744 // about the loop as whole. 7745 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7746 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7747 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7748 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7749 continue; 7750 } 7751 7752 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7753 7754 assert((AllowPredicates || EL.Predicates.empty()) && 7755 "Predicated exit limit when predicates are not allowed!"); 7756 7757 // 1. For each exit that can be computed, add an entry to ExitCounts. 7758 // CouldComputeBECount is true only if all exits can be computed. 7759 if (EL.ExactNotTaken == getCouldNotCompute()) 7760 // We couldn't compute an exact value for this exit, so 7761 // we won't be able to compute an exact value for the loop. 7762 CouldComputeBECount = false; 7763 else 7764 ExitCounts.emplace_back(ExitBB, EL); 7765 7766 // 2. Derive the loop's MaxBECount from each exit's max number of 7767 // non-exiting iterations. Partition the loop exits into two kinds: 7768 // LoopMustExits and LoopMayExits. 7769 // 7770 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7771 // is a LoopMayExit. If any computable LoopMustExit is found, then 7772 // MaxBECount is the minimum EL.MaxNotTaken of computable 7773 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7774 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7775 // computable EL.MaxNotTaken. 7776 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7777 DT.dominates(ExitBB, Latch)) { 7778 if (!MustExitMaxBECount) { 7779 MustExitMaxBECount = EL.MaxNotTaken; 7780 MustExitMaxOrZero = EL.MaxOrZero; 7781 } else { 7782 MustExitMaxBECount = 7783 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7784 } 7785 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7786 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7787 MayExitMaxBECount = EL.MaxNotTaken; 7788 else { 7789 MayExitMaxBECount = 7790 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7791 } 7792 } 7793 } 7794 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7795 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7796 // The loop backedge will be taken the maximum or zero times if there's 7797 // a single exit that must be taken the maximum or zero times. 7798 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7799 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7800 MaxBECount, MaxOrZero); 7801 } 7802 7803 ScalarEvolution::ExitLimit 7804 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7805 bool AllowPredicates) { 7806 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7807 // If our exiting block does not dominate the latch, then its connection with 7808 // loop's exit limit may be far from trivial. 7809 const BasicBlock *Latch = L->getLoopLatch(); 7810 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7811 return getCouldNotCompute(); 7812 7813 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7814 Instruction *Term = ExitingBlock->getTerminator(); 7815 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7816 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7817 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7818 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7819 "It should have one successor in loop and one exit block!"); 7820 // Proceed to the next level to examine the exit condition expression. 7821 return computeExitLimitFromCond( 7822 L, BI->getCondition(), ExitIfTrue, 7823 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7824 } 7825 7826 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7827 // For switch, make sure that there is a single exit from the loop. 7828 BasicBlock *Exit = nullptr; 7829 for (auto *SBB : successors(ExitingBlock)) 7830 if (!L->contains(SBB)) { 7831 if (Exit) // Multiple exit successors. 7832 return getCouldNotCompute(); 7833 Exit = SBB; 7834 } 7835 assert(Exit && "Exiting block must have at least one exit"); 7836 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7837 /*ControlsExit=*/IsOnlyExit); 7838 } 7839 7840 return getCouldNotCompute(); 7841 } 7842 7843 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7844 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7845 bool ControlsExit, bool AllowPredicates) { 7846 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7847 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7848 ControlsExit, AllowPredicates); 7849 } 7850 7851 Optional<ScalarEvolution::ExitLimit> 7852 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7853 bool ExitIfTrue, bool ControlsExit, 7854 bool AllowPredicates) { 7855 (void)this->L; 7856 (void)this->ExitIfTrue; 7857 (void)this->AllowPredicates; 7858 7859 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7860 this->AllowPredicates == AllowPredicates && 7861 "Variance in assumed invariant key components!"); 7862 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7863 if (Itr == TripCountMap.end()) 7864 return None; 7865 return Itr->second; 7866 } 7867 7868 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7869 bool ExitIfTrue, 7870 bool ControlsExit, 7871 bool AllowPredicates, 7872 const ExitLimit &EL) { 7873 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7874 this->AllowPredicates == AllowPredicates && 7875 "Variance in assumed invariant key components!"); 7876 7877 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7878 assert(InsertResult.second && "Expected successful insertion!"); 7879 (void)InsertResult; 7880 (void)ExitIfTrue; 7881 } 7882 7883 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7884 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7885 bool ControlsExit, bool AllowPredicates) { 7886 7887 if (auto MaybeEL = 7888 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7889 return *MaybeEL; 7890 7891 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7892 ControlsExit, AllowPredicates); 7893 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7894 return EL; 7895 } 7896 7897 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7898 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7899 bool ControlsExit, bool AllowPredicates) { 7900 // Handle BinOp conditions (And, Or). 7901 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7902 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7903 return *LimitFromBinOp; 7904 7905 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7906 // Proceed to the next level to examine the icmp. 7907 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7908 ExitLimit EL = 7909 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7910 if (EL.hasFullInfo() || !AllowPredicates) 7911 return EL; 7912 7913 // Try again, but use SCEV predicates this time. 7914 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7915 /*AllowPredicates=*/true); 7916 } 7917 7918 // Check for a constant condition. These are normally stripped out by 7919 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7920 // preserve the CFG and is temporarily leaving constant conditions 7921 // in place. 7922 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7923 if (ExitIfTrue == !CI->getZExtValue()) 7924 // The backedge is always taken. 7925 return getCouldNotCompute(); 7926 else 7927 // The backedge is never taken. 7928 return getZero(CI->getType()); 7929 } 7930 7931 // If it's not an integer or pointer comparison then compute it the hard way. 7932 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7933 } 7934 7935 Optional<ScalarEvolution::ExitLimit> 7936 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7937 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7938 bool ControlsExit, bool AllowPredicates) { 7939 // Check if the controlling expression for this loop is an And or Or. 7940 Value *Op0, *Op1; 7941 bool IsAnd = false; 7942 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7943 IsAnd = true; 7944 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7945 IsAnd = false; 7946 else 7947 return None; 7948 7949 // EitherMayExit is true in these two cases: 7950 // br (and Op0 Op1), loop, exit 7951 // br (or Op0 Op1), exit, loop 7952 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7953 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7954 ControlsExit && !EitherMayExit, 7955 AllowPredicates); 7956 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7957 ControlsExit && !EitherMayExit, 7958 AllowPredicates); 7959 7960 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7961 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7962 if (isa<ConstantInt>(Op1)) 7963 return Op1 == NeutralElement ? EL0 : EL1; 7964 if (isa<ConstantInt>(Op0)) 7965 return Op0 == NeutralElement ? EL1 : EL0; 7966 7967 const SCEV *BECount = getCouldNotCompute(); 7968 const SCEV *MaxBECount = getCouldNotCompute(); 7969 if (EitherMayExit) { 7970 // Both conditions must be same for the loop to continue executing. 7971 // Choose the less conservative count. 7972 // If ExitCond is a short-circuit form (select), using 7973 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7974 // To see the detailed examples, please see 7975 // test/Analysis/ScalarEvolution/exit-count-select.ll 7976 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7977 if (!PoisonSafe) 7978 // Even if ExitCond is select, we can safely derive BECount using both 7979 // EL0 and EL1 in these cases: 7980 // (1) EL0.ExactNotTaken is non-zero 7981 // (2) EL1.ExactNotTaken is non-poison 7982 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7983 // it cannot be umin(0, ..)) 7984 // The PoisonSafe assignment below is simplified and the assertion after 7985 // BECount calculation fully guarantees the condition (3). 7986 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7987 isa<SCEVConstant>(EL1.ExactNotTaken); 7988 if (EL0.ExactNotTaken != getCouldNotCompute() && 7989 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7990 BECount = 7991 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7992 7993 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7994 // it should have been simplified to zero (see the condition (3) above) 7995 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7996 BECount->isZero()); 7997 } 7998 if (EL0.MaxNotTaken == getCouldNotCompute()) 7999 MaxBECount = EL1.MaxNotTaken; 8000 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8001 MaxBECount = EL0.MaxNotTaken; 8002 else 8003 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8004 } else { 8005 // Both conditions must be same at the same time for the loop to exit. 8006 // For now, be conservative. 8007 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8008 BECount = EL0.ExactNotTaken; 8009 } 8010 8011 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8012 // to be more aggressive when computing BECount than when computing 8013 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8014 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8015 // to not. 8016 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8017 !isa<SCEVCouldNotCompute>(BECount)) 8018 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8019 8020 return ExitLimit(BECount, MaxBECount, false, 8021 { &EL0.Predicates, &EL1.Predicates }); 8022 } 8023 8024 ScalarEvolution::ExitLimit 8025 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8026 ICmpInst *ExitCond, 8027 bool ExitIfTrue, 8028 bool ControlsExit, 8029 bool AllowPredicates) { 8030 // If the condition was exit on true, convert the condition to exit on false 8031 ICmpInst::Predicate Pred; 8032 if (!ExitIfTrue) 8033 Pred = ExitCond->getPredicate(); 8034 else 8035 Pred = ExitCond->getInversePredicate(); 8036 const ICmpInst::Predicate OriginalPred = Pred; 8037 8038 // Handle common loops like: for (X = "string"; *X; ++X) 8039 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 8040 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 8041 ExitLimit ItCnt = 8042 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 8043 if (ItCnt.hasAnyInfo()) 8044 return ItCnt; 8045 } 8046 8047 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8048 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8049 8050 // Try to evaluate any dependencies out of the loop. 8051 LHS = getSCEVAtScope(LHS, L); 8052 RHS = getSCEVAtScope(RHS, L); 8053 8054 // At this point, we would like to compute how many iterations of the 8055 // loop the predicate will return true for these inputs. 8056 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8057 // If there is a loop-invariant, force it into the RHS. 8058 std::swap(LHS, RHS); 8059 Pred = ICmpInst::getSwappedPredicate(Pred); 8060 } 8061 8062 // Simplify the operands before analyzing them. 8063 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8064 8065 // If we have a comparison of a chrec against a constant, try to use value 8066 // ranges to answer this query. 8067 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8068 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8069 if (AddRec->getLoop() == L) { 8070 // Form the constant range. 8071 ConstantRange CompRange = 8072 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8073 8074 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8075 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8076 } 8077 8078 switch (Pred) { 8079 case ICmpInst::ICMP_NE: { // while (X != Y) 8080 // Convert to: while (X-Y != 0) 8081 if (LHS->getType()->isPointerTy()) { 8082 LHS = getLosslessPtrToIntExpr(LHS); 8083 if (isa<SCEVCouldNotCompute>(LHS)) 8084 return LHS; 8085 } 8086 if (RHS->getType()->isPointerTy()) { 8087 RHS = getLosslessPtrToIntExpr(RHS); 8088 if (isa<SCEVCouldNotCompute>(RHS)) 8089 return RHS; 8090 } 8091 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8092 AllowPredicates); 8093 if (EL.hasAnyInfo()) return EL; 8094 break; 8095 } 8096 case ICmpInst::ICMP_EQ: { // while (X == Y) 8097 // Convert to: while (X-Y == 0) 8098 if (LHS->getType()->isPointerTy()) { 8099 LHS = getLosslessPtrToIntExpr(LHS); 8100 if (isa<SCEVCouldNotCompute>(LHS)) 8101 return LHS; 8102 } 8103 if (RHS->getType()->isPointerTy()) { 8104 RHS = getLosslessPtrToIntExpr(RHS); 8105 if (isa<SCEVCouldNotCompute>(RHS)) 8106 return RHS; 8107 } 8108 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8109 if (EL.hasAnyInfo()) return EL; 8110 break; 8111 } 8112 case ICmpInst::ICMP_SLT: 8113 case ICmpInst::ICMP_ULT: { // while (X < Y) 8114 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8115 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8116 AllowPredicates); 8117 if (EL.hasAnyInfo()) return EL; 8118 break; 8119 } 8120 case ICmpInst::ICMP_SGT: 8121 case ICmpInst::ICMP_UGT: { // while (X > Y) 8122 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8123 ExitLimit EL = 8124 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8125 AllowPredicates); 8126 if (EL.hasAnyInfo()) return EL; 8127 break; 8128 } 8129 default: 8130 break; 8131 } 8132 8133 auto *ExhaustiveCount = 8134 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8135 8136 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8137 return ExhaustiveCount; 8138 8139 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8140 ExitCond->getOperand(1), L, OriginalPred); 8141 } 8142 8143 ScalarEvolution::ExitLimit 8144 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8145 SwitchInst *Switch, 8146 BasicBlock *ExitingBlock, 8147 bool ControlsExit) { 8148 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8149 8150 // Give up if the exit is the default dest of a switch. 8151 if (Switch->getDefaultDest() == ExitingBlock) 8152 return getCouldNotCompute(); 8153 8154 assert(L->contains(Switch->getDefaultDest()) && 8155 "Default case must not exit the loop!"); 8156 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8157 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8158 8159 // while (X != Y) --> while (X-Y != 0) 8160 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8161 if (EL.hasAnyInfo()) 8162 return EL; 8163 8164 return getCouldNotCompute(); 8165 } 8166 8167 static ConstantInt * 8168 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8169 ScalarEvolution &SE) { 8170 const SCEV *InVal = SE.getConstant(C); 8171 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8172 assert(isa<SCEVConstant>(Val) && 8173 "Evaluation of SCEV at constant didn't fold correctly?"); 8174 return cast<SCEVConstant>(Val)->getValue(); 8175 } 8176 8177 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8178 /// compute the backedge execution count. 8179 ScalarEvolution::ExitLimit 8180 ScalarEvolution::computeLoadConstantCompareExitLimit( 8181 LoadInst *LI, 8182 Constant *RHS, 8183 const Loop *L, 8184 ICmpInst::Predicate predicate) { 8185 if (LI->isVolatile()) return getCouldNotCompute(); 8186 8187 // Check to see if the loaded pointer is a getelementptr of a global. 8188 // TODO: Use SCEV instead of manually grubbing with GEPs. 8189 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8190 if (!GEP) return getCouldNotCompute(); 8191 8192 // Make sure that it is really a constant global we are gepping, with an 8193 // initializer, and make sure the first IDX is really 0. 8194 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8195 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8196 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8197 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8198 return getCouldNotCompute(); 8199 8200 // Okay, we allow one non-constant index into the GEP instruction. 8201 Value *VarIdx = nullptr; 8202 std::vector<Constant*> Indexes; 8203 unsigned VarIdxNum = 0; 8204 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8205 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8206 Indexes.push_back(CI); 8207 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8208 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8209 VarIdx = GEP->getOperand(i); 8210 VarIdxNum = i-2; 8211 Indexes.push_back(nullptr); 8212 } 8213 8214 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8215 if (!VarIdx) 8216 return getCouldNotCompute(); 8217 8218 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8219 // Check to see if X is a loop variant variable value now. 8220 const SCEV *Idx = getSCEV(VarIdx); 8221 Idx = getSCEVAtScope(Idx, L); 8222 8223 // We can only recognize very limited forms of loop index expressions, in 8224 // particular, only affine AddRec's like {C1,+,C2}<L>. 8225 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8226 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8227 isLoopInvariant(IdxExpr, L) || 8228 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8229 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8230 return getCouldNotCompute(); 8231 8232 unsigned MaxSteps = MaxBruteForceIterations; 8233 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8234 ConstantInt *ItCst = ConstantInt::get( 8235 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8236 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8237 8238 // Form the GEP offset. 8239 Indexes[VarIdxNum] = Val; 8240 8241 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8242 Indexes); 8243 if (!Result) break; // Cannot compute! 8244 8245 // Evaluate the condition for this iteration. 8246 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8247 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8248 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8249 ++NumArrayLenItCounts; 8250 return getConstant(ItCst); // Found terminating iteration! 8251 } 8252 } 8253 return getCouldNotCompute(); 8254 } 8255 8256 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8257 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8258 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8259 if (!RHS) 8260 return getCouldNotCompute(); 8261 8262 const BasicBlock *Latch = L->getLoopLatch(); 8263 if (!Latch) 8264 return getCouldNotCompute(); 8265 8266 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8267 if (!Predecessor) 8268 return getCouldNotCompute(); 8269 8270 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8271 // Return LHS in OutLHS and shift_opt in OutOpCode. 8272 auto MatchPositiveShift = 8273 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8274 8275 using namespace PatternMatch; 8276 8277 ConstantInt *ShiftAmt; 8278 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8279 OutOpCode = Instruction::LShr; 8280 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8281 OutOpCode = Instruction::AShr; 8282 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8283 OutOpCode = Instruction::Shl; 8284 else 8285 return false; 8286 8287 return ShiftAmt->getValue().isStrictlyPositive(); 8288 }; 8289 8290 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8291 // 8292 // loop: 8293 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8294 // %iv.shifted = lshr i32 %iv, <positive constant> 8295 // 8296 // Return true on a successful match. Return the corresponding PHI node (%iv 8297 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8298 auto MatchShiftRecurrence = 8299 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8300 Optional<Instruction::BinaryOps> PostShiftOpCode; 8301 8302 { 8303 Instruction::BinaryOps OpC; 8304 Value *V; 8305 8306 // If we encounter a shift instruction, "peel off" the shift operation, 8307 // and remember that we did so. Later when we inspect %iv's backedge 8308 // value, we will make sure that the backedge value uses the same 8309 // operation. 8310 // 8311 // Note: the peeled shift operation does not have to be the same 8312 // instruction as the one feeding into the PHI's backedge value. We only 8313 // really care about it being the same *kind* of shift instruction -- 8314 // that's all that is required for our later inferences to hold. 8315 if (MatchPositiveShift(LHS, V, OpC)) { 8316 PostShiftOpCode = OpC; 8317 LHS = V; 8318 } 8319 } 8320 8321 PNOut = dyn_cast<PHINode>(LHS); 8322 if (!PNOut || PNOut->getParent() != L->getHeader()) 8323 return false; 8324 8325 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8326 Value *OpLHS; 8327 8328 return 8329 // The backedge value for the PHI node must be a shift by a positive 8330 // amount 8331 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8332 8333 // of the PHI node itself 8334 OpLHS == PNOut && 8335 8336 // and the kind of shift should be match the kind of shift we peeled 8337 // off, if any. 8338 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8339 }; 8340 8341 PHINode *PN; 8342 Instruction::BinaryOps OpCode; 8343 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8344 return getCouldNotCompute(); 8345 8346 const DataLayout &DL = getDataLayout(); 8347 8348 // The key rationale for this optimization is that for some kinds of shift 8349 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8350 // within a finite number of iterations. If the condition guarding the 8351 // backedge (in the sense that the backedge is taken if the condition is true) 8352 // is false for the value the shift recurrence stabilizes to, then we know 8353 // that the backedge is taken only a finite number of times. 8354 8355 ConstantInt *StableValue = nullptr; 8356 switch (OpCode) { 8357 default: 8358 llvm_unreachable("Impossible case!"); 8359 8360 case Instruction::AShr: { 8361 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8362 // bitwidth(K) iterations. 8363 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8364 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8365 Predecessor->getTerminator(), &DT); 8366 auto *Ty = cast<IntegerType>(RHS->getType()); 8367 if (Known.isNonNegative()) 8368 StableValue = ConstantInt::get(Ty, 0); 8369 else if (Known.isNegative()) 8370 StableValue = ConstantInt::get(Ty, -1, true); 8371 else 8372 return getCouldNotCompute(); 8373 8374 break; 8375 } 8376 case Instruction::LShr: 8377 case Instruction::Shl: 8378 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8379 // stabilize to 0 in at most bitwidth(K) iterations. 8380 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8381 break; 8382 } 8383 8384 auto *Result = 8385 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8386 assert(Result->getType()->isIntegerTy(1) && 8387 "Otherwise cannot be an operand to a branch instruction"); 8388 8389 if (Result->isZeroValue()) { 8390 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8391 const SCEV *UpperBound = 8392 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8393 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8394 } 8395 8396 return getCouldNotCompute(); 8397 } 8398 8399 /// Return true if we can constant fold an instruction of the specified type, 8400 /// assuming that all operands were constants. 8401 static bool CanConstantFold(const Instruction *I) { 8402 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8403 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8404 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8405 return true; 8406 8407 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8408 if (const Function *F = CI->getCalledFunction()) 8409 return canConstantFoldCallTo(CI, F); 8410 return false; 8411 } 8412 8413 /// Determine whether this instruction can constant evolve within this loop 8414 /// assuming its operands can all constant evolve. 8415 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8416 // An instruction outside of the loop can't be derived from a loop PHI. 8417 if (!L->contains(I)) return false; 8418 8419 if (isa<PHINode>(I)) { 8420 // We don't currently keep track of the control flow needed to evaluate 8421 // PHIs, so we cannot handle PHIs inside of loops. 8422 return L->getHeader() == I->getParent(); 8423 } 8424 8425 // If we won't be able to constant fold this expression even if the operands 8426 // are constants, bail early. 8427 return CanConstantFold(I); 8428 } 8429 8430 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8431 /// recursing through each instruction operand until reaching a loop header phi. 8432 static PHINode * 8433 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8434 DenseMap<Instruction *, PHINode *> &PHIMap, 8435 unsigned Depth) { 8436 if (Depth > MaxConstantEvolvingDepth) 8437 return nullptr; 8438 8439 // Otherwise, we can evaluate this instruction if all of its operands are 8440 // constant or derived from a PHI node themselves. 8441 PHINode *PHI = nullptr; 8442 for (Value *Op : UseInst->operands()) { 8443 if (isa<Constant>(Op)) continue; 8444 8445 Instruction *OpInst = dyn_cast<Instruction>(Op); 8446 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8447 8448 PHINode *P = dyn_cast<PHINode>(OpInst); 8449 if (!P) 8450 // If this operand is already visited, reuse the prior result. 8451 // We may have P != PHI if this is the deepest point at which the 8452 // inconsistent paths meet. 8453 P = PHIMap.lookup(OpInst); 8454 if (!P) { 8455 // Recurse and memoize the results, whether a phi is found or not. 8456 // This recursive call invalidates pointers into PHIMap. 8457 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8458 PHIMap[OpInst] = P; 8459 } 8460 if (!P) 8461 return nullptr; // Not evolving from PHI 8462 if (PHI && PHI != P) 8463 return nullptr; // Evolving from multiple different PHIs. 8464 PHI = P; 8465 } 8466 // This is a expression evolving from a constant PHI! 8467 return PHI; 8468 } 8469 8470 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8471 /// in the loop that V is derived from. We allow arbitrary operations along the 8472 /// way, but the operands of an operation must either be constants or a value 8473 /// derived from a constant PHI. If this expression does not fit with these 8474 /// constraints, return null. 8475 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8476 Instruction *I = dyn_cast<Instruction>(V); 8477 if (!I || !canConstantEvolve(I, L)) return nullptr; 8478 8479 if (PHINode *PN = dyn_cast<PHINode>(I)) 8480 return PN; 8481 8482 // Record non-constant instructions contained by the loop. 8483 DenseMap<Instruction *, PHINode *> PHIMap; 8484 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8485 } 8486 8487 /// EvaluateExpression - Given an expression that passes the 8488 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8489 /// in the loop has the value PHIVal. If we can't fold this expression for some 8490 /// reason, return null. 8491 static Constant *EvaluateExpression(Value *V, const Loop *L, 8492 DenseMap<Instruction *, Constant *> &Vals, 8493 const DataLayout &DL, 8494 const TargetLibraryInfo *TLI) { 8495 // Convenient constant check, but redundant for recursive calls. 8496 if (Constant *C = dyn_cast<Constant>(V)) return C; 8497 Instruction *I = dyn_cast<Instruction>(V); 8498 if (!I) return nullptr; 8499 8500 if (Constant *C = Vals.lookup(I)) return C; 8501 8502 // An instruction inside the loop depends on a value outside the loop that we 8503 // weren't given a mapping for, or a value such as a call inside the loop. 8504 if (!canConstantEvolve(I, L)) return nullptr; 8505 8506 // An unmapped PHI can be due to a branch or another loop inside this loop, 8507 // or due to this not being the initial iteration through a loop where we 8508 // couldn't compute the evolution of this particular PHI last time. 8509 if (isa<PHINode>(I)) return nullptr; 8510 8511 std::vector<Constant*> Operands(I->getNumOperands()); 8512 8513 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8514 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8515 if (!Operand) { 8516 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8517 if (!Operands[i]) return nullptr; 8518 continue; 8519 } 8520 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8521 Vals[Operand] = C; 8522 if (!C) return nullptr; 8523 Operands[i] = C; 8524 } 8525 8526 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8527 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8528 Operands[1], DL, TLI); 8529 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8530 if (!LI->isVolatile()) 8531 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8532 } 8533 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8534 } 8535 8536 8537 // If every incoming value to PN except the one for BB is a specific Constant, 8538 // return that, else return nullptr. 8539 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8540 Constant *IncomingVal = nullptr; 8541 8542 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8543 if (PN->getIncomingBlock(i) == BB) 8544 continue; 8545 8546 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8547 if (!CurrentVal) 8548 return nullptr; 8549 8550 if (IncomingVal != CurrentVal) { 8551 if (IncomingVal) 8552 return nullptr; 8553 IncomingVal = CurrentVal; 8554 } 8555 } 8556 8557 return IncomingVal; 8558 } 8559 8560 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8561 /// in the header of its containing loop, we know the loop executes a 8562 /// constant number of times, and the PHI node is just a recurrence 8563 /// involving constants, fold it. 8564 Constant * 8565 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8566 const APInt &BEs, 8567 const Loop *L) { 8568 auto I = ConstantEvolutionLoopExitValue.find(PN); 8569 if (I != ConstantEvolutionLoopExitValue.end()) 8570 return I->second; 8571 8572 if (BEs.ugt(MaxBruteForceIterations)) 8573 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8574 8575 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8576 8577 DenseMap<Instruction *, Constant *> CurrentIterVals; 8578 BasicBlock *Header = L->getHeader(); 8579 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8580 8581 BasicBlock *Latch = L->getLoopLatch(); 8582 if (!Latch) 8583 return nullptr; 8584 8585 for (PHINode &PHI : Header->phis()) { 8586 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8587 CurrentIterVals[&PHI] = StartCST; 8588 } 8589 if (!CurrentIterVals.count(PN)) 8590 return RetVal = nullptr; 8591 8592 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8593 8594 // Execute the loop symbolically to determine the exit value. 8595 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8596 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8597 8598 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8599 unsigned IterationNum = 0; 8600 const DataLayout &DL = getDataLayout(); 8601 for (; ; ++IterationNum) { 8602 if (IterationNum == NumIterations) 8603 return RetVal = CurrentIterVals[PN]; // Got exit value! 8604 8605 // Compute the value of the PHIs for the next iteration. 8606 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8607 DenseMap<Instruction *, Constant *> NextIterVals; 8608 Constant *NextPHI = 8609 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8610 if (!NextPHI) 8611 return nullptr; // Couldn't evaluate! 8612 NextIterVals[PN] = NextPHI; 8613 8614 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8615 8616 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8617 // cease to be able to evaluate one of them or if they stop evolving, 8618 // because that doesn't necessarily prevent us from computing PN. 8619 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8620 for (const auto &I : CurrentIterVals) { 8621 PHINode *PHI = dyn_cast<PHINode>(I.first); 8622 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8623 PHIsToCompute.emplace_back(PHI, I.second); 8624 } 8625 // We use two distinct loops because EvaluateExpression may invalidate any 8626 // iterators into CurrentIterVals. 8627 for (const auto &I : PHIsToCompute) { 8628 PHINode *PHI = I.first; 8629 Constant *&NextPHI = NextIterVals[PHI]; 8630 if (!NextPHI) { // Not already computed. 8631 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8632 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8633 } 8634 if (NextPHI != I.second) 8635 StoppedEvolving = false; 8636 } 8637 8638 // If all entries in CurrentIterVals == NextIterVals then we can stop 8639 // iterating, the loop can't continue to change. 8640 if (StoppedEvolving) 8641 return RetVal = CurrentIterVals[PN]; 8642 8643 CurrentIterVals.swap(NextIterVals); 8644 } 8645 } 8646 8647 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8648 Value *Cond, 8649 bool ExitWhen) { 8650 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8651 if (!PN) return getCouldNotCompute(); 8652 8653 // If the loop is canonicalized, the PHI will have exactly two entries. 8654 // That's the only form we support here. 8655 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8656 8657 DenseMap<Instruction *, Constant *> CurrentIterVals; 8658 BasicBlock *Header = L->getHeader(); 8659 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8660 8661 BasicBlock *Latch = L->getLoopLatch(); 8662 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8663 8664 for (PHINode &PHI : Header->phis()) { 8665 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8666 CurrentIterVals[&PHI] = StartCST; 8667 } 8668 if (!CurrentIterVals.count(PN)) 8669 return getCouldNotCompute(); 8670 8671 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8672 // the loop symbolically to determine when the condition gets a value of 8673 // "ExitWhen". 8674 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8675 const DataLayout &DL = getDataLayout(); 8676 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8677 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8678 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8679 8680 // Couldn't symbolically evaluate. 8681 if (!CondVal) return getCouldNotCompute(); 8682 8683 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8684 ++NumBruteForceTripCountsComputed; 8685 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8686 } 8687 8688 // Update all the PHI nodes for the next iteration. 8689 DenseMap<Instruction *, Constant *> NextIterVals; 8690 8691 // Create a list of which PHIs we need to compute. We want to do this before 8692 // calling EvaluateExpression on them because that may invalidate iterators 8693 // into CurrentIterVals. 8694 SmallVector<PHINode *, 8> PHIsToCompute; 8695 for (const auto &I : CurrentIterVals) { 8696 PHINode *PHI = dyn_cast<PHINode>(I.first); 8697 if (!PHI || PHI->getParent() != Header) continue; 8698 PHIsToCompute.push_back(PHI); 8699 } 8700 for (PHINode *PHI : PHIsToCompute) { 8701 Constant *&NextPHI = NextIterVals[PHI]; 8702 if (NextPHI) continue; // Already computed! 8703 8704 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8705 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8706 } 8707 CurrentIterVals.swap(NextIterVals); 8708 } 8709 8710 // Too many iterations were needed to evaluate. 8711 return getCouldNotCompute(); 8712 } 8713 8714 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8715 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8716 ValuesAtScopes[V]; 8717 // Check to see if we've folded this expression at this loop before. 8718 for (auto &LS : Values) 8719 if (LS.first == L) 8720 return LS.second ? LS.second : V; 8721 8722 Values.emplace_back(L, nullptr); 8723 8724 // Otherwise compute it. 8725 const SCEV *C = computeSCEVAtScope(V, L); 8726 for (auto &LS : reverse(ValuesAtScopes[V])) 8727 if (LS.first == L) { 8728 LS.second = C; 8729 break; 8730 } 8731 return C; 8732 } 8733 8734 /// This builds up a Constant using the ConstantExpr interface. That way, we 8735 /// will return Constants for objects which aren't represented by a 8736 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8737 /// Returns NULL if the SCEV isn't representable as a Constant. 8738 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8739 switch (V->getSCEVType()) { 8740 case scCouldNotCompute: 8741 case scAddRecExpr: 8742 return nullptr; 8743 case scConstant: 8744 return cast<SCEVConstant>(V)->getValue(); 8745 case scUnknown: 8746 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8747 case scSignExtend: { 8748 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8749 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8750 return ConstantExpr::getSExt(CastOp, SS->getType()); 8751 return nullptr; 8752 } 8753 case scZeroExtend: { 8754 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8755 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8756 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8757 return nullptr; 8758 } 8759 case scPtrToInt: { 8760 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8761 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8762 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8763 8764 return nullptr; 8765 } 8766 case scTruncate: { 8767 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8768 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8769 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8770 return nullptr; 8771 } 8772 case scAddExpr: { 8773 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8774 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8775 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8776 unsigned AS = PTy->getAddressSpace(); 8777 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8778 C = ConstantExpr::getBitCast(C, DestPtrTy); 8779 } 8780 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8781 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8782 if (!C2) 8783 return nullptr; 8784 8785 // First pointer! 8786 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8787 unsigned AS = C2->getType()->getPointerAddressSpace(); 8788 std::swap(C, C2); 8789 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8790 // The offsets have been converted to bytes. We can add bytes to an 8791 // i8* by GEP with the byte count in the first index. 8792 C = ConstantExpr::getBitCast(C, DestPtrTy); 8793 } 8794 8795 // Don't bother trying to sum two pointers. We probably can't 8796 // statically compute a load that results from it anyway. 8797 if (C2->getType()->isPointerTy()) 8798 return nullptr; 8799 8800 if (C->getType()->isPointerTy()) { 8801 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8802 C, C2); 8803 } else { 8804 C = ConstantExpr::getAdd(C, C2); 8805 } 8806 } 8807 return C; 8808 } 8809 return nullptr; 8810 } 8811 case scMulExpr: { 8812 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8813 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8814 // Don't bother with pointers at all. 8815 if (C->getType()->isPointerTy()) 8816 return nullptr; 8817 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8818 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8819 if (!C2 || C2->getType()->isPointerTy()) 8820 return nullptr; 8821 C = ConstantExpr::getMul(C, C2); 8822 } 8823 return C; 8824 } 8825 return nullptr; 8826 } 8827 case scUDivExpr: { 8828 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8829 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8830 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8831 if (LHS->getType() == RHS->getType()) 8832 return ConstantExpr::getUDiv(LHS, RHS); 8833 return nullptr; 8834 } 8835 case scSMaxExpr: 8836 case scUMaxExpr: 8837 case scSMinExpr: 8838 case scUMinExpr: 8839 return nullptr; // TODO: smax, umax, smin, umax. 8840 } 8841 llvm_unreachable("Unknown SCEV kind!"); 8842 } 8843 8844 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8845 if (isa<SCEVConstant>(V)) return V; 8846 8847 // If this instruction is evolved from a constant-evolving PHI, compute the 8848 // exit value from the loop without using SCEVs. 8849 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8850 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8851 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8852 const Loop *CurrLoop = this->LI[I->getParent()]; 8853 // Looking for loop exit value. 8854 if (CurrLoop && CurrLoop->getParentLoop() == L && 8855 PN->getParent() == CurrLoop->getHeader()) { 8856 // Okay, there is no closed form solution for the PHI node. Check 8857 // to see if the loop that contains it has a known backedge-taken 8858 // count. If so, we may be able to force computation of the exit 8859 // value. 8860 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8861 // This trivial case can show up in some degenerate cases where 8862 // the incoming IR has not yet been fully simplified. 8863 if (BackedgeTakenCount->isZero()) { 8864 Value *InitValue = nullptr; 8865 bool MultipleInitValues = false; 8866 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8867 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8868 if (!InitValue) 8869 InitValue = PN->getIncomingValue(i); 8870 else if (InitValue != PN->getIncomingValue(i)) { 8871 MultipleInitValues = true; 8872 break; 8873 } 8874 } 8875 } 8876 if (!MultipleInitValues && InitValue) 8877 return getSCEV(InitValue); 8878 } 8879 // Do we have a loop invariant value flowing around the backedge 8880 // for a loop which must execute the backedge? 8881 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8882 isKnownPositive(BackedgeTakenCount) && 8883 PN->getNumIncomingValues() == 2) { 8884 8885 unsigned InLoopPred = 8886 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8887 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8888 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8889 return getSCEV(BackedgeVal); 8890 } 8891 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8892 // Okay, we know how many times the containing loop executes. If 8893 // this is a constant evolving PHI node, get the final value at 8894 // the specified iteration number. 8895 Constant *RV = getConstantEvolutionLoopExitValue( 8896 PN, BTCC->getAPInt(), CurrLoop); 8897 if (RV) return getSCEV(RV); 8898 } 8899 } 8900 8901 // If there is a single-input Phi, evaluate it at our scope. If we can 8902 // prove that this replacement does not break LCSSA form, use new value. 8903 if (PN->getNumOperands() == 1) { 8904 const SCEV *Input = getSCEV(PN->getOperand(0)); 8905 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8906 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8907 // for the simplest case just support constants. 8908 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8909 } 8910 } 8911 8912 // Okay, this is an expression that we cannot symbolically evaluate 8913 // into a SCEV. Check to see if it's possible to symbolically evaluate 8914 // the arguments into constants, and if so, try to constant propagate the 8915 // result. This is particularly useful for computing loop exit values. 8916 if (CanConstantFold(I)) { 8917 SmallVector<Constant *, 4> Operands; 8918 bool MadeImprovement = false; 8919 for (Value *Op : I->operands()) { 8920 if (Constant *C = dyn_cast<Constant>(Op)) { 8921 Operands.push_back(C); 8922 continue; 8923 } 8924 8925 // If any of the operands is non-constant and if they are 8926 // non-integer and non-pointer, don't even try to analyze them 8927 // with scev techniques. 8928 if (!isSCEVable(Op->getType())) 8929 return V; 8930 8931 const SCEV *OrigV = getSCEV(Op); 8932 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8933 MadeImprovement |= OrigV != OpV; 8934 8935 Constant *C = BuildConstantFromSCEV(OpV); 8936 if (!C) return V; 8937 if (C->getType() != Op->getType()) 8938 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8939 Op->getType(), 8940 false), 8941 C, Op->getType()); 8942 Operands.push_back(C); 8943 } 8944 8945 // Check to see if getSCEVAtScope actually made an improvement. 8946 if (MadeImprovement) { 8947 Constant *C = nullptr; 8948 const DataLayout &DL = getDataLayout(); 8949 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8950 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8951 Operands[1], DL, &TLI); 8952 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8953 if (!Load->isVolatile()) 8954 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8955 DL); 8956 } else 8957 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8958 if (!C) return V; 8959 return getSCEV(C); 8960 } 8961 } 8962 } 8963 8964 // This is some other type of SCEVUnknown, just return it. 8965 return V; 8966 } 8967 8968 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8969 // Avoid performing the look-up in the common case where the specified 8970 // expression has no loop-variant portions. 8971 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8972 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8973 if (OpAtScope != Comm->getOperand(i)) { 8974 // Okay, at least one of these operands is loop variant but might be 8975 // foldable. Build a new instance of the folded commutative expression. 8976 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8977 Comm->op_begin()+i); 8978 NewOps.push_back(OpAtScope); 8979 8980 for (++i; i != e; ++i) { 8981 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8982 NewOps.push_back(OpAtScope); 8983 } 8984 if (isa<SCEVAddExpr>(Comm)) 8985 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8986 if (isa<SCEVMulExpr>(Comm)) 8987 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8988 if (isa<SCEVMinMaxExpr>(Comm)) 8989 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8990 llvm_unreachable("Unknown commutative SCEV type!"); 8991 } 8992 } 8993 // If we got here, all operands are loop invariant. 8994 return Comm; 8995 } 8996 8997 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8998 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8999 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9000 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9001 return Div; // must be loop invariant 9002 return getUDivExpr(LHS, RHS); 9003 } 9004 9005 // If this is a loop recurrence for a loop that does not contain L, then we 9006 // are dealing with the final value computed by the loop. 9007 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9008 // First, attempt to evaluate each operand. 9009 // Avoid performing the look-up in the common case where the specified 9010 // expression has no loop-variant portions. 9011 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9012 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9013 if (OpAtScope == AddRec->getOperand(i)) 9014 continue; 9015 9016 // Okay, at least one of these operands is loop variant but might be 9017 // foldable. Build a new instance of the folded commutative expression. 9018 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9019 AddRec->op_begin()+i); 9020 NewOps.push_back(OpAtScope); 9021 for (++i; i != e; ++i) 9022 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9023 9024 const SCEV *FoldedRec = 9025 getAddRecExpr(NewOps, AddRec->getLoop(), 9026 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9027 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9028 // The addrec may be folded to a nonrecurrence, for example, if the 9029 // induction variable is multiplied by zero after constant folding. Go 9030 // ahead and return the folded value. 9031 if (!AddRec) 9032 return FoldedRec; 9033 break; 9034 } 9035 9036 // If the scope is outside the addrec's loop, evaluate it by using the 9037 // loop exit value of the addrec. 9038 if (!AddRec->getLoop()->contains(L)) { 9039 // To evaluate this recurrence, we need to know how many times the AddRec 9040 // loop iterates. Compute this now. 9041 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9042 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9043 9044 // Then, evaluate the AddRec. 9045 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9046 } 9047 9048 return AddRec; 9049 } 9050 9051 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9052 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9053 if (Op == Cast->getOperand()) 9054 return Cast; // must be loop invariant 9055 return getZeroExtendExpr(Op, Cast->getType()); 9056 } 9057 9058 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9059 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9060 if (Op == Cast->getOperand()) 9061 return Cast; // must be loop invariant 9062 return getSignExtendExpr(Op, Cast->getType()); 9063 } 9064 9065 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9066 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9067 if (Op == Cast->getOperand()) 9068 return Cast; // must be loop invariant 9069 return getTruncateExpr(Op, Cast->getType()); 9070 } 9071 9072 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9073 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9074 if (Op == Cast->getOperand()) 9075 return Cast; // must be loop invariant 9076 return getPtrToIntExpr(Op, Cast->getType()); 9077 } 9078 9079 llvm_unreachable("Unknown SCEV type!"); 9080 } 9081 9082 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9083 return getSCEVAtScope(getSCEV(V), L); 9084 } 9085 9086 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9087 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9088 return stripInjectiveFunctions(ZExt->getOperand()); 9089 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9090 return stripInjectiveFunctions(SExt->getOperand()); 9091 return S; 9092 } 9093 9094 /// Finds the minimum unsigned root of the following equation: 9095 /// 9096 /// A * X = B (mod N) 9097 /// 9098 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9099 /// A and B isn't important. 9100 /// 9101 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9102 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9103 ScalarEvolution &SE) { 9104 uint32_t BW = A.getBitWidth(); 9105 assert(BW == SE.getTypeSizeInBits(B->getType())); 9106 assert(A != 0 && "A must be non-zero."); 9107 9108 // 1. D = gcd(A, N) 9109 // 9110 // The gcd of A and N may have only one prime factor: 2. The number of 9111 // trailing zeros in A is its multiplicity 9112 uint32_t Mult2 = A.countTrailingZeros(); 9113 // D = 2^Mult2 9114 9115 // 2. Check if B is divisible by D. 9116 // 9117 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9118 // is not less than multiplicity of this prime factor for D. 9119 if (SE.GetMinTrailingZeros(B) < Mult2) 9120 return SE.getCouldNotCompute(); 9121 9122 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9123 // modulo (N / D). 9124 // 9125 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9126 // (N / D) in general. The inverse itself always fits into BW bits, though, 9127 // so we immediately truncate it. 9128 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9129 APInt Mod(BW + 1, 0); 9130 Mod.setBit(BW - Mult2); // Mod = N / D 9131 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9132 9133 // 4. Compute the minimum unsigned root of the equation: 9134 // I * (B / D) mod (N / D) 9135 // To simplify the computation, we factor out the divide by D: 9136 // (I * B mod N) / D 9137 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9138 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9139 } 9140 9141 /// For a given quadratic addrec, generate coefficients of the corresponding 9142 /// quadratic equation, multiplied by a common value to ensure that they are 9143 /// integers. 9144 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9145 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9146 /// were multiplied by, and BitWidth is the bit width of the original addrec 9147 /// coefficients. 9148 /// This function returns None if the addrec coefficients are not compile- 9149 /// time constants. 9150 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9151 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9152 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9153 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9154 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9155 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9156 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9157 << *AddRec << '\n'); 9158 9159 // We currently can only solve this if the coefficients are constants. 9160 if (!LC || !MC || !NC) { 9161 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9162 return None; 9163 } 9164 9165 APInt L = LC->getAPInt(); 9166 APInt M = MC->getAPInt(); 9167 APInt N = NC->getAPInt(); 9168 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9169 9170 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9171 unsigned NewWidth = BitWidth + 1; 9172 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9173 << BitWidth << '\n'); 9174 // The sign-extension (as opposed to a zero-extension) here matches the 9175 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9176 N = N.sext(NewWidth); 9177 M = M.sext(NewWidth); 9178 L = L.sext(NewWidth); 9179 9180 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9181 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9182 // L+M, L+2M+N, L+3M+3N, ... 9183 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9184 // 9185 // The equation Acc = 0 is then 9186 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9187 // In a quadratic form it becomes: 9188 // N n^2 + (2M-N) n + 2L = 0. 9189 9190 APInt A = N; 9191 APInt B = 2 * M - A; 9192 APInt C = 2 * L; 9193 APInt T = APInt(NewWidth, 2); 9194 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9195 << "x + " << C << ", coeff bw: " << NewWidth 9196 << ", multiplied by " << T << '\n'); 9197 return std::make_tuple(A, B, C, T, BitWidth); 9198 } 9199 9200 /// Helper function to compare optional APInts: 9201 /// (a) if X and Y both exist, return min(X, Y), 9202 /// (b) if neither X nor Y exist, return None, 9203 /// (c) if exactly one of X and Y exists, return that value. 9204 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9205 if (X.hasValue() && Y.hasValue()) { 9206 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9207 APInt XW = X->sextOrSelf(W); 9208 APInt YW = Y->sextOrSelf(W); 9209 return XW.slt(YW) ? *X : *Y; 9210 } 9211 if (!X.hasValue() && !Y.hasValue()) 9212 return None; 9213 return X.hasValue() ? *X : *Y; 9214 } 9215 9216 /// Helper function to truncate an optional APInt to a given BitWidth. 9217 /// When solving addrec-related equations, it is preferable to return a value 9218 /// that has the same bit width as the original addrec's coefficients. If the 9219 /// solution fits in the original bit width, truncate it (except for i1). 9220 /// Returning a value of a different bit width may inhibit some optimizations. 9221 /// 9222 /// In general, a solution to a quadratic equation generated from an addrec 9223 /// may require BW+1 bits, where BW is the bit width of the addrec's 9224 /// coefficients. The reason is that the coefficients of the quadratic 9225 /// equation are BW+1 bits wide (to avoid truncation when converting from 9226 /// the addrec to the equation). 9227 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9228 if (!X.hasValue()) 9229 return None; 9230 unsigned W = X->getBitWidth(); 9231 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9232 return X->trunc(BitWidth); 9233 return X; 9234 } 9235 9236 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9237 /// iterations. The values L, M, N are assumed to be signed, and they 9238 /// should all have the same bit widths. 9239 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9240 /// where BW is the bit width of the addrec's coefficients. 9241 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9242 /// returned as such, otherwise the bit width of the returned value may 9243 /// be greater than BW. 9244 /// 9245 /// This function returns None if 9246 /// (a) the addrec coefficients are not constant, or 9247 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9248 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9249 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9250 static Optional<APInt> 9251 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9252 APInt A, B, C, M; 9253 unsigned BitWidth; 9254 auto T = GetQuadraticEquation(AddRec); 9255 if (!T.hasValue()) 9256 return None; 9257 9258 std::tie(A, B, C, M, BitWidth) = *T; 9259 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9260 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9261 if (!X.hasValue()) 9262 return None; 9263 9264 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9265 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9266 if (!V->isZero()) 9267 return None; 9268 9269 return TruncIfPossible(X, BitWidth); 9270 } 9271 9272 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9273 /// iterations. The values M, N are assumed to be signed, and they 9274 /// should all have the same bit widths. 9275 /// Find the least n such that c(n) does not belong to the given range, 9276 /// while c(n-1) does. 9277 /// 9278 /// This function returns None if 9279 /// (a) the addrec coefficients are not constant, or 9280 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9281 /// bounds of the range. 9282 static Optional<APInt> 9283 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9284 const ConstantRange &Range, ScalarEvolution &SE) { 9285 assert(AddRec->getOperand(0)->isZero() && 9286 "Starting value of addrec should be 0"); 9287 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9288 << Range << ", addrec " << *AddRec << '\n'); 9289 // This case is handled in getNumIterationsInRange. Here we can assume that 9290 // we start in the range. 9291 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9292 "Addrec's initial value should be in range"); 9293 9294 APInt A, B, C, M; 9295 unsigned BitWidth; 9296 auto T = GetQuadraticEquation(AddRec); 9297 if (!T.hasValue()) 9298 return None; 9299 9300 // Be careful about the return value: there can be two reasons for not 9301 // returning an actual number. First, if no solutions to the equations 9302 // were found, and second, if the solutions don't leave the given range. 9303 // The first case means that the actual solution is "unknown", the second 9304 // means that it's known, but not valid. If the solution is unknown, we 9305 // cannot make any conclusions. 9306 // Return a pair: the optional solution and a flag indicating if the 9307 // solution was found. 9308 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9309 // Solve for signed overflow and unsigned overflow, pick the lower 9310 // solution. 9311 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9312 << Bound << " (before multiplying by " << M << ")\n"); 9313 Bound *= M; // The quadratic equation multiplier. 9314 9315 Optional<APInt> SO = None; 9316 if (BitWidth > 1) { 9317 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9318 "signed overflow\n"); 9319 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9320 } 9321 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9322 "unsigned overflow\n"); 9323 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9324 BitWidth+1); 9325 9326 auto LeavesRange = [&] (const APInt &X) { 9327 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9328 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9329 if (Range.contains(V0->getValue())) 9330 return false; 9331 // X should be at least 1, so X-1 is non-negative. 9332 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9333 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9334 if (Range.contains(V1->getValue())) 9335 return true; 9336 return false; 9337 }; 9338 9339 // If SolveQuadraticEquationWrap returns None, it means that there can 9340 // be a solution, but the function failed to find it. We cannot treat it 9341 // as "no solution". 9342 if (!SO.hasValue() || !UO.hasValue()) 9343 return { None, false }; 9344 9345 // Check the smaller value first to see if it leaves the range. 9346 // At this point, both SO and UO must have values. 9347 Optional<APInt> Min = MinOptional(SO, UO); 9348 if (LeavesRange(*Min)) 9349 return { Min, true }; 9350 Optional<APInt> Max = Min == SO ? UO : SO; 9351 if (LeavesRange(*Max)) 9352 return { Max, true }; 9353 9354 // Solutions were found, but were eliminated, hence the "true". 9355 return { None, true }; 9356 }; 9357 9358 std::tie(A, B, C, M, BitWidth) = *T; 9359 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9360 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9361 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9362 auto SL = SolveForBoundary(Lower); 9363 auto SU = SolveForBoundary(Upper); 9364 // If any of the solutions was unknown, no meaninigful conclusions can 9365 // be made. 9366 if (!SL.second || !SU.second) 9367 return None; 9368 9369 // Claim: The correct solution is not some value between Min and Max. 9370 // 9371 // Justification: Assuming that Min and Max are different values, one of 9372 // them is when the first signed overflow happens, the other is when the 9373 // first unsigned overflow happens. Crossing the range boundary is only 9374 // possible via an overflow (treating 0 as a special case of it, modeling 9375 // an overflow as crossing k*2^W for some k). 9376 // 9377 // The interesting case here is when Min was eliminated as an invalid 9378 // solution, but Max was not. The argument is that if there was another 9379 // overflow between Min and Max, it would also have been eliminated if 9380 // it was considered. 9381 // 9382 // For a given boundary, it is possible to have two overflows of the same 9383 // type (signed/unsigned) without having the other type in between: this 9384 // can happen when the vertex of the parabola is between the iterations 9385 // corresponding to the overflows. This is only possible when the two 9386 // overflows cross k*2^W for the same k. In such case, if the second one 9387 // left the range (and was the first one to do so), the first overflow 9388 // would have to enter the range, which would mean that either we had left 9389 // the range before or that we started outside of it. Both of these cases 9390 // are contradictions. 9391 // 9392 // Claim: In the case where SolveForBoundary returns None, the correct 9393 // solution is not some value between the Max for this boundary and the 9394 // Min of the other boundary. 9395 // 9396 // Justification: Assume that we had such Max_A and Min_B corresponding 9397 // to range boundaries A and B and such that Max_A < Min_B. If there was 9398 // a solution between Max_A and Min_B, it would have to be caused by an 9399 // overflow corresponding to either A or B. It cannot correspond to B, 9400 // since Min_B is the first occurrence of such an overflow. If it 9401 // corresponded to A, it would have to be either a signed or an unsigned 9402 // overflow that is larger than both eliminated overflows for A. But 9403 // between the eliminated overflows and this overflow, the values would 9404 // cover the entire value space, thus crossing the other boundary, which 9405 // is a contradiction. 9406 9407 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9408 } 9409 9410 ScalarEvolution::ExitLimit 9411 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9412 bool AllowPredicates) { 9413 9414 // This is only used for loops with a "x != y" exit test. The exit condition 9415 // is now expressed as a single expression, V = x-y. So the exit test is 9416 // effectively V != 0. We know and take advantage of the fact that this 9417 // expression only being used in a comparison by zero context. 9418 9419 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9420 // If the value is a constant 9421 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9422 // If the value is already zero, the branch will execute zero times. 9423 if (C->getValue()->isZero()) return C; 9424 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9425 } 9426 9427 const SCEVAddRecExpr *AddRec = 9428 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9429 9430 if (!AddRec && AllowPredicates) 9431 // Try to make this an AddRec using runtime tests, in the first X 9432 // iterations of this loop, where X is the SCEV expression found by the 9433 // algorithm below. 9434 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9435 9436 if (!AddRec || AddRec->getLoop() != L) 9437 return getCouldNotCompute(); 9438 9439 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9440 // the quadratic equation to solve it. 9441 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9442 // We can only use this value if the chrec ends up with an exact zero 9443 // value at this index. When solving for "X*X != 5", for example, we 9444 // should not accept a root of 2. 9445 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9446 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9447 return ExitLimit(R, R, false, Predicates); 9448 } 9449 return getCouldNotCompute(); 9450 } 9451 9452 // Otherwise we can only handle this if it is affine. 9453 if (!AddRec->isAffine()) 9454 return getCouldNotCompute(); 9455 9456 // If this is an affine expression, the execution count of this branch is 9457 // the minimum unsigned root of the following equation: 9458 // 9459 // Start + Step*N = 0 (mod 2^BW) 9460 // 9461 // equivalent to: 9462 // 9463 // Step*N = -Start (mod 2^BW) 9464 // 9465 // where BW is the common bit width of Start and Step. 9466 9467 // Get the initial value for the loop. 9468 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9469 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9470 9471 // For now we handle only constant steps. 9472 // 9473 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9474 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9475 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9476 // We have not yet seen any such cases. 9477 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9478 if (!StepC || StepC->getValue()->isZero()) 9479 return getCouldNotCompute(); 9480 9481 // For positive steps (counting up until unsigned overflow): 9482 // N = -Start/Step (as unsigned) 9483 // For negative steps (counting down to zero): 9484 // N = Start/-Step 9485 // First compute the unsigned distance from zero in the direction of Step. 9486 bool CountDown = StepC->getAPInt().isNegative(); 9487 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9488 9489 // Handle unitary steps, which cannot wraparound. 9490 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9491 // N = Distance (as unsigned) 9492 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9493 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9494 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9495 if (MaxBECountBase.ult(MaxBECount)) 9496 MaxBECount = MaxBECountBase; 9497 9498 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9499 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9500 // case, and see if we can improve the bound. 9501 // 9502 // Explicitly handling this here is necessary because getUnsignedRange 9503 // isn't context-sensitive; it doesn't know that we only care about the 9504 // range inside the loop. 9505 const SCEV *Zero = getZero(Distance->getType()); 9506 const SCEV *One = getOne(Distance->getType()); 9507 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9508 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9509 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9510 // as "unsigned_max(Distance + 1) - 1". 9511 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9512 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9513 } 9514 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9515 } 9516 9517 // If the condition controls loop exit (the loop exits only if the expression 9518 // is true) and the addition is no-wrap we can use unsigned divide to 9519 // compute the backedge count. In this case, the step may not divide the 9520 // distance, but we don't care because if the condition is "missed" the loop 9521 // will have undefined behavior due to wrapping. 9522 if (ControlsExit && AddRec->hasNoSelfWrap() && 9523 loopHasNoAbnormalExits(AddRec->getLoop())) { 9524 const SCEV *Exact = 9525 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9526 const SCEV *Max = getCouldNotCompute(); 9527 if (Exact != getCouldNotCompute()) { 9528 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9529 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9530 if (BaseMaxInt.ult(MaxInt)) 9531 Max = getConstant(BaseMaxInt); 9532 else 9533 Max = getConstant(MaxInt); 9534 } 9535 return ExitLimit(Exact, Max, false, Predicates); 9536 } 9537 9538 // Solve the general equation. 9539 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9540 getNegativeSCEV(Start), *this); 9541 const SCEV *M = E == getCouldNotCompute() 9542 ? E 9543 : getConstant(getUnsignedRangeMax(E)); 9544 return ExitLimit(E, M, false, Predicates); 9545 } 9546 9547 ScalarEvolution::ExitLimit 9548 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9549 // Loops that look like: while (X == 0) are very strange indeed. We don't 9550 // handle them yet except for the trivial case. This could be expanded in the 9551 // future as needed. 9552 9553 // If the value is a constant, check to see if it is known to be non-zero 9554 // already. If so, the backedge will execute zero times. 9555 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9556 if (!C->getValue()->isZero()) 9557 return getZero(C->getType()); 9558 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9559 } 9560 9561 // We could implement others, but I really doubt anyone writes loops like 9562 // this, and if they did, they would already be constant folded. 9563 return getCouldNotCompute(); 9564 } 9565 9566 std::pair<const BasicBlock *, const BasicBlock *> 9567 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9568 const { 9569 // If the block has a unique predecessor, then there is no path from the 9570 // predecessor to the block that does not go through the direct edge 9571 // from the predecessor to the block. 9572 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9573 return {Pred, BB}; 9574 9575 // A loop's header is defined to be a block that dominates the loop. 9576 // If the header has a unique predecessor outside the loop, it must be 9577 // a block that has exactly one successor that can reach the loop. 9578 if (const Loop *L = LI.getLoopFor(BB)) 9579 return {L->getLoopPredecessor(), L->getHeader()}; 9580 9581 return {nullptr, nullptr}; 9582 } 9583 9584 /// SCEV structural equivalence is usually sufficient for testing whether two 9585 /// expressions are equal, however for the purposes of looking for a condition 9586 /// guarding a loop, it can be useful to be a little more general, since a 9587 /// front-end may have replicated the controlling expression. 9588 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9589 // Quick check to see if they are the same SCEV. 9590 if (A == B) return true; 9591 9592 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9593 // Not all instructions that are "identical" compute the same value. For 9594 // instance, two distinct alloca instructions allocating the same type are 9595 // identical and do not read memory; but compute distinct values. 9596 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9597 }; 9598 9599 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9600 // two different instructions with the same value. Check for this case. 9601 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9602 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9603 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9604 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9605 if (ComputesEqualValues(AI, BI)) 9606 return true; 9607 9608 // Otherwise assume they may have a different value. 9609 return false; 9610 } 9611 9612 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9613 const SCEV *&LHS, const SCEV *&RHS, 9614 unsigned Depth) { 9615 bool Changed = false; 9616 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9617 // '0 != 0'. 9618 auto TrivialCase = [&](bool TriviallyTrue) { 9619 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9620 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9621 return true; 9622 }; 9623 // If we hit the max recursion limit bail out. 9624 if (Depth >= 3) 9625 return false; 9626 9627 // Canonicalize a constant to the right side. 9628 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9629 // Check for both operands constant. 9630 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9631 if (ConstantExpr::getICmp(Pred, 9632 LHSC->getValue(), 9633 RHSC->getValue())->isNullValue()) 9634 return TrivialCase(false); 9635 else 9636 return TrivialCase(true); 9637 } 9638 // Otherwise swap the operands to put the constant on the right. 9639 std::swap(LHS, RHS); 9640 Pred = ICmpInst::getSwappedPredicate(Pred); 9641 Changed = true; 9642 } 9643 9644 // If we're comparing an addrec with a value which is loop-invariant in the 9645 // addrec's loop, put the addrec on the left. Also make a dominance check, 9646 // as both operands could be addrecs loop-invariant in each other's loop. 9647 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9648 const Loop *L = AR->getLoop(); 9649 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9650 std::swap(LHS, RHS); 9651 Pred = ICmpInst::getSwappedPredicate(Pred); 9652 Changed = true; 9653 } 9654 } 9655 9656 // If there's a constant operand, canonicalize comparisons with boundary 9657 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9658 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9659 const APInt &RA = RC->getAPInt(); 9660 9661 bool SimplifiedByConstantRange = false; 9662 9663 if (!ICmpInst::isEquality(Pred)) { 9664 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9665 if (ExactCR.isFullSet()) 9666 return TrivialCase(true); 9667 else if (ExactCR.isEmptySet()) 9668 return TrivialCase(false); 9669 9670 APInt NewRHS; 9671 CmpInst::Predicate NewPred; 9672 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9673 ICmpInst::isEquality(NewPred)) { 9674 // We were able to convert an inequality to an equality. 9675 Pred = NewPred; 9676 RHS = getConstant(NewRHS); 9677 Changed = SimplifiedByConstantRange = true; 9678 } 9679 } 9680 9681 if (!SimplifiedByConstantRange) { 9682 switch (Pred) { 9683 default: 9684 break; 9685 case ICmpInst::ICMP_EQ: 9686 case ICmpInst::ICMP_NE: 9687 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9688 if (!RA) 9689 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9690 if (const SCEVMulExpr *ME = 9691 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9692 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9693 ME->getOperand(0)->isAllOnesValue()) { 9694 RHS = AE->getOperand(1); 9695 LHS = ME->getOperand(1); 9696 Changed = true; 9697 } 9698 break; 9699 9700 9701 // The "Should have been caught earlier!" messages refer to the fact 9702 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9703 // should have fired on the corresponding cases, and canonicalized the 9704 // check to trivial case. 9705 9706 case ICmpInst::ICMP_UGE: 9707 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9708 Pred = ICmpInst::ICMP_UGT; 9709 RHS = getConstant(RA - 1); 9710 Changed = true; 9711 break; 9712 case ICmpInst::ICMP_ULE: 9713 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9714 Pred = ICmpInst::ICMP_ULT; 9715 RHS = getConstant(RA + 1); 9716 Changed = true; 9717 break; 9718 case ICmpInst::ICMP_SGE: 9719 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9720 Pred = ICmpInst::ICMP_SGT; 9721 RHS = getConstant(RA - 1); 9722 Changed = true; 9723 break; 9724 case ICmpInst::ICMP_SLE: 9725 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9726 Pred = ICmpInst::ICMP_SLT; 9727 RHS = getConstant(RA + 1); 9728 Changed = true; 9729 break; 9730 } 9731 } 9732 } 9733 9734 // Check for obvious equality. 9735 if (HasSameValue(LHS, RHS)) { 9736 if (ICmpInst::isTrueWhenEqual(Pred)) 9737 return TrivialCase(true); 9738 if (ICmpInst::isFalseWhenEqual(Pred)) 9739 return TrivialCase(false); 9740 } 9741 9742 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9743 // adding or subtracting 1 from one of the operands. 9744 switch (Pred) { 9745 case ICmpInst::ICMP_SLE: 9746 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9747 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9748 SCEV::FlagNSW); 9749 Pred = ICmpInst::ICMP_SLT; 9750 Changed = true; 9751 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9752 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9753 SCEV::FlagNSW); 9754 Pred = ICmpInst::ICMP_SLT; 9755 Changed = true; 9756 } 9757 break; 9758 case ICmpInst::ICMP_SGE: 9759 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9760 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9761 SCEV::FlagNSW); 9762 Pred = ICmpInst::ICMP_SGT; 9763 Changed = true; 9764 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9765 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9766 SCEV::FlagNSW); 9767 Pred = ICmpInst::ICMP_SGT; 9768 Changed = true; 9769 } 9770 break; 9771 case ICmpInst::ICMP_ULE: 9772 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9773 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9774 SCEV::FlagNUW); 9775 Pred = ICmpInst::ICMP_ULT; 9776 Changed = true; 9777 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9778 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9779 Pred = ICmpInst::ICMP_ULT; 9780 Changed = true; 9781 } 9782 break; 9783 case ICmpInst::ICMP_UGE: 9784 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9785 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9786 Pred = ICmpInst::ICMP_UGT; 9787 Changed = true; 9788 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9789 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9790 SCEV::FlagNUW); 9791 Pred = ICmpInst::ICMP_UGT; 9792 Changed = true; 9793 } 9794 break; 9795 default: 9796 break; 9797 } 9798 9799 // TODO: More simplifications are possible here. 9800 9801 // Recursively simplify until we either hit a recursion limit or nothing 9802 // changes. 9803 if (Changed) 9804 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9805 9806 return Changed; 9807 } 9808 9809 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9810 return getSignedRangeMax(S).isNegative(); 9811 } 9812 9813 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9814 return getSignedRangeMin(S).isStrictlyPositive(); 9815 } 9816 9817 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9818 return !getSignedRangeMin(S).isNegative(); 9819 } 9820 9821 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9822 return !getSignedRangeMax(S).isStrictlyPositive(); 9823 } 9824 9825 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9826 return getUnsignedRangeMin(S) != 0; 9827 } 9828 9829 std::pair<const SCEV *, const SCEV *> 9830 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9831 // Compute SCEV on entry of loop L. 9832 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9833 if (Start == getCouldNotCompute()) 9834 return { Start, Start }; 9835 // Compute post increment SCEV for loop L. 9836 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9837 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9838 return { Start, PostInc }; 9839 } 9840 9841 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9842 const SCEV *LHS, const SCEV *RHS) { 9843 // First collect all loops. 9844 SmallPtrSet<const Loop *, 8> LoopsUsed; 9845 getUsedLoops(LHS, LoopsUsed); 9846 getUsedLoops(RHS, LoopsUsed); 9847 9848 if (LoopsUsed.empty()) 9849 return false; 9850 9851 // Domination relationship must be a linear order on collected loops. 9852 #ifndef NDEBUG 9853 for (auto *L1 : LoopsUsed) 9854 for (auto *L2 : LoopsUsed) 9855 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9856 DT.dominates(L2->getHeader(), L1->getHeader())) && 9857 "Domination relationship is not a linear order"); 9858 #endif 9859 9860 const Loop *MDL = 9861 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9862 [&](const Loop *L1, const Loop *L2) { 9863 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9864 }); 9865 9866 // Get init and post increment value for LHS. 9867 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9868 // if LHS contains unknown non-invariant SCEV then bail out. 9869 if (SplitLHS.first == getCouldNotCompute()) 9870 return false; 9871 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9872 // Get init and post increment value for RHS. 9873 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9874 // if RHS contains unknown non-invariant SCEV then bail out. 9875 if (SplitRHS.first == getCouldNotCompute()) 9876 return false; 9877 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9878 // It is possible that init SCEV contains an invariant load but it does 9879 // not dominate MDL and is not available at MDL loop entry, so we should 9880 // check it here. 9881 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9882 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9883 return false; 9884 9885 // It seems backedge guard check is faster than entry one so in some cases 9886 // it can speed up whole estimation by short circuit 9887 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9888 SplitRHS.second) && 9889 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9890 } 9891 9892 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9893 const SCEV *LHS, const SCEV *RHS) { 9894 // Canonicalize the inputs first. 9895 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9896 9897 if (isKnownViaInduction(Pred, LHS, RHS)) 9898 return true; 9899 9900 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9901 return true; 9902 9903 // Otherwise see what can be done with some simple reasoning. 9904 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9905 } 9906 9907 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9908 const SCEV *LHS, 9909 const SCEV *RHS) { 9910 if (isKnownPredicate(Pred, LHS, RHS)) 9911 return true; 9912 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9913 return false; 9914 return None; 9915 } 9916 9917 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9918 const SCEV *LHS, const SCEV *RHS, 9919 const Instruction *Context) { 9920 // TODO: Analyze guards and assumes from Context's block. 9921 return isKnownPredicate(Pred, LHS, RHS) || 9922 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9923 } 9924 9925 Optional<bool> 9926 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9927 const SCEV *RHS, 9928 const Instruction *Context) { 9929 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9930 if (KnownWithoutContext) 9931 return KnownWithoutContext; 9932 9933 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9934 return true; 9935 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9936 ICmpInst::getInversePredicate(Pred), 9937 LHS, RHS)) 9938 return false; 9939 return None; 9940 } 9941 9942 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9943 const SCEVAddRecExpr *LHS, 9944 const SCEV *RHS) { 9945 const Loop *L = LHS->getLoop(); 9946 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9947 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9948 } 9949 9950 Optional<ScalarEvolution::MonotonicPredicateType> 9951 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9952 ICmpInst::Predicate Pred) { 9953 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9954 9955 #ifndef NDEBUG 9956 // Verify an invariant: inverting the predicate should turn a monotonically 9957 // increasing change to a monotonically decreasing one, and vice versa. 9958 if (Result) { 9959 auto ResultSwapped = 9960 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9961 9962 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9963 assert(ResultSwapped.getValue() != Result.getValue() && 9964 "monotonicity should flip as we flip the predicate"); 9965 } 9966 #endif 9967 9968 return Result; 9969 } 9970 9971 Optional<ScalarEvolution::MonotonicPredicateType> 9972 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9973 ICmpInst::Predicate Pred) { 9974 // A zero step value for LHS means the induction variable is essentially a 9975 // loop invariant value. We don't really depend on the predicate actually 9976 // flipping from false to true (for increasing predicates, and the other way 9977 // around for decreasing predicates), all we care about is that *if* the 9978 // predicate changes then it only changes from false to true. 9979 // 9980 // A zero step value in itself is not very useful, but there may be places 9981 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9982 // as general as possible. 9983 9984 // Only handle LE/LT/GE/GT predicates. 9985 if (!ICmpInst::isRelational(Pred)) 9986 return None; 9987 9988 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9989 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9990 "Should be greater or less!"); 9991 9992 // Check that AR does not wrap. 9993 if (ICmpInst::isUnsigned(Pred)) { 9994 if (!LHS->hasNoUnsignedWrap()) 9995 return None; 9996 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9997 } else { 9998 assert(ICmpInst::isSigned(Pred) && 9999 "Relational predicate is either signed or unsigned!"); 10000 if (!LHS->hasNoSignedWrap()) 10001 return None; 10002 10003 const SCEV *Step = LHS->getStepRecurrence(*this); 10004 10005 if (isKnownNonNegative(Step)) 10006 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10007 10008 if (isKnownNonPositive(Step)) 10009 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10010 10011 return None; 10012 } 10013 } 10014 10015 Optional<ScalarEvolution::LoopInvariantPredicate> 10016 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10017 const SCEV *LHS, const SCEV *RHS, 10018 const Loop *L) { 10019 10020 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10021 if (!isLoopInvariant(RHS, L)) { 10022 if (!isLoopInvariant(LHS, L)) 10023 return None; 10024 10025 std::swap(LHS, RHS); 10026 Pred = ICmpInst::getSwappedPredicate(Pred); 10027 } 10028 10029 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10030 if (!ArLHS || ArLHS->getLoop() != L) 10031 return None; 10032 10033 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10034 if (!MonotonicType) 10035 return None; 10036 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10037 // true as the loop iterates, and the backedge is control dependent on 10038 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10039 // 10040 // * if the predicate was false in the first iteration then the predicate 10041 // is never evaluated again, since the loop exits without taking the 10042 // backedge. 10043 // * if the predicate was true in the first iteration then it will 10044 // continue to be true for all future iterations since it is 10045 // monotonically increasing. 10046 // 10047 // For both the above possibilities, we can replace the loop varying 10048 // predicate with its value on the first iteration of the loop (which is 10049 // loop invariant). 10050 // 10051 // A similar reasoning applies for a monotonically decreasing predicate, by 10052 // replacing true with false and false with true in the above two bullets. 10053 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10054 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10055 10056 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10057 return None; 10058 10059 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10060 } 10061 10062 Optional<ScalarEvolution::LoopInvariantPredicate> 10063 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10064 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10065 const Instruction *Context, const SCEV *MaxIter) { 10066 // Try to prove the following set of facts: 10067 // - The predicate is monotonic in the iteration space. 10068 // - If the check does not fail on the 1st iteration: 10069 // - No overflow will happen during first MaxIter iterations; 10070 // - It will not fail on the MaxIter'th iteration. 10071 // If the check does fail on the 1st iteration, we leave the loop and no 10072 // other checks matter. 10073 10074 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10075 if (!isLoopInvariant(RHS, L)) { 10076 if (!isLoopInvariant(LHS, L)) 10077 return None; 10078 10079 std::swap(LHS, RHS); 10080 Pred = ICmpInst::getSwappedPredicate(Pred); 10081 } 10082 10083 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10084 if (!AR || AR->getLoop() != L) 10085 return None; 10086 10087 // The predicate must be relational (i.e. <, <=, >=, >). 10088 if (!ICmpInst::isRelational(Pred)) 10089 return None; 10090 10091 // TODO: Support steps other than +/- 1. 10092 const SCEV *Step = AR->getStepRecurrence(*this); 10093 auto *One = getOne(Step->getType()); 10094 auto *MinusOne = getNegativeSCEV(One); 10095 if (Step != One && Step != MinusOne) 10096 return None; 10097 10098 // Type mismatch here means that MaxIter is potentially larger than max 10099 // unsigned value in start type, which mean we cannot prove no wrap for the 10100 // indvar. 10101 if (AR->getType() != MaxIter->getType()) 10102 return None; 10103 10104 // Value of IV on suggested last iteration. 10105 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10106 // Does it still meet the requirement? 10107 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10108 return None; 10109 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10110 // not exceed max unsigned value of this type), this effectively proves 10111 // that there is no wrap during the iteration. To prove that there is no 10112 // signed/unsigned wrap, we need to check that 10113 // Start <= Last for step = 1 or Start >= Last for step = -1. 10114 ICmpInst::Predicate NoOverflowPred = 10115 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10116 if (Step == MinusOne) 10117 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10118 const SCEV *Start = AR->getStart(); 10119 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 10120 return None; 10121 10122 // Everything is fine. 10123 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10124 } 10125 10126 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10127 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10128 if (HasSameValue(LHS, RHS)) 10129 return ICmpInst::isTrueWhenEqual(Pred); 10130 10131 // This code is split out from isKnownPredicate because it is called from 10132 // within isLoopEntryGuardedByCond. 10133 10134 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10135 const ConstantRange &RangeRHS) { 10136 return RangeLHS.icmp(Pred, RangeRHS); 10137 }; 10138 10139 // The check at the top of the function catches the case where the values are 10140 // known to be equal. 10141 if (Pred == CmpInst::ICMP_EQ) 10142 return false; 10143 10144 if (Pred == CmpInst::ICMP_NE) { 10145 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10146 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10147 return true; 10148 auto *Diff = getMinusSCEV(LHS, RHS); 10149 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10150 } 10151 10152 if (CmpInst::isSigned(Pred)) 10153 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10154 10155 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10156 } 10157 10158 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10159 const SCEV *LHS, 10160 const SCEV *RHS) { 10161 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10162 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10163 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10164 // OutC1 and OutC2. 10165 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10166 APInt &OutC1, APInt &OutC2, 10167 SCEV::NoWrapFlags ExpectedFlags) { 10168 const SCEV *XNonConstOp, *XConstOp; 10169 const SCEV *YNonConstOp, *YConstOp; 10170 SCEV::NoWrapFlags XFlagsPresent; 10171 SCEV::NoWrapFlags YFlagsPresent; 10172 10173 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10174 XConstOp = getZero(X->getType()); 10175 XNonConstOp = X; 10176 XFlagsPresent = ExpectedFlags; 10177 } 10178 if (!isa<SCEVConstant>(XConstOp) || 10179 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10180 return false; 10181 10182 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10183 YConstOp = getZero(Y->getType()); 10184 YNonConstOp = Y; 10185 YFlagsPresent = ExpectedFlags; 10186 } 10187 10188 if (!isa<SCEVConstant>(YConstOp) || 10189 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10190 return false; 10191 10192 if (YNonConstOp != XNonConstOp) 10193 return false; 10194 10195 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10196 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10197 10198 return true; 10199 }; 10200 10201 APInt C1; 10202 APInt C2; 10203 10204 switch (Pred) { 10205 default: 10206 break; 10207 10208 case ICmpInst::ICMP_SGE: 10209 std::swap(LHS, RHS); 10210 LLVM_FALLTHROUGH; 10211 case ICmpInst::ICMP_SLE: 10212 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10213 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10214 return true; 10215 10216 break; 10217 10218 case ICmpInst::ICMP_SGT: 10219 std::swap(LHS, RHS); 10220 LLVM_FALLTHROUGH; 10221 case ICmpInst::ICMP_SLT: 10222 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10223 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10224 return true; 10225 10226 break; 10227 10228 case ICmpInst::ICMP_UGE: 10229 std::swap(LHS, RHS); 10230 LLVM_FALLTHROUGH; 10231 case ICmpInst::ICMP_ULE: 10232 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10233 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10234 return true; 10235 10236 break; 10237 10238 case ICmpInst::ICMP_UGT: 10239 std::swap(LHS, RHS); 10240 LLVM_FALLTHROUGH; 10241 case ICmpInst::ICMP_ULT: 10242 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10243 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10244 return true; 10245 break; 10246 } 10247 10248 return false; 10249 } 10250 10251 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10252 const SCEV *LHS, 10253 const SCEV *RHS) { 10254 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10255 return false; 10256 10257 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10258 // the stack can result in exponential time complexity. 10259 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10260 10261 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10262 // 10263 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10264 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10265 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10266 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10267 // use isKnownPredicate later if needed. 10268 return isKnownNonNegative(RHS) && 10269 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10270 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10271 } 10272 10273 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10274 ICmpInst::Predicate Pred, 10275 const SCEV *LHS, const SCEV *RHS) { 10276 // No need to even try if we know the module has no guards. 10277 if (!HasGuards) 10278 return false; 10279 10280 return any_of(*BB, [&](const Instruction &I) { 10281 using namespace llvm::PatternMatch; 10282 10283 Value *Condition; 10284 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10285 m_Value(Condition))) && 10286 isImpliedCond(Pred, LHS, RHS, Condition, false); 10287 }); 10288 } 10289 10290 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10291 /// protected by a conditional between LHS and RHS. This is used to 10292 /// to eliminate casts. 10293 bool 10294 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10295 ICmpInst::Predicate Pred, 10296 const SCEV *LHS, const SCEV *RHS) { 10297 // Interpret a null as meaning no loop, where there is obviously no guard 10298 // (interprocedural conditions notwithstanding). 10299 if (!L) return true; 10300 10301 if (VerifyIR) 10302 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10303 "This cannot be done on broken IR!"); 10304 10305 10306 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10307 return true; 10308 10309 BasicBlock *Latch = L->getLoopLatch(); 10310 if (!Latch) 10311 return false; 10312 10313 BranchInst *LoopContinuePredicate = 10314 dyn_cast<BranchInst>(Latch->getTerminator()); 10315 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10316 isImpliedCond(Pred, LHS, RHS, 10317 LoopContinuePredicate->getCondition(), 10318 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10319 return true; 10320 10321 // We don't want more than one activation of the following loops on the stack 10322 // -- that can lead to O(n!) time complexity. 10323 if (WalkingBEDominatingConds) 10324 return false; 10325 10326 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10327 10328 // See if we can exploit a trip count to prove the predicate. 10329 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10330 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10331 if (LatchBECount != getCouldNotCompute()) { 10332 // We know that Latch branches back to the loop header exactly 10333 // LatchBECount times. This means the backdege condition at Latch is 10334 // equivalent to "{0,+,1} u< LatchBECount". 10335 Type *Ty = LatchBECount->getType(); 10336 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10337 const SCEV *LoopCounter = 10338 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10339 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10340 LatchBECount)) 10341 return true; 10342 } 10343 10344 // Check conditions due to any @llvm.assume intrinsics. 10345 for (auto &AssumeVH : AC.assumptions()) { 10346 if (!AssumeVH) 10347 continue; 10348 auto *CI = cast<CallInst>(AssumeVH); 10349 if (!DT.dominates(CI, Latch->getTerminator())) 10350 continue; 10351 10352 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10353 return true; 10354 } 10355 10356 // If the loop is not reachable from the entry block, we risk running into an 10357 // infinite loop as we walk up into the dom tree. These loops do not matter 10358 // anyway, so we just return a conservative answer when we see them. 10359 if (!DT.isReachableFromEntry(L->getHeader())) 10360 return false; 10361 10362 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10363 return true; 10364 10365 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10366 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10367 assert(DTN && "should reach the loop header before reaching the root!"); 10368 10369 BasicBlock *BB = DTN->getBlock(); 10370 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10371 return true; 10372 10373 BasicBlock *PBB = BB->getSinglePredecessor(); 10374 if (!PBB) 10375 continue; 10376 10377 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10378 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10379 continue; 10380 10381 Value *Condition = ContinuePredicate->getCondition(); 10382 10383 // If we have an edge `E` within the loop body that dominates the only 10384 // latch, the condition guarding `E` also guards the backedge. This 10385 // reasoning works only for loops with a single latch. 10386 10387 BasicBlockEdge DominatingEdge(PBB, BB); 10388 if (DominatingEdge.isSingleEdge()) { 10389 // We're constructively (and conservatively) enumerating edges within the 10390 // loop body that dominate the latch. The dominator tree better agree 10391 // with us on this: 10392 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10393 10394 if (isImpliedCond(Pred, LHS, RHS, Condition, 10395 BB != ContinuePredicate->getSuccessor(0))) 10396 return true; 10397 } 10398 } 10399 10400 return false; 10401 } 10402 10403 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10404 ICmpInst::Predicate Pred, 10405 const SCEV *LHS, 10406 const SCEV *RHS) { 10407 if (VerifyIR) 10408 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10409 "This cannot be done on broken IR!"); 10410 10411 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10412 // the facts (a >= b && a != b) separately. A typical situation is when the 10413 // non-strict comparison is known from ranges and non-equality is known from 10414 // dominating predicates. If we are proving strict comparison, we always try 10415 // to prove non-equality and non-strict comparison separately. 10416 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10417 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10418 bool ProvedNonStrictComparison = false; 10419 bool ProvedNonEquality = false; 10420 10421 auto SplitAndProve = 10422 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10423 if (!ProvedNonStrictComparison) 10424 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10425 if (!ProvedNonEquality) 10426 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10427 if (ProvedNonStrictComparison && ProvedNonEquality) 10428 return true; 10429 return false; 10430 }; 10431 10432 if (ProvingStrictComparison) { 10433 auto ProofFn = [&](ICmpInst::Predicate P) { 10434 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10435 }; 10436 if (SplitAndProve(ProofFn)) 10437 return true; 10438 } 10439 10440 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10441 auto ProveViaGuard = [&](const BasicBlock *Block) { 10442 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10443 return true; 10444 if (ProvingStrictComparison) { 10445 auto ProofFn = [&](ICmpInst::Predicate P) { 10446 return isImpliedViaGuard(Block, P, LHS, RHS); 10447 }; 10448 if (SplitAndProve(ProofFn)) 10449 return true; 10450 } 10451 return false; 10452 }; 10453 10454 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10455 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10456 const Instruction *Context = &BB->front(); 10457 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10458 return true; 10459 if (ProvingStrictComparison) { 10460 auto ProofFn = [&](ICmpInst::Predicate P) { 10461 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10462 }; 10463 if (SplitAndProve(ProofFn)) 10464 return true; 10465 } 10466 return false; 10467 }; 10468 10469 // Starting at the block's predecessor, climb up the predecessor chain, as long 10470 // as there are predecessors that can be found that have unique successors 10471 // leading to the original block. 10472 const Loop *ContainingLoop = LI.getLoopFor(BB); 10473 const BasicBlock *PredBB; 10474 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10475 PredBB = ContainingLoop->getLoopPredecessor(); 10476 else 10477 PredBB = BB->getSinglePredecessor(); 10478 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10479 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10480 if (ProveViaGuard(Pair.first)) 10481 return true; 10482 10483 const BranchInst *LoopEntryPredicate = 10484 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10485 if (!LoopEntryPredicate || 10486 LoopEntryPredicate->isUnconditional()) 10487 continue; 10488 10489 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10490 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10491 return true; 10492 } 10493 10494 // Check conditions due to any @llvm.assume intrinsics. 10495 for (auto &AssumeVH : AC.assumptions()) { 10496 if (!AssumeVH) 10497 continue; 10498 auto *CI = cast<CallInst>(AssumeVH); 10499 if (!DT.dominates(CI, BB)) 10500 continue; 10501 10502 if (ProveViaCond(CI->getArgOperand(0), false)) 10503 return true; 10504 } 10505 10506 return false; 10507 } 10508 10509 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10510 ICmpInst::Predicate Pred, 10511 const SCEV *LHS, 10512 const SCEV *RHS) { 10513 // Interpret a null as meaning no loop, where there is obviously no guard 10514 // (interprocedural conditions notwithstanding). 10515 if (!L) 10516 return false; 10517 10518 // Both LHS and RHS must be available at loop entry. 10519 assert(isAvailableAtLoopEntry(LHS, L) && 10520 "LHS is not available at Loop Entry"); 10521 assert(isAvailableAtLoopEntry(RHS, L) && 10522 "RHS is not available at Loop Entry"); 10523 10524 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10525 return true; 10526 10527 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10528 } 10529 10530 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10531 const SCEV *RHS, 10532 const Value *FoundCondValue, bool Inverse, 10533 const Instruction *Context) { 10534 // False conditions implies anything. Do not bother analyzing it further. 10535 if (FoundCondValue == 10536 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10537 return true; 10538 10539 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10540 return false; 10541 10542 auto ClearOnExit = 10543 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10544 10545 // Recursively handle And and Or conditions. 10546 const Value *Op0, *Op1; 10547 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10548 if (!Inverse) 10549 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10550 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10551 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10552 if (Inverse) 10553 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10554 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10555 } 10556 10557 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10558 if (!ICI) return false; 10559 10560 // Now that we found a conditional branch that dominates the loop or controls 10561 // the loop latch. Check to see if it is the comparison we are looking for. 10562 ICmpInst::Predicate FoundPred; 10563 if (Inverse) 10564 FoundPred = ICI->getInversePredicate(); 10565 else 10566 FoundPred = ICI->getPredicate(); 10567 10568 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10569 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10570 10571 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10572 } 10573 10574 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10575 const SCEV *RHS, 10576 ICmpInst::Predicate FoundPred, 10577 const SCEV *FoundLHS, const SCEV *FoundRHS, 10578 const Instruction *Context) { 10579 // Balance the types. 10580 if (getTypeSizeInBits(LHS->getType()) < 10581 getTypeSizeInBits(FoundLHS->getType())) { 10582 // For unsigned and equality predicates, try to prove that both found 10583 // operands fit into narrow unsigned range. If so, try to prove facts in 10584 // narrow types. 10585 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10586 auto *NarrowType = LHS->getType(); 10587 auto *WideType = FoundLHS->getType(); 10588 auto BitWidth = getTypeSizeInBits(NarrowType); 10589 const SCEV *MaxValue = getZeroExtendExpr( 10590 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10591 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10592 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10593 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10594 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10595 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10596 TruncFoundRHS, Context)) 10597 return true; 10598 } 10599 } 10600 10601 if (LHS->getType()->isPointerTy()) 10602 return false; 10603 if (CmpInst::isSigned(Pred)) { 10604 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10605 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10606 } else { 10607 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10608 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10609 } 10610 } else if (getTypeSizeInBits(LHS->getType()) > 10611 getTypeSizeInBits(FoundLHS->getType())) { 10612 if (FoundLHS->getType()->isPointerTy()) 10613 return false; 10614 if (CmpInst::isSigned(FoundPred)) { 10615 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10616 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10617 } else { 10618 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10619 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10620 } 10621 } 10622 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10623 FoundRHS, Context); 10624 } 10625 10626 bool ScalarEvolution::isImpliedCondBalancedTypes( 10627 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10628 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10629 const Instruction *Context) { 10630 assert(getTypeSizeInBits(LHS->getType()) == 10631 getTypeSizeInBits(FoundLHS->getType()) && 10632 "Types should be balanced!"); 10633 // Canonicalize the query to match the way instcombine will have 10634 // canonicalized the comparison. 10635 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10636 if (LHS == RHS) 10637 return CmpInst::isTrueWhenEqual(Pred); 10638 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10639 if (FoundLHS == FoundRHS) 10640 return CmpInst::isFalseWhenEqual(FoundPred); 10641 10642 // Check to see if we can make the LHS or RHS match. 10643 if (LHS == FoundRHS || RHS == FoundLHS) { 10644 if (isa<SCEVConstant>(RHS)) { 10645 std::swap(FoundLHS, FoundRHS); 10646 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10647 } else { 10648 std::swap(LHS, RHS); 10649 Pred = ICmpInst::getSwappedPredicate(Pred); 10650 } 10651 } 10652 10653 // Check whether the found predicate is the same as the desired predicate. 10654 if (FoundPred == Pred) 10655 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10656 10657 // Check whether swapping the found predicate makes it the same as the 10658 // desired predicate. 10659 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10660 // We can write the implication 10661 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10662 // using one of the following ways: 10663 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10664 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10665 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10666 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10667 // Forms 1. and 2. require swapping the operands of one condition. Don't 10668 // do this if it would break canonical constant/addrec ordering. 10669 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10670 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10671 Context); 10672 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10673 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10674 10675 // Don't try to getNotSCEV pointers. 10676 if (LHS->getType()->isPointerTy() || FoundLHS->getType()->isPointerTy()) 10677 return false; 10678 10679 // There's no clear preference between forms 3. and 4., try both. 10680 return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10681 FoundLHS, FoundRHS, Context) || 10682 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10683 getNotSCEV(FoundRHS), Context); 10684 } 10685 10686 // Unsigned comparison is the same as signed comparison when both the operands 10687 // are non-negative. 10688 if (CmpInst::isUnsigned(FoundPred) && 10689 CmpInst::getSignedPredicate(FoundPred) == Pred && 10690 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10691 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10692 10693 // Check if we can make progress by sharpening ranges. 10694 if (FoundPred == ICmpInst::ICMP_NE && 10695 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10696 10697 const SCEVConstant *C = nullptr; 10698 const SCEV *V = nullptr; 10699 10700 if (isa<SCEVConstant>(FoundLHS)) { 10701 C = cast<SCEVConstant>(FoundLHS); 10702 V = FoundRHS; 10703 } else { 10704 C = cast<SCEVConstant>(FoundRHS); 10705 V = FoundLHS; 10706 } 10707 10708 // The guarding predicate tells us that C != V. If the known range 10709 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10710 // range we consider has to correspond to same signedness as the 10711 // predicate we're interested in folding. 10712 10713 APInt Min = ICmpInst::isSigned(Pred) ? 10714 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10715 10716 if (Min == C->getAPInt()) { 10717 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10718 // This is true even if (Min + 1) wraps around -- in case of 10719 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10720 10721 APInt SharperMin = Min + 1; 10722 10723 switch (Pred) { 10724 case ICmpInst::ICMP_SGE: 10725 case ICmpInst::ICMP_UGE: 10726 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10727 // RHS, we're done. 10728 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10729 Context)) 10730 return true; 10731 LLVM_FALLTHROUGH; 10732 10733 case ICmpInst::ICMP_SGT: 10734 case ICmpInst::ICMP_UGT: 10735 // We know from the range information that (V `Pred` Min || 10736 // V == Min). We know from the guarding condition that !(V 10737 // == Min). This gives us 10738 // 10739 // V `Pred` Min || V == Min && !(V == Min) 10740 // => V `Pred` Min 10741 // 10742 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10743 10744 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10745 Context)) 10746 return true; 10747 break; 10748 10749 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10750 case ICmpInst::ICMP_SLE: 10751 case ICmpInst::ICMP_ULE: 10752 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10753 LHS, V, getConstant(SharperMin), Context)) 10754 return true; 10755 LLVM_FALLTHROUGH; 10756 10757 case ICmpInst::ICMP_SLT: 10758 case ICmpInst::ICMP_ULT: 10759 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10760 LHS, V, getConstant(Min), Context)) 10761 return true; 10762 break; 10763 10764 default: 10765 // No change 10766 break; 10767 } 10768 } 10769 } 10770 10771 // Check whether the actual condition is beyond sufficient. 10772 if (FoundPred == ICmpInst::ICMP_EQ) 10773 if (ICmpInst::isTrueWhenEqual(Pred)) 10774 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10775 return true; 10776 if (Pred == ICmpInst::ICMP_NE) 10777 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10778 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10779 Context)) 10780 return true; 10781 10782 // Otherwise assume the worst. 10783 return false; 10784 } 10785 10786 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10787 const SCEV *&L, const SCEV *&R, 10788 SCEV::NoWrapFlags &Flags) { 10789 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10790 if (!AE || AE->getNumOperands() != 2) 10791 return false; 10792 10793 L = AE->getOperand(0); 10794 R = AE->getOperand(1); 10795 Flags = AE->getNoWrapFlags(); 10796 return true; 10797 } 10798 10799 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10800 const SCEV *Less) { 10801 // We avoid subtracting expressions here because this function is usually 10802 // fairly deep in the call stack (i.e. is called many times). 10803 10804 // X - X = 0. 10805 if (More == Less) 10806 return APInt(getTypeSizeInBits(More->getType()), 0); 10807 10808 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10809 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10810 const auto *MAR = cast<SCEVAddRecExpr>(More); 10811 10812 if (LAR->getLoop() != MAR->getLoop()) 10813 return None; 10814 10815 // We look at affine expressions only; not for correctness but to keep 10816 // getStepRecurrence cheap. 10817 if (!LAR->isAffine() || !MAR->isAffine()) 10818 return None; 10819 10820 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10821 return None; 10822 10823 Less = LAR->getStart(); 10824 More = MAR->getStart(); 10825 10826 // fall through 10827 } 10828 10829 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10830 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10831 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10832 return M - L; 10833 } 10834 10835 SCEV::NoWrapFlags Flags; 10836 const SCEV *LLess = nullptr, *RLess = nullptr; 10837 const SCEV *LMore = nullptr, *RMore = nullptr; 10838 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10839 // Compare (X + C1) vs X. 10840 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10841 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10842 if (RLess == More) 10843 return -(C1->getAPInt()); 10844 10845 // Compare X vs (X + C2). 10846 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10847 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10848 if (RMore == Less) 10849 return C2->getAPInt(); 10850 10851 // Compare (X + C1) vs (X + C2). 10852 if (C1 && C2 && RLess == RMore) 10853 return C2->getAPInt() - C1->getAPInt(); 10854 10855 return None; 10856 } 10857 10858 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10859 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10860 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10861 // Try to recognize the following pattern: 10862 // 10863 // FoundRHS = ... 10864 // ... 10865 // loop: 10866 // FoundLHS = {Start,+,W} 10867 // context_bb: // Basic block from the same loop 10868 // known(Pred, FoundLHS, FoundRHS) 10869 // 10870 // If some predicate is known in the context of a loop, it is also known on 10871 // each iteration of this loop, including the first iteration. Therefore, in 10872 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10873 // prove the original pred using this fact. 10874 if (!Context) 10875 return false; 10876 const BasicBlock *ContextBB = Context->getParent(); 10877 // Make sure AR varies in the context block. 10878 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10879 const Loop *L = AR->getLoop(); 10880 // Make sure that context belongs to the loop and executes on 1st iteration 10881 // (if it ever executes at all). 10882 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10883 return false; 10884 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10885 return false; 10886 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10887 } 10888 10889 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10890 const Loop *L = AR->getLoop(); 10891 // Make sure that context belongs to the loop and executes on 1st iteration 10892 // (if it ever executes at all). 10893 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10894 return false; 10895 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10896 return false; 10897 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10898 } 10899 10900 return false; 10901 } 10902 10903 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10904 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10905 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10906 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10907 return false; 10908 10909 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10910 if (!AddRecLHS) 10911 return false; 10912 10913 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10914 if (!AddRecFoundLHS) 10915 return false; 10916 10917 // We'd like to let SCEV reason about control dependencies, so we constrain 10918 // both the inequalities to be about add recurrences on the same loop. This 10919 // way we can use isLoopEntryGuardedByCond later. 10920 10921 const Loop *L = AddRecFoundLHS->getLoop(); 10922 if (L != AddRecLHS->getLoop()) 10923 return false; 10924 10925 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10926 // 10927 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10928 // ... (2) 10929 // 10930 // Informal proof for (2), assuming (1) [*]: 10931 // 10932 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10933 // 10934 // Then 10935 // 10936 // FoundLHS s< FoundRHS s< INT_MIN - C 10937 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10938 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10939 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10940 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10941 // <=> FoundLHS + C s< FoundRHS + C 10942 // 10943 // [*]: (1) can be proved by ruling out overflow. 10944 // 10945 // [**]: This can be proved by analyzing all the four possibilities: 10946 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10947 // (A s>= 0, B s>= 0). 10948 // 10949 // Note: 10950 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10951 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10952 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10953 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10954 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10955 // C)". 10956 10957 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10958 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10959 if (!LDiff || !RDiff || *LDiff != *RDiff) 10960 return false; 10961 10962 if (LDiff->isMinValue()) 10963 return true; 10964 10965 APInt FoundRHSLimit; 10966 10967 if (Pred == CmpInst::ICMP_ULT) { 10968 FoundRHSLimit = -(*RDiff); 10969 } else { 10970 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10971 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10972 } 10973 10974 // Try to prove (1) or (2), as needed. 10975 return isAvailableAtLoopEntry(FoundRHS, L) && 10976 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10977 getConstant(FoundRHSLimit)); 10978 } 10979 10980 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10981 const SCEV *LHS, const SCEV *RHS, 10982 const SCEV *FoundLHS, 10983 const SCEV *FoundRHS, unsigned Depth) { 10984 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10985 10986 auto ClearOnExit = make_scope_exit([&]() { 10987 if (LPhi) { 10988 bool Erased = PendingMerges.erase(LPhi); 10989 assert(Erased && "Failed to erase LPhi!"); 10990 (void)Erased; 10991 } 10992 if (RPhi) { 10993 bool Erased = PendingMerges.erase(RPhi); 10994 assert(Erased && "Failed to erase RPhi!"); 10995 (void)Erased; 10996 } 10997 }); 10998 10999 // Find respective Phis and check that they are not being pending. 11000 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11001 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11002 if (!PendingMerges.insert(Phi).second) 11003 return false; 11004 LPhi = Phi; 11005 } 11006 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11007 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11008 // If we detect a loop of Phi nodes being processed by this method, for 11009 // example: 11010 // 11011 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11012 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11013 // 11014 // we don't want to deal with a case that complex, so return conservative 11015 // answer false. 11016 if (!PendingMerges.insert(Phi).second) 11017 return false; 11018 RPhi = Phi; 11019 } 11020 11021 // If none of LHS, RHS is a Phi, nothing to do here. 11022 if (!LPhi && !RPhi) 11023 return false; 11024 11025 // If there is a SCEVUnknown Phi we are interested in, make it left. 11026 if (!LPhi) { 11027 std::swap(LHS, RHS); 11028 std::swap(FoundLHS, FoundRHS); 11029 std::swap(LPhi, RPhi); 11030 Pred = ICmpInst::getSwappedPredicate(Pred); 11031 } 11032 11033 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11034 const BasicBlock *LBB = LPhi->getParent(); 11035 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11036 11037 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11038 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11039 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11040 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11041 }; 11042 11043 if (RPhi && RPhi->getParent() == LBB) { 11044 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11045 // If we compare two Phis from the same block, and for each entry block 11046 // the predicate is true for incoming values from this block, then the 11047 // predicate is also true for the Phis. 11048 for (const BasicBlock *IncBB : predecessors(LBB)) { 11049 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11050 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11051 if (!ProvedEasily(L, R)) 11052 return false; 11053 } 11054 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11055 // Case two: RHS is also a Phi from the same basic block, and it is an 11056 // AddRec. It means that there is a loop which has both AddRec and Unknown 11057 // PHIs, for it we can compare incoming values of AddRec from above the loop 11058 // and latch with their respective incoming values of LPhi. 11059 // TODO: Generalize to handle loops with many inputs in a header. 11060 if (LPhi->getNumIncomingValues() != 2) return false; 11061 11062 auto *RLoop = RAR->getLoop(); 11063 auto *Predecessor = RLoop->getLoopPredecessor(); 11064 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11065 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11066 if (!ProvedEasily(L1, RAR->getStart())) 11067 return false; 11068 auto *Latch = RLoop->getLoopLatch(); 11069 assert(Latch && "Loop with AddRec with no latch?"); 11070 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11071 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11072 return false; 11073 } else { 11074 // In all other cases go over inputs of LHS and compare each of them to RHS, 11075 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11076 // At this point RHS is either a non-Phi, or it is a Phi from some block 11077 // different from LBB. 11078 for (const BasicBlock *IncBB : predecessors(LBB)) { 11079 // Check that RHS is available in this block. 11080 if (!dominates(RHS, IncBB)) 11081 return false; 11082 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11083 // Make sure L does not refer to a value from a potentially previous 11084 // iteration of a loop. 11085 if (!properlyDominates(L, IncBB)) 11086 return false; 11087 if (!ProvedEasily(L, RHS)) 11088 return false; 11089 } 11090 } 11091 return true; 11092 } 11093 11094 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11095 const SCEV *LHS, const SCEV *RHS, 11096 const SCEV *FoundLHS, 11097 const SCEV *FoundRHS, 11098 const Instruction *Context) { 11099 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11100 return true; 11101 11102 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11103 return true; 11104 11105 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11106 Context)) 11107 return true; 11108 11109 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11110 FoundLHS, FoundRHS); 11111 } 11112 11113 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11114 template <typename MinMaxExprType> 11115 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11116 const SCEV *Candidate) { 11117 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11118 if (!MinMaxExpr) 11119 return false; 11120 11121 return is_contained(MinMaxExpr->operands(), Candidate); 11122 } 11123 11124 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11125 ICmpInst::Predicate Pred, 11126 const SCEV *LHS, const SCEV *RHS) { 11127 // If both sides are affine addrecs for the same loop, with equal 11128 // steps, and we know the recurrences don't wrap, then we only 11129 // need to check the predicate on the starting values. 11130 11131 if (!ICmpInst::isRelational(Pred)) 11132 return false; 11133 11134 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11135 if (!LAR) 11136 return false; 11137 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11138 if (!RAR) 11139 return false; 11140 if (LAR->getLoop() != RAR->getLoop()) 11141 return false; 11142 if (!LAR->isAffine() || !RAR->isAffine()) 11143 return false; 11144 11145 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11146 return false; 11147 11148 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11149 SCEV::FlagNSW : SCEV::FlagNUW; 11150 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11151 return false; 11152 11153 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11154 } 11155 11156 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11157 /// expression? 11158 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11159 ICmpInst::Predicate Pred, 11160 const SCEV *LHS, const SCEV *RHS) { 11161 switch (Pred) { 11162 default: 11163 return false; 11164 11165 case ICmpInst::ICMP_SGE: 11166 std::swap(LHS, RHS); 11167 LLVM_FALLTHROUGH; 11168 case ICmpInst::ICMP_SLE: 11169 return 11170 // min(A, ...) <= A 11171 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11172 // A <= max(A, ...) 11173 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11174 11175 case ICmpInst::ICMP_UGE: 11176 std::swap(LHS, RHS); 11177 LLVM_FALLTHROUGH; 11178 case ICmpInst::ICMP_ULE: 11179 return 11180 // min(A, ...) <= A 11181 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11182 // A <= max(A, ...) 11183 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11184 } 11185 11186 llvm_unreachable("covered switch fell through?!"); 11187 } 11188 11189 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11190 const SCEV *LHS, const SCEV *RHS, 11191 const SCEV *FoundLHS, 11192 const SCEV *FoundRHS, 11193 unsigned Depth) { 11194 assert(getTypeSizeInBits(LHS->getType()) == 11195 getTypeSizeInBits(RHS->getType()) && 11196 "LHS and RHS have different sizes?"); 11197 assert(getTypeSizeInBits(FoundLHS->getType()) == 11198 getTypeSizeInBits(FoundRHS->getType()) && 11199 "FoundLHS and FoundRHS have different sizes?"); 11200 // We want to avoid hurting the compile time with analysis of too big trees. 11201 if (Depth > MaxSCEVOperationsImplicationDepth) 11202 return false; 11203 11204 // We only want to work with GT comparison so far. 11205 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11206 Pred = CmpInst::getSwappedPredicate(Pred); 11207 std::swap(LHS, RHS); 11208 std::swap(FoundLHS, FoundRHS); 11209 } 11210 11211 // For unsigned, try to reduce it to corresponding signed comparison. 11212 if (Pred == ICmpInst::ICMP_UGT) 11213 // We can replace unsigned predicate with its signed counterpart if all 11214 // involved values are non-negative. 11215 // TODO: We could have better support for unsigned. 11216 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11217 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11218 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11219 // use this fact to prove that LHS and RHS are non-negative. 11220 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11221 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11222 FoundRHS) && 11223 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11224 FoundRHS)) 11225 Pred = ICmpInst::ICMP_SGT; 11226 } 11227 11228 if (Pred != ICmpInst::ICMP_SGT) 11229 return false; 11230 11231 auto GetOpFromSExt = [&](const SCEV *S) { 11232 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11233 return Ext->getOperand(); 11234 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11235 // the constant in some cases. 11236 return S; 11237 }; 11238 11239 // Acquire values from extensions. 11240 auto *OrigLHS = LHS; 11241 auto *OrigFoundLHS = FoundLHS; 11242 LHS = GetOpFromSExt(LHS); 11243 FoundLHS = GetOpFromSExt(FoundLHS); 11244 11245 // Is the SGT predicate can be proved trivially or using the found context. 11246 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11247 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11248 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11249 FoundRHS, Depth + 1); 11250 }; 11251 11252 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11253 // We want to avoid creation of any new non-constant SCEV. Since we are 11254 // going to compare the operands to RHS, we should be certain that we don't 11255 // need any size extensions for this. So let's decline all cases when the 11256 // sizes of types of LHS and RHS do not match. 11257 // TODO: Maybe try to get RHS from sext to catch more cases? 11258 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11259 return false; 11260 11261 // Should not overflow. 11262 if (!LHSAddExpr->hasNoSignedWrap()) 11263 return false; 11264 11265 auto *LL = LHSAddExpr->getOperand(0); 11266 auto *LR = LHSAddExpr->getOperand(1); 11267 auto *MinusOne = getMinusOne(RHS->getType()); 11268 11269 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11270 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11271 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11272 }; 11273 // Try to prove the following rule: 11274 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11275 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11276 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11277 return true; 11278 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11279 Value *LL, *LR; 11280 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11281 11282 using namespace llvm::PatternMatch; 11283 11284 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11285 // Rules for division. 11286 // We are going to perform some comparisons with Denominator and its 11287 // derivative expressions. In general case, creating a SCEV for it may 11288 // lead to a complex analysis of the entire graph, and in particular it 11289 // can request trip count recalculation for the same loop. This would 11290 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11291 // this, we only want to create SCEVs that are constants in this section. 11292 // So we bail if Denominator is not a constant. 11293 if (!isa<ConstantInt>(LR)) 11294 return false; 11295 11296 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11297 11298 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11299 // then a SCEV for the numerator already exists and matches with FoundLHS. 11300 auto *Numerator = getExistingSCEV(LL); 11301 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11302 return false; 11303 11304 // Make sure that the numerator matches with FoundLHS and the denominator 11305 // is positive. 11306 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11307 return false; 11308 11309 auto *DTy = Denominator->getType(); 11310 auto *FRHSTy = FoundRHS->getType(); 11311 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11312 // One of types is a pointer and another one is not. We cannot extend 11313 // them properly to a wider type, so let us just reject this case. 11314 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11315 // to avoid this check. 11316 return false; 11317 11318 // Given that: 11319 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11320 auto *WTy = getWiderType(DTy, FRHSTy); 11321 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11322 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11323 11324 // Try to prove the following rule: 11325 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11326 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11327 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11328 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11329 if (isKnownNonPositive(RHS) && 11330 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11331 return true; 11332 11333 // Try to prove the following rule: 11334 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11335 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11336 // If we divide it by Denominator > 2, then: 11337 // 1. If FoundLHS is negative, then the result is 0. 11338 // 2. If FoundLHS is non-negative, then the result is non-negative. 11339 // Anyways, the result is non-negative. 11340 auto *MinusOne = getMinusOne(WTy); 11341 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11342 if (isKnownNegative(RHS) && 11343 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11344 return true; 11345 } 11346 } 11347 11348 // If our expression contained SCEVUnknown Phis, and we split it down and now 11349 // need to prove something for them, try to prove the predicate for every 11350 // possible incoming values of those Phis. 11351 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11352 return true; 11353 11354 return false; 11355 } 11356 11357 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11358 const SCEV *LHS, const SCEV *RHS) { 11359 // zext x u<= sext x, sext x s<= zext x 11360 switch (Pred) { 11361 case ICmpInst::ICMP_SGE: 11362 std::swap(LHS, RHS); 11363 LLVM_FALLTHROUGH; 11364 case ICmpInst::ICMP_SLE: { 11365 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11366 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11367 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11368 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11369 return true; 11370 break; 11371 } 11372 case ICmpInst::ICMP_UGE: 11373 std::swap(LHS, RHS); 11374 LLVM_FALLTHROUGH; 11375 case ICmpInst::ICMP_ULE: { 11376 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11377 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11378 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11379 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11380 return true; 11381 break; 11382 } 11383 default: 11384 break; 11385 }; 11386 return false; 11387 } 11388 11389 bool 11390 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11391 const SCEV *LHS, const SCEV *RHS) { 11392 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11393 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11394 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11395 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11396 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11397 } 11398 11399 bool 11400 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11401 const SCEV *LHS, const SCEV *RHS, 11402 const SCEV *FoundLHS, 11403 const SCEV *FoundRHS) { 11404 switch (Pred) { 11405 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11406 case ICmpInst::ICMP_EQ: 11407 case ICmpInst::ICMP_NE: 11408 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11409 return true; 11410 break; 11411 case ICmpInst::ICMP_SLT: 11412 case ICmpInst::ICMP_SLE: 11413 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11414 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11415 return true; 11416 break; 11417 case ICmpInst::ICMP_SGT: 11418 case ICmpInst::ICMP_SGE: 11419 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11420 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11421 return true; 11422 break; 11423 case ICmpInst::ICMP_ULT: 11424 case ICmpInst::ICMP_ULE: 11425 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11426 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11427 return true; 11428 break; 11429 case ICmpInst::ICMP_UGT: 11430 case ICmpInst::ICMP_UGE: 11431 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11432 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11433 return true; 11434 break; 11435 } 11436 11437 // Maybe it can be proved via operations? 11438 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11439 return true; 11440 11441 return false; 11442 } 11443 11444 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11445 const SCEV *LHS, 11446 const SCEV *RHS, 11447 const SCEV *FoundLHS, 11448 const SCEV *FoundRHS) { 11449 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11450 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11451 // reduce the compile time impact of this optimization. 11452 return false; 11453 11454 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11455 if (!Addend) 11456 return false; 11457 11458 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11459 11460 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11461 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11462 ConstantRange FoundLHSRange = 11463 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11464 11465 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11466 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11467 11468 // We can also compute the range of values for `LHS` that satisfy the 11469 // consequent, "`LHS` `Pred` `RHS`": 11470 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11471 // The antecedent implies the consequent if every value of `LHS` that 11472 // satisfies the antecedent also satisfies the consequent. 11473 return LHSRange.icmp(Pred, ConstRHS); 11474 } 11475 11476 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11477 bool IsSigned) { 11478 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11479 11480 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11481 const SCEV *One = getOne(Stride->getType()); 11482 11483 if (IsSigned) { 11484 APInt MaxRHS = getSignedRangeMax(RHS); 11485 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11486 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11487 11488 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11489 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11490 } 11491 11492 APInt MaxRHS = getUnsignedRangeMax(RHS); 11493 APInt MaxValue = APInt::getMaxValue(BitWidth); 11494 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11495 11496 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11497 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11498 } 11499 11500 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11501 bool IsSigned) { 11502 11503 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11504 const SCEV *One = getOne(Stride->getType()); 11505 11506 if (IsSigned) { 11507 APInt MinRHS = getSignedRangeMin(RHS); 11508 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11509 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11510 11511 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11512 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11513 } 11514 11515 APInt MinRHS = getUnsignedRangeMin(RHS); 11516 APInt MinValue = APInt::getMinValue(BitWidth); 11517 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11518 11519 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11520 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11521 } 11522 11523 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11524 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11525 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11526 // expression fixes the case of N=0. 11527 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11528 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11529 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11530 } 11531 11532 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11533 const SCEV *Stride, 11534 const SCEV *End, 11535 unsigned BitWidth, 11536 bool IsSigned) { 11537 // The logic in this function assumes we can represent a positive stride. 11538 // If we can't, the backedge-taken count must be zero. 11539 if (IsSigned && BitWidth == 1) 11540 return getZero(Stride->getType()); 11541 11542 // Calculate the maximum backedge count based on the range of values 11543 // permitted by Start, End, and Stride. 11544 APInt MinStart = 11545 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11546 11547 APInt MinStride = 11548 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11549 11550 // We assume either the stride is positive, or the backedge-taken count 11551 // is zero. So force StrideForMaxBECount to be at least one. 11552 APInt One(BitWidth, 1); 11553 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11554 : APIntOps::umax(One, MinStride); 11555 11556 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11557 : APInt::getMaxValue(BitWidth); 11558 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11559 11560 // Although End can be a MAX expression we estimate MaxEnd considering only 11561 // the case End = RHS of the loop termination condition. This is safe because 11562 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11563 // taken count. 11564 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11565 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11566 11567 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11568 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11569 : APIntOps::umax(MaxEnd, MinStart); 11570 11571 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11572 getConstant(StrideForMaxBECount) /* Step */); 11573 } 11574 11575 ScalarEvolution::ExitLimit 11576 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11577 const Loop *L, bool IsSigned, 11578 bool ControlsExit, bool AllowPredicates) { 11579 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11580 11581 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11582 bool PredicatedIV = false; 11583 11584 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11585 // Can we prove this loop *must* be UB if overflow of IV occurs? 11586 // Reasoning goes as follows: 11587 // * Suppose the IV did self wrap. 11588 // * If Stride evenly divides the iteration space, then once wrap 11589 // occurs, the loop must revisit the same values. 11590 // * We know that RHS is invariant, and that none of those values 11591 // caused this exit to be taken previously. Thus, this exit is 11592 // dynamically dead. 11593 // * If this is the sole exit, then a dead exit implies the loop 11594 // must be infinite if there are no abnormal exits. 11595 // * If the loop were infinite, then it must either not be mustprogress 11596 // or have side effects. Otherwise, it must be UB. 11597 // * It can't (by assumption), be UB so we have contradicted our 11598 // premise and can conclude the IV did not in fact self-wrap. 11599 if (!isLoopInvariant(RHS, L)) 11600 return false; 11601 11602 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11603 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11604 return false; 11605 11606 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11607 return false; 11608 11609 return loopIsFiniteByAssumption(L); 11610 }; 11611 11612 if (!IV) { 11613 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11614 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11615 if (AR && AR->getLoop() == L && AR->isAffine()) { 11616 auto Flags = AR->getNoWrapFlags(); 11617 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11618 Flags = setFlags(Flags, SCEV::FlagNW); 11619 11620 SmallVector<const SCEV*> Operands{AR->operands()}; 11621 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11622 11623 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11624 } 11625 if (AR->hasNoUnsignedWrap()) { 11626 // Emulate what getZeroExtendExpr would have done during construction 11627 // if we'd been able to infer the fact just above at that time. 11628 const SCEV *Step = AR->getStepRecurrence(*this); 11629 Type *Ty = ZExt->getType(); 11630 auto *S = getAddRecExpr( 11631 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11632 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11633 IV = dyn_cast<SCEVAddRecExpr>(S); 11634 } 11635 } 11636 } 11637 } 11638 11639 11640 if (!IV && AllowPredicates) { 11641 // Try to make this an AddRec using runtime tests, in the first X 11642 // iterations of this loop, where X is the SCEV expression found by the 11643 // algorithm below. 11644 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11645 PredicatedIV = true; 11646 } 11647 11648 // Avoid weird loops 11649 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11650 return getCouldNotCompute(); 11651 11652 // A precondition of this method is that the condition being analyzed 11653 // reaches an exiting branch which dominates the latch. Given that, we can 11654 // assume that an increment which violates the nowrap specification and 11655 // produces poison must cause undefined behavior when the resulting poison 11656 // value is branched upon and thus we can conclude that the backedge is 11657 // taken no more often than would be required to produce that poison value. 11658 // Note that a well defined loop can exit on the iteration which violates 11659 // the nowrap specification if there is another exit (either explicit or 11660 // implicit/exceptional) which causes the loop to execute before the 11661 // exiting instruction we're analyzing would trigger UB. 11662 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11663 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11664 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11665 11666 const SCEV *Stride = IV->getStepRecurrence(*this); 11667 11668 bool PositiveStride = isKnownPositive(Stride); 11669 11670 // Avoid negative or zero stride values. 11671 if (!PositiveStride) { 11672 // We can compute the correct backedge taken count for loops with unknown 11673 // strides if we can prove that the loop is not an infinite loop with side 11674 // effects. Here's the loop structure we are trying to handle - 11675 // 11676 // i = start 11677 // do { 11678 // A[i] = i; 11679 // i += s; 11680 // } while (i < end); 11681 // 11682 // The backedge taken count for such loops is evaluated as - 11683 // (max(end, start + stride) - start - 1) /u stride 11684 // 11685 // The additional preconditions that we need to check to prove correctness 11686 // of the above formula is as follows - 11687 // 11688 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11689 // NoWrap flag). 11690 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11691 // no side effects within the loop) 11692 // c) loop has a single static exit (with no abnormal exits) 11693 // 11694 // Precondition a) implies that if the stride is negative, this is a single 11695 // trip loop. The backedge taken count formula reduces to zero in this case. 11696 // 11697 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11698 // then a zero stride means the backedge can't be taken without executing 11699 // undefined behavior. 11700 // 11701 // The positive stride case is the same as isKnownPositive(Stride) returning 11702 // true (original behavior of the function). 11703 // 11704 // We want to make sure that the stride is truly unknown as there are edge 11705 // cases where ScalarEvolution propagates no wrap flags to the 11706 // post-increment/decrement IV even though the increment/decrement operation 11707 // itself is wrapping. The computed backedge taken count may be wrong in 11708 // such cases. This is prevented by checking that the stride is not known to 11709 // be either positive or non-positive. For example, no wrap flags are 11710 // propagated to the post-increment IV of this loop with a trip count of 2 - 11711 // 11712 // unsigned char i; 11713 // for(i=127; i<128; i+=129) 11714 // A[i] = i; 11715 // 11716 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11717 !loopIsFiniteByAssumption(L) || !loopHasNoAbnormalExits(L)) 11718 return getCouldNotCompute(); 11719 11720 if (!isKnownNonZero(Stride)) { 11721 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11722 // if it might eventually be greater than start and if so, on which 11723 // iteration. We can't even produce a useful upper bound. 11724 if (!isLoopInvariant(RHS, L)) 11725 return getCouldNotCompute(); 11726 11727 // We allow a potentially zero stride, but we need to divide by stride 11728 // below. Since the loop can't be infinite and this check must control 11729 // the sole exit, we can infer the exit must be taken on the first 11730 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11731 // we know the numerator in the divides below must be zero, so we can 11732 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11733 // and produce the right result. 11734 // FIXME: Handle the case where Stride is poison? 11735 auto wouldZeroStrideBeUB = [&]() { 11736 // Proof by contradiction. Suppose the stride were zero. If we can 11737 // prove that the backedge *is* taken on the first iteration, then since 11738 // we know this condition controls the sole exit, we must have an 11739 // infinite loop. We can't have a (well defined) infinite loop per 11740 // check just above. 11741 // Note: The (Start - Stride) term is used to get the start' term from 11742 // (start' + stride,+,stride). Remember that we only care about the 11743 // result of this expression when stride == 0 at runtime. 11744 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11745 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11746 }; 11747 if (!wouldZeroStrideBeUB()) { 11748 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11749 } 11750 } 11751 } else if (!Stride->isOne() && !NoWrap) { 11752 auto isUBOnWrap = [&]() { 11753 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11754 // follows trivially from the fact that every (un)signed-wrapped, but 11755 // not self-wrapped value must be LT than the last value before 11756 // (un)signed wrap. Since we know that last value didn't exit, nor 11757 // will any smaller one. 11758 return canAssumeNoSelfWrap(IV); 11759 }; 11760 11761 // Avoid proven overflow cases: this will ensure that the backedge taken 11762 // count will not generate any unsigned overflow. Relaxed no-overflow 11763 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11764 // undefined behaviors like the case of C language. 11765 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11766 return getCouldNotCompute(); 11767 } 11768 11769 // On all paths just preceeding, we established the following invariant: 11770 // IV can be assumed not to overflow up to and including the exiting 11771 // iteration. We proved this in one of two ways: 11772 // 1) We can show overflow doesn't occur before the exiting iteration 11773 // 1a) canIVOverflowOnLT, and b) step of one 11774 // 2) We can show that if overflow occurs, the loop must execute UB 11775 // before any possible exit. 11776 // Note that we have not yet proved RHS invariant (in general). 11777 11778 const SCEV *Start = IV->getStart(); 11779 11780 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11781 // Use integer-typed versions for actual computation. 11782 const SCEV *OrigStart = Start; 11783 const SCEV *OrigRHS = RHS; 11784 if (Start->getType()->isPointerTy()) { 11785 Start = getLosslessPtrToIntExpr(Start); 11786 if (isa<SCEVCouldNotCompute>(Start)) 11787 return Start; 11788 } 11789 if (RHS->getType()->isPointerTy()) { 11790 RHS = getLosslessPtrToIntExpr(RHS); 11791 if (isa<SCEVCouldNotCompute>(RHS)) 11792 return RHS; 11793 } 11794 11795 // When the RHS is not invariant, we do not know the end bound of the loop and 11796 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11797 // calculate the MaxBECount, given the start, stride and max value for the end 11798 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11799 // checked above). 11800 if (!isLoopInvariant(RHS, L)) { 11801 const SCEV *MaxBECount = computeMaxBECountForLT( 11802 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11803 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11804 false /*MaxOrZero*/, Predicates); 11805 } 11806 11807 // We use the expression (max(End,Start)-Start)/Stride to describe the 11808 // backedge count, as if the backedge is taken at least once max(End,Start) 11809 // is End and so the result is as above, and if not max(End,Start) is Start 11810 // so we get a backedge count of zero. 11811 const SCEV *BECount = nullptr; 11812 auto *StartMinusStride = getMinusSCEV(OrigStart, Stride); 11813 // Can we prove (max(RHS,Start) > Start - Stride? 11814 if (isLoopEntryGuardedByCond(L, Cond, StartMinusStride, Start) && 11815 isLoopEntryGuardedByCond(L, Cond, StartMinusStride, RHS)) { 11816 // In this case, we can use a refined formula for computing backedge taken 11817 // count. The general formula remains: 11818 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11819 // We want to use the alternate formula: 11820 // "((End - 1) - (Start - Stride)) /u Stride" 11821 // Let's do a quick case analysis to show these are equivalent under 11822 // our precondition that max(RHS,Start) > Start - Stride. 11823 // * For RHS <= Start, the backedge-taken count must be zero. 11824 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11825 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11826 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11827 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11828 // this to the stride of 1 case. 11829 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11830 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11831 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11832 // "((RHS - (Start - Stride) - 1) /u Stride". 11833 // Our preconditions trivially imply no overflow in that form. 11834 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11835 const SCEV *Numerator = 11836 getMinusSCEV(getAddExpr(RHS, MinusOne), StartMinusStride); 11837 if (!isa<SCEVCouldNotCompute>(Numerator)) { 11838 BECount = getUDivExpr(Numerator, Stride); 11839 } 11840 } 11841 11842 const SCEV *BECountIfBackedgeTaken = nullptr; 11843 if (!BECount) { 11844 auto canProveRHSGreaterThanEqualStart = [&]() { 11845 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11846 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11847 return true; 11848 11849 // (RHS > Start - 1) implies RHS >= Start. 11850 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11851 // "Start - 1" doesn't overflow. 11852 // * For signed comparison, if Start - 1 does overflow, it's equal 11853 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11854 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11855 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11856 // 11857 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11858 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11859 auto *StartMinusOne = getAddExpr(OrigStart, 11860 getMinusOne(OrigStart->getType())); 11861 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11862 }; 11863 11864 // If we know that RHS >= Start in the context of loop, then we know that 11865 // max(RHS, Start) = RHS at this point. 11866 const SCEV *End; 11867 if (canProveRHSGreaterThanEqualStart()) { 11868 End = RHS; 11869 } else { 11870 // If RHS < Start, the backedge will be taken zero times. So in 11871 // general, we can write the backedge-taken count as: 11872 // 11873 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11874 // 11875 // We convert it to the following to make it more convenient for SCEV: 11876 // 11877 // ceil(max(RHS, Start) - Start) / Stride 11878 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11879 11880 // See what would happen if we assume the backedge is taken. This is 11881 // used to compute MaxBECount. 11882 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11883 } 11884 11885 // At this point, we know: 11886 // 11887 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11888 // 2. The index variable doesn't overflow. 11889 // 11890 // Therefore, we know N exists such that 11891 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11892 // doesn't overflow. 11893 // 11894 // Using this information, try to prove whether the addition in 11895 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11896 const SCEV *One = getOne(Stride->getType()); 11897 bool MayAddOverflow = [&] { 11898 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11899 if (StrideC->getAPInt().isPowerOf2()) { 11900 // Suppose Stride is a power of two, and Start/End are unsigned 11901 // integers. Let UMAX be the largest representable unsigned 11902 // integer. 11903 // 11904 // By the preconditions of this function, we know 11905 // "(Start + Stride * N) >= End", and this doesn't overflow. 11906 // As a formula: 11907 // 11908 // End <= (Start + Stride * N) <= UMAX 11909 // 11910 // Subtracting Start from all the terms: 11911 // 11912 // End - Start <= Stride * N <= UMAX - Start 11913 // 11914 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11915 // 11916 // End - Start <= Stride * N <= UMAX 11917 // 11918 // Stride * N is a multiple of Stride. Therefore, 11919 // 11920 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11921 // 11922 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11923 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11924 // 11925 // End - Start <= Stride * N <= UMAX - Stride - 1 11926 // 11927 // Dropping the middle term: 11928 // 11929 // End - Start <= UMAX - Stride - 1 11930 // 11931 // Adding Stride - 1 to both sides: 11932 // 11933 // (End - Start) + (Stride - 1) <= UMAX 11934 // 11935 // In other words, the addition doesn't have unsigned overflow. 11936 // 11937 // A similar proof works if we treat Start/End as signed values. 11938 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11939 // use signed max instead of unsigned max. Note that we're trying 11940 // to prove a lack of unsigned overflow in either case. 11941 return false; 11942 } 11943 } 11944 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 11945 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 11946 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 11947 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 11948 // 11949 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 11950 return false; 11951 } 11952 return true; 11953 }(); 11954 11955 const SCEV *Delta = getMinusSCEV(End, Start); 11956 if (!MayAddOverflow) { 11957 // floor((D + (S - 1)) / S) 11958 // We prefer this formulation if it's legal because it's fewer operations. 11959 BECount = 11960 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 11961 } else { 11962 BECount = getUDivCeilSCEV(Delta, Stride); 11963 } 11964 } 11965 11966 const SCEV *MaxBECount; 11967 bool MaxOrZero = false; 11968 if (isa<SCEVConstant>(BECount)) { 11969 MaxBECount = BECount; 11970 } else if (BECountIfBackedgeTaken && 11971 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11972 // If we know exactly how many times the backedge will be taken if it's 11973 // taken at least once, then the backedge count will either be that or 11974 // zero. 11975 MaxBECount = BECountIfBackedgeTaken; 11976 MaxOrZero = true; 11977 } else { 11978 MaxBECount = computeMaxBECountForLT( 11979 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11980 } 11981 11982 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11983 !isa<SCEVCouldNotCompute>(BECount)) 11984 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11985 11986 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11987 } 11988 11989 ScalarEvolution::ExitLimit 11990 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11991 const Loop *L, bool IsSigned, 11992 bool ControlsExit, bool AllowPredicates) { 11993 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11994 // We handle only IV > Invariant 11995 if (!isLoopInvariant(RHS, L)) 11996 return getCouldNotCompute(); 11997 11998 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11999 if (!IV && AllowPredicates) 12000 // Try to make this an AddRec using runtime tests, in the first X 12001 // iterations of this loop, where X is the SCEV expression found by the 12002 // algorithm below. 12003 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12004 12005 // Avoid weird loops 12006 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12007 return getCouldNotCompute(); 12008 12009 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12010 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12011 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12012 12013 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12014 12015 // Avoid negative or zero stride values 12016 if (!isKnownPositive(Stride)) 12017 return getCouldNotCompute(); 12018 12019 // Avoid proven overflow cases: this will ensure that the backedge taken count 12020 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12021 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12022 // behaviors like the case of C language. 12023 if (!Stride->isOne() && !NoWrap) 12024 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12025 return getCouldNotCompute(); 12026 12027 const SCEV *Start = IV->getStart(); 12028 const SCEV *End = RHS; 12029 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12030 // If we know that Start >= RHS in the context of loop, then we know that 12031 // min(RHS, Start) = RHS at this point. 12032 if (isLoopEntryGuardedByCond( 12033 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12034 End = RHS; 12035 else 12036 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12037 } 12038 12039 if (Start->getType()->isPointerTy()) { 12040 Start = getLosslessPtrToIntExpr(Start); 12041 if (isa<SCEVCouldNotCompute>(Start)) 12042 return Start; 12043 } 12044 if (End->getType()->isPointerTy()) { 12045 End = getLosslessPtrToIntExpr(End); 12046 if (isa<SCEVCouldNotCompute>(End)) 12047 return End; 12048 } 12049 12050 // Compute ((Start - End) + (Stride - 1)) / Stride. 12051 // FIXME: This can overflow. Holding off on fixing this for now; 12052 // howManyGreaterThans will hopefully be gone soon. 12053 const SCEV *One = getOne(Stride->getType()); 12054 const SCEV *BECount = getUDivExpr( 12055 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12056 12057 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12058 : getUnsignedRangeMax(Start); 12059 12060 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12061 : getUnsignedRangeMin(Stride); 12062 12063 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12064 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12065 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12066 12067 // Although End can be a MIN expression we estimate MinEnd considering only 12068 // the case End = RHS. This is safe because in the other case (Start - End) 12069 // is zero, leading to a zero maximum backedge taken count. 12070 APInt MinEnd = 12071 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12072 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12073 12074 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12075 ? BECount 12076 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12077 getConstant(MinStride)); 12078 12079 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12080 MaxBECount = BECount; 12081 12082 return ExitLimit(BECount, MaxBECount, false, Predicates); 12083 } 12084 12085 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12086 ScalarEvolution &SE) const { 12087 if (Range.isFullSet()) // Infinite loop. 12088 return SE.getCouldNotCompute(); 12089 12090 // If the start is a non-zero constant, shift the range to simplify things. 12091 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12092 if (!SC->getValue()->isZero()) { 12093 SmallVector<const SCEV *, 4> Operands(operands()); 12094 Operands[0] = SE.getZero(SC->getType()); 12095 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12096 getNoWrapFlags(FlagNW)); 12097 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12098 return ShiftedAddRec->getNumIterationsInRange( 12099 Range.subtract(SC->getAPInt()), SE); 12100 // This is strange and shouldn't happen. 12101 return SE.getCouldNotCompute(); 12102 } 12103 12104 // The only time we can solve this is when we have all constant indices. 12105 // Otherwise, we cannot determine the overflow conditions. 12106 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12107 return SE.getCouldNotCompute(); 12108 12109 // Okay at this point we know that all elements of the chrec are constants and 12110 // that the start element is zero. 12111 12112 // First check to see if the range contains zero. If not, the first 12113 // iteration exits. 12114 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12115 if (!Range.contains(APInt(BitWidth, 0))) 12116 return SE.getZero(getType()); 12117 12118 if (isAffine()) { 12119 // If this is an affine expression then we have this situation: 12120 // Solve {0,+,A} in Range === Ax in Range 12121 12122 // We know that zero is in the range. If A is positive then we know that 12123 // the upper value of the range must be the first possible exit value. 12124 // If A is negative then the lower of the range is the last possible loop 12125 // value. Also note that we already checked for a full range. 12126 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12127 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12128 12129 // The exit value should be (End+A)/A. 12130 APInt ExitVal = (End + A).udiv(A); 12131 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12132 12133 // Evaluate at the exit value. If we really did fall out of the valid 12134 // range, then we computed our trip count, otherwise wrap around or other 12135 // things must have happened. 12136 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12137 if (Range.contains(Val->getValue())) 12138 return SE.getCouldNotCompute(); // Something strange happened 12139 12140 // Ensure that the previous value is in the range. This is a sanity check. 12141 assert(Range.contains( 12142 EvaluateConstantChrecAtConstant(this, 12143 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12144 "Linear scev computation is off in a bad way!"); 12145 return SE.getConstant(ExitValue); 12146 } 12147 12148 if (isQuadratic()) { 12149 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12150 return SE.getConstant(S.getValue()); 12151 } 12152 12153 return SE.getCouldNotCompute(); 12154 } 12155 12156 const SCEVAddRecExpr * 12157 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12158 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12159 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12160 // but in this case we cannot guarantee that the value returned will be an 12161 // AddRec because SCEV does not have a fixed point where it stops 12162 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12163 // may happen if we reach arithmetic depth limit while simplifying. So we 12164 // construct the returned value explicitly. 12165 SmallVector<const SCEV *, 3> Ops; 12166 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12167 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12168 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12169 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12170 // We know that the last operand is not a constant zero (otherwise it would 12171 // have been popped out earlier). This guarantees us that if the result has 12172 // the same last operand, then it will also not be popped out, meaning that 12173 // the returned value will be an AddRec. 12174 const SCEV *Last = getOperand(getNumOperands() - 1); 12175 assert(!Last->isZero() && "Recurrency with zero step?"); 12176 Ops.push_back(Last); 12177 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12178 SCEV::FlagAnyWrap)); 12179 } 12180 12181 // Return true when S contains at least an undef value. 12182 static inline bool containsUndefs(const SCEV *S) { 12183 return SCEVExprContains(S, [](const SCEV *S) { 12184 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12185 return isa<UndefValue>(SU->getValue()); 12186 return false; 12187 }); 12188 } 12189 12190 /// Return the size of an element read or written by Inst. 12191 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12192 Type *Ty; 12193 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12194 Ty = Store->getValueOperand()->getType(); 12195 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12196 Ty = Load->getType(); 12197 else 12198 return nullptr; 12199 12200 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12201 return getSizeOfExpr(ETy, Ty); 12202 } 12203 12204 //===----------------------------------------------------------------------===// 12205 // SCEVCallbackVH Class Implementation 12206 //===----------------------------------------------------------------------===// 12207 12208 void ScalarEvolution::SCEVCallbackVH::deleted() { 12209 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12210 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12211 SE->ConstantEvolutionLoopExitValue.erase(PN); 12212 SE->eraseValueFromMap(getValPtr()); 12213 // this now dangles! 12214 } 12215 12216 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12217 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12218 12219 // Forget all the expressions associated with users of the old value, 12220 // so that future queries will recompute the expressions using the new 12221 // value. 12222 Value *Old = getValPtr(); 12223 SmallVector<User *, 16> Worklist(Old->users()); 12224 SmallPtrSet<User *, 8> Visited; 12225 while (!Worklist.empty()) { 12226 User *U = Worklist.pop_back_val(); 12227 // Deleting the Old value will cause this to dangle. Postpone 12228 // that until everything else is done. 12229 if (U == Old) 12230 continue; 12231 if (!Visited.insert(U).second) 12232 continue; 12233 if (PHINode *PN = dyn_cast<PHINode>(U)) 12234 SE->ConstantEvolutionLoopExitValue.erase(PN); 12235 SE->eraseValueFromMap(U); 12236 llvm::append_range(Worklist, U->users()); 12237 } 12238 // Delete the Old value. 12239 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12240 SE->ConstantEvolutionLoopExitValue.erase(PN); 12241 SE->eraseValueFromMap(Old); 12242 // this now dangles! 12243 } 12244 12245 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12246 : CallbackVH(V), SE(se) {} 12247 12248 //===----------------------------------------------------------------------===// 12249 // ScalarEvolution Class Implementation 12250 //===----------------------------------------------------------------------===// 12251 12252 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12253 AssumptionCache &AC, DominatorTree &DT, 12254 LoopInfo &LI) 12255 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12256 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12257 LoopDispositions(64), BlockDispositions(64) { 12258 // To use guards for proving predicates, we need to scan every instruction in 12259 // relevant basic blocks, and not just terminators. Doing this is a waste of 12260 // time if the IR does not actually contain any calls to 12261 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12262 // 12263 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12264 // to _add_ guards to the module when there weren't any before, and wants 12265 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12266 // efficient in lieu of being smart in that rather obscure case. 12267 12268 auto *GuardDecl = F.getParent()->getFunction( 12269 Intrinsic::getName(Intrinsic::experimental_guard)); 12270 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12271 } 12272 12273 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12274 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12275 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12276 ValueExprMap(std::move(Arg.ValueExprMap)), 12277 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12278 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12279 PendingMerges(std::move(Arg.PendingMerges)), 12280 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12281 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12282 PredicatedBackedgeTakenCounts( 12283 std::move(Arg.PredicatedBackedgeTakenCounts)), 12284 ConstantEvolutionLoopExitValue( 12285 std::move(Arg.ConstantEvolutionLoopExitValue)), 12286 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12287 LoopDispositions(std::move(Arg.LoopDispositions)), 12288 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12289 BlockDispositions(std::move(Arg.BlockDispositions)), 12290 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12291 SignedRanges(std::move(Arg.SignedRanges)), 12292 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12293 UniquePreds(std::move(Arg.UniquePreds)), 12294 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12295 LoopUsers(std::move(Arg.LoopUsers)), 12296 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12297 FirstUnknown(Arg.FirstUnknown) { 12298 Arg.FirstUnknown = nullptr; 12299 } 12300 12301 ScalarEvolution::~ScalarEvolution() { 12302 // Iterate through all the SCEVUnknown instances and call their 12303 // destructors, so that they release their references to their values. 12304 for (SCEVUnknown *U = FirstUnknown; U;) { 12305 SCEVUnknown *Tmp = U; 12306 U = U->Next; 12307 Tmp->~SCEVUnknown(); 12308 } 12309 FirstUnknown = nullptr; 12310 12311 ExprValueMap.clear(); 12312 ValueExprMap.clear(); 12313 HasRecMap.clear(); 12314 BackedgeTakenCounts.clear(); 12315 PredicatedBackedgeTakenCounts.clear(); 12316 12317 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12318 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12319 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12320 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12321 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12322 } 12323 12324 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12325 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12326 } 12327 12328 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12329 const Loop *L) { 12330 // Print all inner loops first 12331 for (Loop *I : *L) 12332 PrintLoopInfo(OS, SE, I); 12333 12334 OS << "Loop "; 12335 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12336 OS << ": "; 12337 12338 SmallVector<BasicBlock *, 8> ExitingBlocks; 12339 L->getExitingBlocks(ExitingBlocks); 12340 if (ExitingBlocks.size() != 1) 12341 OS << "<multiple exits> "; 12342 12343 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12344 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12345 else 12346 OS << "Unpredictable backedge-taken count.\n"; 12347 12348 if (ExitingBlocks.size() > 1) 12349 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12350 OS << " exit count for " << ExitingBlock->getName() << ": " 12351 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12352 } 12353 12354 OS << "Loop "; 12355 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12356 OS << ": "; 12357 12358 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12359 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12360 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12361 OS << ", actual taken count either this or zero."; 12362 } else { 12363 OS << "Unpredictable max backedge-taken count. "; 12364 } 12365 12366 OS << "\n" 12367 "Loop "; 12368 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12369 OS << ": "; 12370 12371 SCEVUnionPredicate Pred; 12372 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12373 if (!isa<SCEVCouldNotCompute>(PBT)) { 12374 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12375 OS << " Predicates:\n"; 12376 Pred.print(OS, 4); 12377 } else { 12378 OS << "Unpredictable predicated backedge-taken count. "; 12379 } 12380 OS << "\n"; 12381 12382 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12383 OS << "Loop "; 12384 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12385 OS << ": "; 12386 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12387 } 12388 } 12389 12390 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12391 switch (LD) { 12392 case ScalarEvolution::LoopVariant: 12393 return "Variant"; 12394 case ScalarEvolution::LoopInvariant: 12395 return "Invariant"; 12396 case ScalarEvolution::LoopComputable: 12397 return "Computable"; 12398 } 12399 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12400 } 12401 12402 void ScalarEvolution::print(raw_ostream &OS) const { 12403 // ScalarEvolution's implementation of the print method is to print 12404 // out SCEV values of all instructions that are interesting. Doing 12405 // this potentially causes it to create new SCEV objects though, 12406 // which technically conflicts with the const qualifier. This isn't 12407 // observable from outside the class though, so casting away the 12408 // const isn't dangerous. 12409 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12410 12411 if (ClassifyExpressions) { 12412 OS << "Classifying expressions for: "; 12413 F.printAsOperand(OS, /*PrintType=*/false); 12414 OS << "\n"; 12415 for (Instruction &I : instructions(F)) 12416 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12417 OS << I << '\n'; 12418 OS << " --> "; 12419 const SCEV *SV = SE.getSCEV(&I); 12420 SV->print(OS); 12421 if (!isa<SCEVCouldNotCompute>(SV)) { 12422 OS << " U: "; 12423 SE.getUnsignedRange(SV).print(OS); 12424 OS << " S: "; 12425 SE.getSignedRange(SV).print(OS); 12426 } 12427 12428 const Loop *L = LI.getLoopFor(I.getParent()); 12429 12430 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12431 if (AtUse != SV) { 12432 OS << " --> "; 12433 AtUse->print(OS); 12434 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12435 OS << " U: "; 12436 SE.getUnsignedRange(AtUse).print(OS); 12437 OS << " S: "; 12438 SE.getSignedRange(AtUse).print(OS); 12439 } 12440 } 12441 12442 if (L) { 12443 OS << "\t\t" "Exits: "; 12444 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12445 if (!SE.isLoopInvariant(ExitValue, L)) { 12446 OS << "<<Unknown>>"; 12447 } else { 12448 OS << *ExitValue; 12449 } 12450 12451 bool First = true; 12452 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12453 if (First) { 12454 OS << "\t\t" "LoopDispositions: { "; 12455 First = false; 12456 } else { 12457 OS << ", "; 12458 } 12459 12460 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12461 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12462 } 12463 12464 for (auto *InnerL : depth_first(L)) { 12465 if (InnerL == L) 12466 continue; 12467 if (First) { 12468 OS << "\t\t" "LoopDispositions: { "; 12469 First = false; 12470 } else { 12471 OS << ", "; 12472 } 12473 12474 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12475 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12476 } 12477 12478 OS << " }"; 12479 } 12480 12481 OS << "\n"; 12482 } 12483 } 12484 12485 OS << "Determining loop execution counts for: "; 12486 F.printAsOperand(OS, /*PrintType=*/false); 12487 OS << "\n"; 12488 for (Loop *I : LI) 12489 PrintLoopInfo(OS, &SE, I); 12490 } 12491 12492 ScalarEvolution::LoopDisposition 12493 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12494 auto &Values = LoopDispositions[S]; 12495 for (auto &V : Values) { 12496 if (V.getPointer() == L) 12497 return V.getInt(); 12498 } 12499 Values.emplace_back(L, LoopVariant); 12500 LoopDisposition D = computeLoopDisposition(S, L); 12501 auto &Values2 = LoopDispositions[S]; 12502 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12503 if (V.getPointer() == L) { 12504 V.setInt(D); 12505 break; 12506 } 12507 } 12508 return D; 12509 } 12510 12511 ScalarEvolution::LoopDisposition 12512 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12513 switch (S->getSCEVType()) { 12514 case scConstant: 12515 return LoopInvariant; 12516 case scPtrToInt: 12517 case scTruncate: 12518 case scZeroExtend: 12519 case scSignExtend: 12520 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12521 case scAddRecExpr: { 12522 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12523 12524 // If L is the addrec's loop, it's computable. 12525 if (AR->getLoop() == L) 12526 return LoopComputable; 12527 12528 // Add recurrences are never invariant in the function-body (null loop). 12529 if (!L) 12530 return LoopVariant; 12531 12532 // Everything that is not defined at loop entry is variant. 12533 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12534 return LoopVariant; 12535 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12536 " dominate the contained loop's header?"); 12537 12538 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12539 if (AR->getLoop()->contains(L)) 12540 return LoopInvariant; 12541 12542 // This recurrence is variant w.r.t. L if any of its operands 12543 // are variant. 12544 for (auto *Op : AR->operands()) 12545 if (!isLoopInvariant(Op, L)) 12546 return LoopVariant; 12547 12548 // Otherwise it's loop-invariant. 12549 return LoopInvariant; 12550 } 12551 case scAddExpr: 12552 case scMulExpr: 12553 case scUMaxExpr: 12554 case scSMaxExpr: 12555 case scUMinExpr: 12556 case scSMinExpr: { 12557 bool HasVarying = false; 12558 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12559 LoopDisposition D = getLoopDisposition(Op, L); 12560 if (D == LoopVariant) 12561 return LoopVariant; 12562 if (D == LoopComputable) 12563 HasVarying = true; 12564 } 12565 return HasVarying ? LoopComputable : LoopInvariant; 12566 } 12567 case scUDivExpr: { 12568 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12569 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12570 if (LD == LoopVariant) 12571 return LoopVariant; 12572 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12573 if (RD == LoopVariant) 12574 return LoopVariant; 12575 return (LD == LoopInvariant && RD == LoopInvariant) ? 12576 LoopInvariant : LoopComputable; 12577 } 12578 case scUnknown: 12579 // All non-instruction values are loop invariant. All instructions are loop 12580 // invariant if they are not contained in the specified loop. 12581 // Instructions are never considered invariant in the function body 12582 // (null loop) because they are defined within the "loop". 12583 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12584 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12585 return LoopInvariant; 12586 case scCouldNotCompute: 12587 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12588 } 12589 llvm_unreachable("Unknown SCEV kind!"); 12590 } 12591 12592 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12593 return getLoopDisposition(S, L) == LoopInvariant; 12594 } 12595 12596 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12597 return getLoopDisposition(S, L) == LoopComputable; 12598 } 12599 12600 ScalarEvolution::BlockDisposition 12601 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12602 auto &Values = BlockDispositions[S]; 12603 for (auto &V : Values) { 12604 if (V.getPointer() == BB) 12605 return V.getInt(); 12606 } 12607 Values.emplace_back(BB, DoesNotDominateBlock); 12608 BlockDisposition D = computeBlockDisposition(S, BB); 12609 auto &Values2 = BlockDispositions[S]; 12610 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12611 if (V.getPointer() == BB) { 12612 V.setInt(D); 12613 break; 12614 } 12615 } 12616 return D; 12617 } 12618 12619 ScalarEvolution::BlockDisposition 12620 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12621 switch (S->getSCEVType()) { 12622 case scConstant: 12623 return ProperlyDominatesBlock; 12624 case scPtrToInt: 12625 case scTruncate: 12626 case scZeroExtend: 12627 case scSignExtend: 12628 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12629 case scAddRecExpr: { 12630 // This uses a "dominates" query instead of "properly dominates" query 12631 // to test for proper dominance too, because the instruction which 12632 // produces the addrec's value is a PHI, and a PHI effectively properly 12633 // dominates its entire containing block. 12634 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12635 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12636 return DoesNotDominateBlock; 12637 12638 // Fall through into SCEVNAryExpr handling. 12639 LLVM_FALLTHROUGH; 12640 } 12641 case scAddExpr: 12642 case scMulExpr: 12643 case scUMaxExpr: 12644 case scSMaxExpr: 12645 case scUMinExpr: 12646 case scSMinExpr: { 12647 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12648 bool Proper = true; 12649 for (const SCEV *NAryOp : NAry->operands()) { 12650 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12651 if (D == DoesNotDominateBlock) 12652 return DoesNotDominateBlock; 12653 if (D == DominatesBlock) 12654 Proper = false; 12655 } 12656 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12657 } 12658 case scUDivExpr: { 12659 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12660 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12661 BlockDisposition LD = getBlockDisposition(LHS, BB); 12662 if (LD == DoesNotDominateBlock) 12663 return DoesNotDominateBlock; 12664 BlockDisposition RD = getBlockDisposition(RHS, BB); 12665 if (RD == DoesNotDominateBlock) 12666 return DoesNotDominateBlock; 12667 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12668 ProperlyDominatesBlock : DominatesBlock; 12669 } 12670 case scUnknown: 12671 if (Instruction *I = 12672 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12673 if (I->getParent() == BB) 12674 return DominatesBlock; 12675 if (DT.properlyDominates(I->getParent(), BB)) 12676 return ProperlyDominatesBlock; 12677 return DoesNotDominateBlock; 12678 } 12679 return ProperlyDominatesBlock; 12680 case scCouldNotCompute: 12681 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12682 } 12683 llvm_unreachable("Unknown SCEV kind!"); 12684 } 12685 12686 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12687 return getBlockDisposition(S, BB) >= DominatesBlock; 12688 } 12689 12690 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12691 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12692 } 12693 12694 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12695 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12696 } 12697 12698 void 12699 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12700 ValuesAtScopes.erase(S); 12701 LoopDispositions.erase(S); 12702 BlockDispositions.erase(S); 12703 UnsignedRanges.erase(S); 12704 SignedRanges.erase(S); 12705 ExprValueMap.erase(S); 12706 HasRecMap.erase(S); 12707 MinTrailingZerosCache.erase(S); 12708 12709 for (auto I = PredicatedSCEVRewrites.begin(); 12710 I != PredicatedSCEVRewrites.end();) { 12711 std::pair<const SCEV *, const Loop *> Entry = I->first; 12712 if (Entry.first == S) 12713 PredicatedSCEVRewrites.erase(I++); 12714 else 12715 ++I; 12716 } 12717 12718 auto RemoveSCEVFromBackedgeMap = 12719 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12720 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12721 BackedgeTakenInfo &BEInfo = I->second; 12722 if (BEInfo.hasOperand(S)) 12723 Map.erase(I++); 12724 else 12725 ++I; 12726 } 12727 }; 12728 12729 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12730 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12731 } 12732 12733 void 12734 ScalarEvolution::getUsedLoops(const SCEV *S, 12735 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12736 struct FindUsedLoops { 12737 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12738 : LoopsUsed(LoopsUsed) {} 12739 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12740 bool follow(const SCEV *S) { 12741 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12742 LoopsUsed.insert(AR->getLoop()); 12743 return true; 12744 } 12745 12746 bool isDone() const { return false; } 12747 }; 12748 12749 FindUsedLoops F(LoopsUsed); 12750 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12751 } 12752 12753 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12754 SmallPtrSet<const Loop *, 8> LoopsUsed; 12755 getUsedLoops(S, LoopsUsed); 12756 for (auto *L : LoopsUsed) 12757 LoopUsers[L].push_back(S); 12758 } 12759 12760 void ScalarEvolution::verify() const { 12761 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12762 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12763 12764 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12765 12766 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12767 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12768 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12769 12770 const SCEV *visitConstant(const SCEVConstant *Constant) { 12771 return SE.getConstant(Constant->getAPInt()); 12772 } 12773 12774 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12775 return SE.getUnknown(Expr->getValue()); 12776 } 12777 12778 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12779 return SE.getCouldNotCompute(); 12780 } 12781 }; 12782 12783 SCEVMapper SCM(SE2); 12784 12785 while (!LoopStack.empty()) { 12786 auto *L = LoopStack.pop_back_val(); 12787 llvm::append_range(LoopStack, *L); 12788 12789 auto *CurBECount = SCM.visit( 12790 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12791 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12792 12793 if (CurBECount == SE2.getCouldNotCompute() || 12794 NewBECount == SE2.getCouldNotCompute()) { 12795 // NB! This situation is legal, but is very suspicious -- whatever pass 12796 // change the loop to make a trip count go from could not compute to 12797 // computable or vice-versa *should have* invalidated SCEV. However, we 12798 // choose not to assert here (for now) since we don't want false 12799 // positives. 12800 continue; 12801 } 12802 12803 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12804 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12805 // not propagate undef aggressively). This means we can (and do) fail 12806 // verification in cases where a transform makes the trip count of a loop 12807 // go from "undef" to "undef+1" (say). The transform is fine, since in 12808 // both cases the loop iterates "undef" times, but SCEV thinks we 12809 // increased the trip count of the loop by 1 incorrectly. 12810 continue; 12811 } 12812 12813 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12814 SE.getTypeSizeInBits(NewBECount->getType())) 12815 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12816 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12817 SE.getTypeSizeInBits(NewBECount->getType())) 12818 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12819 12820 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12821 12822 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12823 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12824 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12825 dbgs() << "Old: " << *CurBECount << "\n"; 12826 dbgs() << "New: " << *NewBECount << "\n"; 12827 dbgs() << "Delta: " << *Delta << "\n"; 12828 std::abort(); 12829 } 12830 } 12831 12832 // Collect all valid loops currently in LoopInfo. 12833 SmallPtrSet<Loop *, 32> ValidLoops; 12834 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12835 while (!Worklist.empty()) { 12836 Loop *L = Worklist.pop_back_val(); 12837 if (ValidLoops.contains(L)) 12838 continue; 12839 ValidLoops.insert(L); 12840 Worklist.append(L->begin(), L->end()); 12841 } 12842 // Check for SCEV expressions referencing invalid/deleted loops. 12843 for (auto &KV : ValueExprMap) { 12844 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12845 if (!AR) 12846 continue; 12847 assert(ValidLoops.contains(AR->getLoop()) && 12848 "AddRec references invalid loop"); 12849 } 12850 } 12851 12852 bool ScalarEvolution::invalidate( 12853 Function &F, const PreservedAnalyses &PA, 12854 FunctionAnalysisManager::Invalidator &Inv) { 12855 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12856 // of its dependencies is invalidated. 12857 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12858 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12859 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12860 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12861 Inv.invalidate<LoopAnalysis>(F, PA); 12862 } 12863 12864 AnalysisKey ScalarEvolutionAnalysis::Key; 12865 12866 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12867 FunctionAnalysisManager &AM) { 12868 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12869 AM.getResult<AssumptionAnalysis>(F), 12870 AM.getResult<DominatorTreeAnalysis>(F), 12871 AM.getResult<LoopAnalysis>(F)); 12872 } 12873 12874 PreservedAnalyses 12875 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12876 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12877 return PreservedAnalyses::all(); 12878 } 12879 12880 PreservedAnalyses 12881 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12882 // For compatibility with opt's -analyze feature under legacy pass manager 12883 // which was not ported to NPM. This keeps tests using 12884 // update_analyze_test_checks.py working. 12885 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12886 << F.getName() << "':\n"; 12887 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12888 return PreservedAnalyses::all(); 12889 } 12890 12891 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12892 "Scalar Evolution Analysis", false, true) 12893 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12894 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12895 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12896 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12897 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12898 "Scalar Evolution Analysis", false, true) 12899 12900 char ScalarEvolutionWrapperPass::ID = 0; 12901 12902 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12903 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12904 } 12905 12906 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12907 SE.reset(new ScalarEvolution( 12908 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12909 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12910 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12911 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12912 return false; 12913 } 12914 12915 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12916 12917 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12918 SE->print(OS); 12919 } 12920 12921 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12922 if (!VerifySCEV) 12923 return; 12924 12925 SE->verify(); 12926 } 12927 12928 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12929 AU.setPreservesAll(); 12930 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12931 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12932 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12933 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12934 } 12935 12936 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12937 const SCEV *RHS) { 12938 FoldingSetNodeID ID; 12939 assert(LHS->getType() == RHS->getType() && 12940 "Type mismatch between LHS and RHS"); 12941 // Unique this node based on the arguments 12942 ID.AddInteger(SCEVPredicate::P_Equal); 12943 ID.AddPointer(LHS); 12944 ID.AddPointer(RHS); 12945 void *IP = nullptr; 12946 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12947 return S; 12948 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12949 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12950 UniquePreds.InsertNode(Eq, IP); 12951 return Eq; 12952 } 12953 12954 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12955 const SCEVAddRecExpr *AR, 12956 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12957 FoldingSetNodeID ID; 12958 // Unique this node based on the arguments 12959 ID.AddInteger(SCEVPredicate::P_Wrap); 12960 ID.AddPointer(AR); 12961 ID.AddInteger(AddedFlags); 12962 void *IP = nullptr; 12963 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12964 return S; 12965 auto *OF = new (SCEVAllocator) 12966 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12967 UniquePreds.InsertNode(OF, IP); 12968 return OF; 12969 } 12970 12971 namespace { 12972 12973 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12974 public: 12975 12976 /// Rewrites \p S in the context of a loop L and the SCEV predication 12977 /// infrastructure. 12978 /// 12979 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12980 /// equivalences present in \p Pred. 12981 /// 12982 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12983 /// \p NewPreds such that the result will be an AddRecExpr. 12984 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12985 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12986 SCEVUnionPredicate *Pred) { 12987 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12988 return Rewriter.visit(S); 12989 } 12990 12991 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12992 if (Pred) { 12993 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12994 for (auto *Pred : ExprPreds) 12995 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12996 if (IPred->getLHS() == Expr) 12997 return IPred->getRHS(); 12998 } 12999 return convertToAddRecWithPreds(Expr); 13000 } 13001 13002 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13003 const SCEV *Operand = visit(Expr->getOperand()); 13004 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13005 if (AR && AR->getLoop() == L && AR->isAffine()) { 13006 // This couldn't be folded because the operand didn't have the nuw 13007 // flag. Add the nusw flag as an assumption that we could make. 13008 const SCEV *Step = AR->getStepRecurrence(SE); 13009 Type *Ty = Expr->getType(); 13010 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13011 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13012 SE.getSignExtendExpr(Step, Ty), L, 13013 AR->getNoWrapFlags()); 13014 } 13015 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13016 } 13017 13018 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13019 const SCEV *Operand = visit(Expr->getOperand()); 13020 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13021 if (AR && AR->getLoop() == L && AR->isAffine()) { 13022 // This couldn't be folded because the operand didn't have the nsw 13023 // flag. Add the nssw flag as an assumption that we could make. 13024 const SCEV *Step = AR->getStepRecurrence(SE); 13025 Type *Ty = Expr->getType(); 13026 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13027 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13028 SE.getSignExtendExpr(Step, Ty), L, 13029 AR->getNoWrapFlags()); 13030 } 13031 return SE.getSignExtendExpr(Operand, Expr->getType()); 13032 } 13033 13034 private: 13035 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13036 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13037 SCEVUnionPredicate *Pred) 13038 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13039 13040 bool addOverflowAssumption(const SCEVPredicate *P) { 13041 if (!NewPreds) { 13042 // Check if we've already made this assumption. 13043 return Pred && Pred->implies(P); 13044 } 13045 NewPreds->insert(P); 13046 return true; 13047 } 13048 13049 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13050 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13051 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13052 return addOverflowAssumption(A); 13053 } 13054 13055 // If \p Expr represents a PHINode, we try to see if it can be represented 13056 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13057 // to add this predicate as a runtime overflow check, we return the AddRec. 13058 // If \p Expr does not meet these conditions (is not a PHI node, or we 13059 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13060 // return \p Expr. 13061 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13062 if (!isa<PHINode>(Expr->getValue())) 13063 return Expr; 13064 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13065 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13066 if (!PredicatedRewrite) 13067 return Expr; 13068 for (auto *P : PredicatedRewrite->second){ 13069 // Wrap predicates from outer loops are not supported. 13070 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13071 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13072 if (L != AR->getLoop()) 13073 return Expr; 13074 } 13075 if (!addOverflowAssumption(P)) 13076 return Expr; 13077 } 13078 return PredicatedRewrite->first; 13079 } 13080 13081 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13082 SCEVUnionPredicate *Pred; 13083 const Loop *L; 13084 }; 13085 13086 } // end anonymous namespace 13087 13088 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13089 SCEVUnionPredicate &Preds) { 13090 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13091 } 13092 13093 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13094 const SCEV *S, const Loop *L, 13095 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13096 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13097 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13098 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13099 13100 if (!AddRec) 13101 return nullptr; 13102 13103 // Since the transformation was successful, we can now transfer the SCEV 13104 // predicates. 13105 for (auto *P : TransformPreds) 13106 Preds.insert(P); 13107 13108 return AddRec; 13109 } 13110 13111 /// SCEV predicates 13112 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13113 SCEVPredicateKind Kind) 13114 : FastID(ID), Kind(Kind) {} 13115 13116 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13117 const SCEV *LHS, const SCEV *RHS) 13118 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13119 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13120 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13121 } 13122 13123 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13124 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13125 13126 if (!Op) 13127 return false; 13128 13129 return Op->LHS == LHS && Op->RHS == RHS; 13130 } 13131 13132 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13133 13134 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13135 13136 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13137 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13138 } 13139 13140 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13141 const SCEVAddRecExpr *AR, 13142 IncrementWrapFlags Flags) 13143 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13144 13145 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13146 13147 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13148 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13149 13150 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13151 } 13152 13153 bool SCEVWrapPredicate::isAlwaysTrue() const { 13154 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13155 IncrementWrapFlags IFlags = Flags; 13156 13157 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13158 IFlags = clearFlags(IFlags, IncrementNSSW); 13159 13160 return IFlags == IncrementAnyWrap; 13161 } 13162 13163 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13164 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13165 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13166 OS << "<nusw>"; 13167 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13168 OS << "<nssw>"; 13169 OS << "\n"; 13170 } 13171 13172 SCEVWrapPredicate::IncrementWrapFlags 13173 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13174 ScalarEvolution &SE) { 13175 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13176 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13177 13178 // We can safely transfer the NSW flag as NSSW. 13179 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13180 ImpliedFlags = IncrementNSSW; 13181 13182 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13183 // If the increment is positive, the SCEV NUW flag will also imply the 13184 // WrapPredicate NUSW flag. 13185 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13186 if (Step->getValue()->getValue().isNonNegative()) 13187 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13188 } 13189 13190 return ImpliedFlags; 13191 } 13192 13193 /// Union predicates don't get cached so create a dummy set ID for it. 13194 SCEVUnionPredicate::SCEVUnionPredicate() 13195 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13196 13197 bool SCEVUnionPredicate::isAlwaysTrue() const { 13198 return all_of(Preds, 13199 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13200 } 13201 13202 ArrayRef<const SCEVPredicate *> 13203 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13204 auto I = SCEVToPreds.find(Expr); 13205 if (I == SCEVToPreds.end()) 13206 return ArrayRef<const SCEVPredicate *>(); 13207 return I->second; 13208 } 13209 13210 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13211 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13212 return all_of(Set->Preds, 13213 [this](const SCEVPredicate *I) { return this->implies(I); }); 13214 13215 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13216 if (ScevPredsIt == SCEVToPreds.end()) 13217 return false; 13218 auto &SCEVPreds = ScevPredsIt->second; 13219 13220 return any_of(SCEVPreds, 13221 [N](const SCEVPredicate *I) { return I->implies(N); }); 13222 } 13223 13224 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13225 13226 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13227 for (auto Pred : Preds) 13228 Pred->print(OS, Depth); 13229 } 13230 13231 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13232 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13233 for (auto Pred : Set->Preds) 13234 add(Pred); 13235 return; 13236 } 13237 13238 if (implies(N)) 13239 return; 13240 13241 const SCEV *Key = N->getExpr(); 13242 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13243 " associated expression!"); 13244 13245 SCEVToPreds[Key].push_back(N); 13246 Preds.push_back(N); 13247 } 13248 13249 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13250 Loop &L) 13251 : SE(SE), L(L) {} 13252 13253 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13254 const SCEV *Expr = SE.getSCEV(V); 13255 RewriteEntry &Entry = RewriteMap[Expr]; 13256 13257 // If we already have an entry and the version matches, return it. 13258 if (Entry.second && Generation == Entry.first) 13259 return Entry.second; 13260 13261 // We found an entry but it's stale. Rewrite the stale entry 13262 // according to the current predicate. 13263 if (Entry.second) 13264 Expr = Entry.second; 13265 13266 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13267 Entry = {Generation, NewSCEV}; 13268 13269 return NewSCEV; 13270 } 13271 13272 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13273 if (!BackedgeCount) { 13274 SCEVUnionPredicate BackedgePred; 13275 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13276 addPredicate(BackedgePred); 13277 } 13278 return BackedgeCount; 13279 } 13280 13281 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13282 if (Preds.implies(&Pred)) 13283 return; 13284 Preds.add(&Pred); 13285 updateGeneration(); 13286 } 13287 13288 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13289 return Preds; 13290 } 13291 13292 void PredicatedScalarEvolution::updateGeneration() { 13293 // If the generation number wrapped recompute everything. 13294 if (++Generation == 0) { 13295 for (auto &II : RewriteMap) { 13296 const SCEV *Rewritten = II.second.second; 13297 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13298 } 13299 } 13300 } 13301 13302 void PredicatedScalarEvolution::setNoOverflow( 13303 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13304 const SCEV *Expr = getSCEV(V); 13305 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13306 13307 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13308 13309 // Clear the statically implied flags. 13310 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13311 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13312 13313 auto II = FlagsMap.insert({V, Flags}); 13314 if (!II.second) 13315 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13316 } 13317 13318 bool PredicatedScalarEvolution::hasNoOverflow( 13319 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13320 const SCEV *Expr = getSCEV(V); 13321 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13322 13323 Flags = SCEVWrapPredicate::clearFlags( 13324 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13325 13326 auto II = FlagsMap.find(V); 13327 13328 if (II != FlagsMap.end()) 13329 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13330 13331 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13332 } 13333 13334 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13335 const SCEV *Expr = this->getSCEV(V); 13336 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13337 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13338 13339 if (!New) 13340 return nullptr; 13341 13342 for (auto *P : NewPreds) 13343 Preds.add(P); 13344 13345 updateGeneration(); 13346 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13347 return New; 13348 } 13349 13350 PredicatedScalarEvolution::PredicatedScalarEvolution( 13351 const PredicatedScalarEvolution &Init) 13352 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13353 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13354 for (auto I : Init.FlagsMap) 13355 FlagsMap.insert(I); 13356 } 13357 13358 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13359 // For each block. 13360 for (auto *BB : L.getBlocks()) 13361 for (auto &I : *BB) { 13362 if (!SE.isSCEVable(I.getType())) 13363 continue; 13364 13365 auto *Expr = SE.getSCEV(&I); 13366 auto II = RewriteMap.find(Expr); 13367 13368 if (II == RewriteMap.end()) 13369 continue; 13370 13371 // Don't print things that are not interesting. 13372 if (II->second.second == Expr) 13373 continue; 13374 13375 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13376 OS.indent(Depth + 2) << *Expr << "\n"; 13377 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13378 } 13379 } 13380 13381 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13382 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13383 // for URem with constant power-of-2 second operands. 13384 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13385 // 4, A / B becomes X / 8). 13386 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13387 const SCEV *&RHS) { 13388 // Try to match 'zext (trunc A to iB) to iY', which is used 13389 // for URem with constant power-of-2 second operands. Make sure the size of 13390 // the operand A matches the size of the whole expressions. 13391 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13392 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13393 LHS = Trunc->getOperand(); 13394 // Bail out if the type of the LHS is larger than the type of the 13395 // expression for now. 13396 if (getTypeSizeInBits(LHS->getType()) > 13397 getTypeSizeInBits(Expr->getType())) 13398 return false; 13399 if (LHS->getType() != Expr->getType()) 13400 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13401 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13402 << getTypeSizeInBits(Trunc->getType())); 13403 return true; 13404 } 13405 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13406 if (Add == nullptr || Add->getNumOperands() != 2) 13407 return false; 13408 13409 const SCEV *A = Add->getOperand(1); 13410 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13411 13412 if (Mul == nullptr) 13413 return false; 13414 13415 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13416 // (SomeExpr + (-(SomeExpr / B) * B)). 13417 if (Expr == getURemExpr(A, B)) { 13418 LHS = A; 13419 RHS = B; 13420 return true; 13421 } 13422 return false; 13423 }; 13424 13425 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13426 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13427 return MatchURemWithDivisor(Mul->getOperand(1)) || 13428 MatchURemWithDivisor(Mul->getOperand(2)); 13429 13430 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13431 if (Mul->getNumOperands() == 2) 13432 return MatchURemWithDivisor(Mul->getOperand(1)) || 13433 MatchURemWithDivisor(Mul->getOperand(0)) || 13434 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13435 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13436 return false; 13437 } 13438 13439 const SCEV * 13440 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13441 SmallVector<BasicBlock*, 16> ExitingBlocks; 13442 L->getExitingBlocks(ExitingBlocks); 13443 13444 // Form an expression for the maximum exit count possible for this loop. We 13445 // merge the max and exact information to approximate a version of 13446 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13447 SmallVector<const SCEV*, 4> ExitCounts; 13448 for (BasicBlock *ExitingBB : ExitingBlocks) { 13449 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13450 if (isa<SCEVCouldNotCompute>(ExitCount)) 13451 ExitCount = getExitCount(L, ExitingBB, 13452 ScalarEvolution::ConstantMaximum); 13453 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13454 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13455 "We should only have known counts for exiting blocks that " 13456 "dominate latch!"); 13457 ExitCounts.push_back(ExitCount); 13458 } 13459 } 13460 if (ExitCounts.empty()) 13461 return getCouldNotCompute(); 13462 return getUMinFromMismatchedTypes(ExitCounts); 13463 } 13464 13465 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13466 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13467 /// we cannot guarantee that the replacement is loop invariant in the loop of 13468 /// the AddRec. 13469 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13470 ValueToSCEVMapTy ⤅ 13471 13472 public: 13473 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13474 : SCEVRewriteVisitor(SE), Map(M) {} 13475 13476 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13477 13478 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13479 auto I = Map.find(Expr->getValue()); 13480 if (I == Map.end()) 13481 return Expr; 13482 return I->second; 13483 } 13484 }; 13485 13486 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13487 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13488 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13489 // If we have LHS == 0, check if LHS is computing a property of some unknown 13490 // SCEV %v which we can rewrite %v to express explicitly. 13491 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13492 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13493 RHSC->getValue()->isNullValue()) { 13494 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13495 // explicitly express that. 13496 const SCEV *URemLHS = nullptr; 13497 const SCEV *URemRHS = nullptr; 13498 if (matchURem(LHS, URemLHS, URemRHS)) { 13499 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13500 Value *V = LHSUnknown->getValue(); 13501 auto Multiple = 13502 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13503 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13504 RewriteMap[V] = Multiple; 13505 return; 13506 } 13507 } 13508 } 13509 13510 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13511 std::swap(LHS, RHS); 13512 Predicate = CmpInst::getSwappedPredicate(Predicate); 13513 } 13514 13515 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13516 // create this form when combining two checks of the form (X u< C2 + C1) and 13517 // (X >=u C1). 13518 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13519 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13520 if (!AddExpr || AddExpr->getNumOperands() != 2) 13521 return false; 13522 13523 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13524 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13525 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13526 if (!C1 || !C2 || !LHSUnknown) 13527 return false; 13528 13529 auto ExactRegion = 13530 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13531 .sub(C1->getAPInt()); 13532 13533 // Bail out, unless we have a non-wrapping, monotonic range. 13534 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13535 return false; 13536 auto I = RewriteMap.find(LHSUnknown->getValue()); 13537 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13538 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13539 getConstant(ExactRegion.getUnsignedMin()), 13540 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13541 return true; 13542 }; 13543 if (MatchRangeCheckIdiom()) 13544 return; 13545 13546 // For now, limit to conditions that provide information about unknown 13547 // expressions. RHS also cannot contain add recurrences. 13548 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13549 if (!LHSUnknown || containsAddRecurrence(RHS)) 13550 return; 13551 13552 // Check whether LHS has already been rewritten. In that case we want to 13553 // chain further rewrites onto the already rewritten value. 13554 auto I = RewriteMap.find(LHSUnknown->getValue()); 13555 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13556 const SCEV *RewrittenRHS = nullptr; 13557 switch (Predicate) { 13558 case CmpInst::ICMP_ULT: 13559 RewrittenRHS = 13560 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13561 break; 13562 case CmpInst::ICMP_SLT: 13563 RewrittenRHS = 13564 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13565 break; 13566 case CmpInst::ICMP_ULE: 13567 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13568 break; 13569 case CmpInst::ICMP_SLE: 13570 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13571 break; 13572 case CmpInst::ICMP_UGT: 13573 RewrittenRHS = 13574 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13575 break; 13576 case CmpInst::ICMP_SGT: 13577 RewrittenRHS = 13578 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13579 break; 13580 case CmpInst::ICMP_UGE: 13581 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13582 break; 13583 case CmpInst::ICMP_SGE: 13584 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13585 break; 13586 case CmpInst::ICMP_EQ: 13587 if (isa<SCEVConstant>(RHS)) 13588 RewrittenRHS = RHS; 13589 break; 13590 case CmpInst::ICMP_NE: 13591 if (isa<SCEVConstant>(RHS) && 13592 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13593 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13594 break; 13595 default: 13596 break; 13597 } 13598 13599 if (RewrittenRHS) 13600 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13601 }; 13602 // Starting at the loop predecessor, climb up the predecessor chain, as long 13603 // as there are predecessors that can be found that have unique successors 13604 // leading to the original header. 13605 // TODO: share this logic with isLoopEntryGuardedByCond. 13606 ValueToSCEVMapTy RewriteMap; 13607 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13608 L->getLoopPredecessor(), L->getHeader()); 13609 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13610 13611 const BranchInst *LoopEntryPredicate = 13612 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13613 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13614 continue; 13615 13616 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13617 SmallVector<Value *, 8> Worklist; 13618 SmallPtrSet<Value *, 8> Visited; 13619 Worklist.push_back(LoopEntryPredicate->getCondition()); 13620 while (!Worklist.empty()) { 13621 Value *Cond = Worklist.pop_back_val(); 13622 if (!Visited.insert(Cond).second) 13623 continue; 13624 13625 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13626 auto Predicate = 13627 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13628 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13629 getSCEV(Cmp->getOperand(1)), RewriteMap); 13630 continue; 13631 } 13632 13633 Value *L, *R; 13634 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13635 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13636 Worklist.push_back(L); 13637 Worklist.push_back(R); 13638 } 13639 } 13640 } 13641 13642 // Also collect information from assumptions dominating the loop. 13643 for (auto &AssumeVH : AC.assumptions()) { 13644 if (!AssumeVH) 13645 continue; 13646 auto *AssumeI = cast<CallInst>(AssumeVH); 13647 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13648 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13649 continue; 13650 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13651 getSCEV(Cmp->getOperand(1)), RewriteMap); 13652 } 13653 13654 if (RewriteMap.empty()) 13655 return Expr; 13656 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13657 return Rewriter.visit(Expr); 13658 } 13659