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(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 static cl::opt<bool> 224 ClassifyExpressions("scalar-evolution-classify-expressions", 225 cl::Hidden, cl::init(true), 226 cl::desc("When printing analysis, include information on every instruction")); 227 228 static cl::opt<bool> UseExpensiveRangeSharpening( 229 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 230 cl::init(false), 231 cl::desc("Use more powerful methods of sharpening expression ranges. May " 232 "be costly in terms of compile time")); 233 234 //===----------------------------------------------------------------------===// 235 // SCEV class definitions 236 //===----------------------------------------------------------------------===// 237 238 //===----------------------------------------------------------------------===// 239 // Implementation of the SCEV class. 240 // 241 242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 243 LLVM_DUMP_METHOD void SCEV::dump() const { 244 print(dbgs()); 245 dbgs() << '\n'; 246 } 247 #endif 248 249 void SCEV::print(raw_ostream &OS) const { 250 switch (getSCEVType()) { 251 case scConstant: 252 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 253 return; 254 case scPtrToInt: { 255 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 256 const SCEV *Op = PtrToInt->getOperand(); 257 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 258 << *PtrToInt->getType() << ")"; 259 return; 260 } 261 case scTruncate: { 262 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 263 const SCEV *Op = Trunc->getOperand(); 264 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 265 << *Trunc->getType() << ")"; 266 return; 267 } 268 case scZeroExtend: { 269 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 270 const SCEV *Op = ZExt->getOperand(); 271 OS << "(zext " << *Op->getType() << " " << *Op << " to " 272 << *ZExt->getType() << ")"; 273 return; 274 } 275 case scSignExtend: { 276 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 277 const SCEV *Op = SExt->getOperand(); 278 OS << "(sext " << *Op->getType() << " " << *Op << " to " 279 << *SExt->getType() << ")"; 280 return; 281 } 282 case scAddRecExpr: { 283 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 284 OS << "{" << *AR->getOperand(0); 285 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 286 OS << ",+," << *AR->getOperand(i); 287 OS << "}<"; 288 if (AR->hasNoUnsignedWrap()) 289 OS << "nuw><"; 290 if (AR->hasNoSignedWrap()) 291 OS << "nsw><"; 292 if (AR->hasNoSelfWrap() && 293 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 294 OS << "nw><"; 295 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 296 OS << ">"; 297 return; 298 } 299 case scAddExpr: 300 case scMulExpr: 301 case scUMaxExpr: 302 case scSMaxExpr: 303 case scUMinExpr: 304 case scSMinExpr: { 305 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 306 const char *OpStr = nullptr; 307 switch (NAry->getSCEVType()) { 308 case scAddExpr: OpStr = " + "; break; 309 case scMulExpr: OpStr = " * "; break; 310 case scUMaxExpr: OpStr = " umax "; break; 311 case scSMaxExpr: OpStr = " smax "; break; 312 case scUMinExpr: 313 OpStr = " umin "; 314 break; 315 case scSMinExpr: 316 OpStr = " smin "; 317 break; 318 default: 319 llvm_unreachable("There are no other nary expression types."); 320 } 321 OS << "("; 322 ListSeparator LS(OpStr); 323 for (const SCEV *Op : NAry->operands()) 324 OS << LS << *Op; 325 OS << ")"; 326 switch (NAry->getSCEVType()) { 327 case scAddExpr: 328 case scMulExpr: 329 if (NAry->hasNoUnsignedWrap()) 330 OS << "<nuw>"; 331 if (NAry->hasNoSignedWrap()) 332 OS << "<nsw>"; 333 break; 334 default: 335 // Nothing to print for other nary expressions. 336 break; 337 } 338 return; 339 } 340 case scUDivExpr: { 341 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 342 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 343 return; 344 } 345 case scUnknown: { 346 const SCEVUnknown *U = cast<SCEVUnknown>(this); 347 Type *AllocTy; 348 if (U->isSizeOf(AllocTy)) { 349 OS << "sizeof(" << *AllocTy << ")"; 350 return; 351 } 352 if (U->isAlignOf(AllocTy)) { 353 OS << "alignof(" << *AllocTy << ")"; 354 return; 355 } 356 357 Type *CTy; 358 Constant *FieldNo; 359 if (U->isOffsetOf(CTy, FieldNo)) { 360 OS << "offsetof(" << *CTy << ", "; 361 FieldNo->printAsOperand(OS, false); 362 OS << ")"; 363 return; 364 } 365 366 // Otherwise just print it normally. 367 U->getValue()->printAsOperand(OS, false); 368 return; 369 } 370 case scCouldNotCompute: 371 OS << "***COULDNOTCOMPUTE***"; 372 return; 373 } 374 llvm_unreachable("Unknown SCEV kind!"); 375 } 376 377 Type *SCEV::getType() const { 378 switch (getSCEVType()) { 379 case scConstant: 380 return cast<SCEVConstant>(this)->getType(); 381 case scPtrToInt: 382 case scTruncate: 383 case scZeroExtend: 384 case scSignExtend: 385 return cast<SCEVCastExpr>(this)->getType(); 386 case scAddRecExpr: 387 return cast<SCEVAddRecExpr>(this)->getType(); 388 case scMulExpr: 389 return cast<SCEVMulExpr>(this)->getType(); 390 case scUMaxExpr: 391 case scSMaxExpr: 392 case scUMinExpr: 393 case scSMinExpr: 394 return cast<SCEVMinMaxExpr>(this)->getType(); 395 case scAddExpr: 396 return cast<SCEVAddExpr>(this)->getType(); 397 case scUDivExpr: 398 return cast<SCEVUDivExpr>(this)->getType(); 399 case scUnknown: 400 return cast<SCEVUnknown>(this)->getType(); 401 case scCouldNotCompute: 402 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 403 } 404 llvm_unreachable("Unknown SCEV kind!"); 405 } 406 407 bool SCEV::isZero() const { 408 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 409 return SC->getValue()->isZero(); 410 return false; 411 } 412 413 bool SCEV::isOne() const { 414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 415 return SC->getValue()->isOne(); 416 return false; 417 } 418 419 bool SCEV::isAllOnesValue() const { 420 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 421 return SC->getValue()->isMinusOne(); 422 return false; 423 } 424 425 bool SCEV::isNonConstantNegative() const { 426 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 427 if (!Mul) return false; 428 429 // If there is a constant factor, it will be first. 430 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 431 if (!SC) return false; 432 433 // Return true if the value is negative, this matches things like (-42 * V). 434 return SC->getAPInt().isNegative(); 435 } 436 437 SCEVCouldNotCompute::SCEVCouldNotCompute() : 438 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 439 440 bool SCEVCouldNotCompute::classof(const SCEV *S) { 441 return S->getSCEVType() == scCouldNotCompute; 442 } 443 444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 445 FoldingSetNodeID ID; 446 ID.AddInteger(scConstant); 447 ID.AddPointer(V); 448 void *IP = nullptr; 449 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 450 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 451 UniqueSCEVs.InsertNode(S, IP); 452 return S; 453 } 454 455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 456 return getConstant(ConstantInt::get(getContext(), Val)); 457 } 458 459 const SCEV * 460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 461 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 462 return getConstant(ConstantInt::get(ITy, V, isSigned)); 463 } 464 465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 466 const SCEV *op, Type *ty) 467 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 468 Operands[0] = op; 469 } 470 471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 472 Type *ITy) 473 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 474 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 475 "Must be a non-bit-width-changing pointer-to-integer cast!"); 476 } 477 478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 479 SCEVTypes SCEVTy, const SCEV *op, 480 Type *ty) 481 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 482 483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 484 Type *ty) 485 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 486 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 487 "Cannot truncate non-integer value!"); 488 } 489 490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 491 const SCEV *op, Type *ty) 492 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 493 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 494 "Cannot zero extend non-integer value!"); 495 } 496 497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 498 const SCEV *op, Type *ty) 499 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 500 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 501 "Cannot sign extend non-integer value!"); 502 } 503 504 void SCEVUnknown::deleted() { 505 // Clear this SCEVUnknown from various maps. 506 SE->forgetMemoizedResults(this); 507 508 // Remove this SCEVUnknown from the uniquing map. 509 SE->UniqueSCEVs.RemoveNode(this); 510 511 // Release the value. 512 setValPtr(nullptr); 513 } 514 515 void SCEVUnknown::allUsesReplacedWith(Value *New) { 516 // Remove this SCEVUnknown from the uniquing map. 517 SE->UniqueSCEVs.RemoveNode(this); 518 519 // Update this SCEVUnknown to point to the new value. This is needed 520 // because there may still be outstanding SCEVs which still point to 521 // this SCEVUnknown. 522 setValPtr(New); 523 } 524 525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 526 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 527 if (VCE->getOpcode() == Instruction::PtrToInt) 528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 529 if (CE->getOpcode() == Instruction::GetElementPtr && 530 CE->getOperand(0)->isNullValue() && 531 CE->getNumOperands() == 2) 532 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 533 if (CI->isOne()) { 534 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 535 return true; 536 } 537 538 return false; 539 } 540 541 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 542 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 543 if (VCE->getOpcode() == Instruction::PtrToInt) 544 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 545 if (CE->getOpcode() == Instruction::GetElementPtr && 546 CE->getOperand(0)->isNullValue()) { 547 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 548 if (StructType *STy = dyn_cast<StructType>(Ty)) 549 if (!STy->isPacked() && 550 CE->getNumOperands() == 3 && 551 CE->getOperand(1)->isNullValue()) { 552 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 553 if (CI->isOne() && 554 STy->getNumElements() == 2 && 555 STy->getElementType(0)->isIntegerTy(1)) { 556 AllocTy = STy->getElementType(1); 557 return true; 558 } 559 } 560 } 561 562 return false; 563 } 564 565 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 566 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 567 if (VCE->getOpcode() == Instruction::PtrToInt) 568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 569 if (CE->getOpcode() == Instruction::GetElementPtr && 570 CE->getNumOperands() == 3 && 571 CE->getOperand(0)->isNullValue() && 572 CE->getOperand(1)->isNullValue()) { 573 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 574 // Ignore vector types here so that ScalarEvolutionExpander doesn't 575 // emit getelementptrs that index into vectors. 576 if (Ty->isStructTy() || Ty->isArrayTy()) { 577 CTy = Ty; 578 FieldNo = CE->getOperand(2); 579 return true; 580 } 581 } 582 583 return false; 584 } 585 586 //===----------------------------------------------------------------------===// 587 // SCEV Utilities 588 //===----------------------------------------------------------------------===// 589 590 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 591 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 592 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 593 /// have been previously deemed to be "equally complex" by this routine. It is 594 /// intended to avoid exponential time complexity in cases like: 595 /// 596 /// %a = f(%x, %y) 597 /// %b = f(%a, %a) 598 /// %c = f(%b, %b) 599 /// 600 /// %d = f(%x, %y) 601 /// %e = f(%d, %d) 602 /// %f = f(%e, %e) 603 /// 604 /// CompareValueComplexity(%f, %c) 605 /// 606 /// Since we do not continue running this routine on expression trees once we 607 /// have seen unequal values, there is no need to track them in the cache. 608 static int 609 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 610 const LoopInfo *const LI, Value *LV, Value *RV, 611 unsigned Depth) { 612 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 613 return 0; 614 615 // Order pointer values after integer values. This helps SCEVExpander form 616 // GEPs. 617 bool LIsPointer = LV->getType()->isPointerTy(), 618 RIsPointer = RV->getType()->isPointerTy(); 619 if (LIsPointer != RIsPointer) 620 return (int)LIsPointer - (int)RIsPointer; 621 622 // Compare getValueID values. 623 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 624 if (LID != RID) 625 return (int)LID - (int)RID; 626 627 // Sort arguments by their position. 628 if (const auto *LA = dyn_cast<Argument>(LV)) { 629 const auto *RA = cast<Argument>(RV); 630 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 631 return (int)LArgNo - (int)RArgNo; 632 } 633 634 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 635 const auto *RGV = cast<GlobalValue>(RV); 636 637 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 638 auto LT = GV->getLinkage(); 639 return !(GlobalValue::isPrivateLinkage(LT) || 640 GlobalValue::isInternalLinkage(LT)); 641 }; 642 643 // Use the names to distinguish the two values, but only if the 644 // names are semantically important. 645 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 646 return LGV->getName().compare(RGV->getName()); 647 } 648 649 // For instructions, compare their loop depth, and their operand count. This 650 // is pretty loose. 651 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 652 const auto *RInst = cast<Instruction>(RV); 653 654 // Compare loop depths. 655 const BasicBlock *LParent = LInst->getParent(), 656 *RParent = RInst->getParent(); 657 if (LParent != RParent) { 658 unsigned LDepth = LI->getLoopDepth(LParent), 659 RDepth = LI->getLoopDepth(RParent); 660 if (LDepth != RDepth) 661 return (int)LDepth - (int)RDepth; 662 } 663 664 // Compare the number of operands. 665 unsigned LNumOps = LInst->getNumOperands(), 666 RNumOps = RInst->getNumOperands(); 667 if (LNumOps != RNumOps) 668 return (int)LNumOps - (int)RNumOps; 669 670 for (unsigned Idx : seq(0u, LNumOps)) { 671 int Result = 672 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 673 RInst->getOperand(Idx), Depth + 1); 674 if (Result != 0) 675 return Result; 676 } 677 } 678 679 EqCacheValue.unionSets(LV, RV); 680 return 0; 681 } 682 683 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 684 // than RHS, respectively. A three-way result allows recursive comparisons to be 685 // more efficient. 686 // If the max analysis depth was reached, return None, assuming we do not know 687 // if they are equivalent for sure. 688 static Optional<int> 689 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 690 EquivalenceClasses<const Value *> &EqCacheValue, 691 const LoopInfo *const LI, const SCEV *LHS, 692 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 693 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 694 if (LHS == RHS) 695 return 0; 696 697 // Primarily, sort the SCEVs by their getSCEVType(). 698 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 699 if (LType != RType) 700 return (int)LType - (int)RType; 701 702 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 703 return 0; 704 705 if (Depth > MaxSCEVCompareDepth) 706 return None; 707 708 // Aside from the getSCEVType() ordering, the particular ordering 709 // isn't very important except that it's beneficial to be consistent, 710 // so that (a + b) and (b + a) don't end up as different expressions. 711 switch (LType) { 712 case scUnknown: { 713 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 714 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 715 716 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 717 RU->getValue(), Depth + 1); 718 if (X == 0) 719 EqCacheSCEV.unionSets(LHS, RHS); 720 return X; 721 } 722 723 case scConstant: { 724 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 725 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 726 727 // Compare constant values. 728 const APInt &LA = LC->getAPInt(); 729 const APInt &RA = RC->getAPInt(); 730 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 731 if (LBitWidth != RBitWidth) 732 return (int)LBitWidth - (int)RBitWidth; 733 return LA.ult(RA) ? -1 : 1; 734 } 735 736 case scAddRecExpr: { 737 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 738 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 739 740 // There is always a dominance between two recs that are used by one SCEV, 741 // so we can safely sort recs by loop header dominance. We require such 742 // order in getAddExpr. 743 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 744 if (LLoop != RLoop) { 745 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 746 assert(LHead != RHead && "Two loops share the same header?"); 747 if (DT.dominates(LHead, RHead)) 748 return 1; 749 else 750 assert(DT.dominates(RHead, LHead) && 751 "No dominance between recurrences used by one SCEV?"); 752 return -1; 753 } 754 755 // Addrec complexity grows with operand count. 756 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 757 if (LNumOps != RNumOps) 758 return (int)LNumOps - (int)RNumOps; 759 760 // Lexicographically compare. 761 for (unsigned i = 0; i != LNumOps; ++i) { 762 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 763 LA->getOperand(i), RA->getOperand(i), DT, 764 Depth + 1); 765 if (X != 0) 766 return X; 767 } 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return 0; 770 } 771 772 case scAddExpr: 773 case scMulExpr: 774 case scSMaxExpr: 775 case scUMaxExpr: 776 case scSMinExpr: 777 case scUMinExpr: { 778 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 779 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 780 781 // Lexicographically compare n-ary expressions. 782 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 783 if (LNumOps != RNumOps) 784 return (int)LNumOps - (int)RNumOps; 785 786 for (unsigned i = 0; i != LNumOps; ++i) { 787 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 788 LC->getOperand(i), RC->getOperand(i), DT, 789 Depth + 1); 790 if (X != 0) 791 return X; 792 } 793 EqCacheSCEV.unionSets(LHS, RHS); 794 return 0; 795 } 796 797 case scUDivExpr: { 798 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 799 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 800 801 // Lexicographically compare udiv expressions. 802 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 803 RC->getLHS(), DT, Depth + 1); 804 if (X != 0) 805 return X; 806 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 807 RC->getRHS(), DT, Depth + 1); 808 if (X == 0) 809 EqCacheSCEV.unionSets(LHS, RHS); 810 return X; 811 } 812 813 case scPtrToInt: 814 case scTruncate: 815 case scZeroExtend: 816 case scSignExtend: { 817 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 818 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 819 820 // Compare cast expressions by operand. 821 auto X = 822 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 823 RC->getOperand(), DT, Depth + 1); 824 if (X == 0) 825 EqCacheSCEV.unionSets(LHS, RHS); 826 return X; 827 } 828 829 case scCouldNotCompute: 830 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 831 } 832 llvm_unreachable("Unknown SCEV kind!"); 833 } 834 835 /// Given a list of SCEV objects, order them by their complexity, and group 836 /// objects of the same complexity together by value. When this routine is 837 /// finished, we know that any duplicates in the vector are consecutive and that 838 /// complexity is monotonically increasing. 839 /// 840 /// Note that we go take special precautions to ensure that we get deterministic 841 /// results from this routine. In other words, we don't want the results of 842 /// this to depend on where the addresses of various SCEV objects happened to 843 /// land in memory. 844 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 845 LoopInfo *LI, DominatorTree &DT) { 846 if (Ops.size() < 2) return; // Noop 847 848 EquivalenceClasses<const SCEV *> EqCacheSCEV; 849 EquivalenceClasses<const Value *> EqCacheValue; 850 851 // Whether LHS has provably less complexity than RHS. 852 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 853 auto Complexity = 854 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 855 return Complexity && *Complexity < 0; 856 }; 857 if (Ops.size() == 2) { 858 // This is the common case, which also happens to be trivially simple. 859 // Special case it. 860 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 861 if (IsLessComplex(RHS, LHS)) 862 std::swap(LHS, RHS); 863 return; 864 } 865 866 // Do the rough sort by complexity. 867 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 868 return IsLessComplex(LHS, RHS); 869 }); 870 871 // Now that we are sorted by complexity, group elements of the same 872 // complexity. Note that this is, at worst, N^2, but the vector is likely to 873 // be extremely short in practice. Note that we take this approach because we 874 // do not want to depend on the addresses of the objects we are grouping. 875 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 876 const SCEV *S = Ops[i]; 877 unsigned Complexity = S->getSCEVType(); 878 879 // If there are any objects of the same complexity and same value as this 880 // one, group them. 881 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 882 if (Ops[j] == S) { // Found a duplicate. 883 // Move it to immediately after i'th element. 884 std::swap(Ops[i+1], Ops[j]); 885 ++i; // no need to rescan it. 886 if (i == e-2) return; // Done! 887 } 888 } 889 } 890 } 891 892 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 893 /// least HugeExprThreshold nodes). 894 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 895 return any_of(Ops, [](const SCEV *S) { 896 return S->getExpressionSize() >= HugeExprThreshold; 897 }); 898 } 899 900 //===----------------------------------------------------------------------===// 901 // Simple SCEV method implementations 902 //===----------------------------------------------------------------------===// 903 904 /// Compute BC(It, K). The result has width W. Assume, K > 0. 905 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 906 ScalarEvolution &SE, 907 Type *ResultTy) { 908 // Handle the simplest case efficiently. 909 if (K == 1) 910 return SE.getTruncateOrZeroExtend(It, ResultTy); 911 912 // We are using the following formula for BC(It, K): 913 // 914 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 915 // 916 // Suppose, W is the bitwidth of the return value. We must be prepared for 917 // overflow. Hence, we must assure that the result of our computation is 918 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 919 // safe in modular arithmetic. 920 // 921 // However, this code doesn't use exactly that formula; the formula it uses 922 // is something like the following, where T is the number of factors of 2 in 923 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 924 // exponentiation: 925 // 926 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 927 // 928 // This formula is trivially equivalent to the previous formula. However, 929 // this formula can be implemented much more efficiently. The trick is that 930 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 931 // arithmetic. To do exact division in modular arithmetic, all we have 932 // to do is multiply by the inverse. Therefore, this step can be done at 933 // width W. 934 // 935 // The next issue is how to safely do the division by 2^T. The way this 936 // is done is by doing the multiplication step at a width of at least W + T 937 // bits. This way, the bottom W+T bits of the product are accurate. Then, 938 // when we perform the division by 2^T (which is equivalent to a right shift 939 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 940 // truncated out after the division by 2^T. 941 // 942 // In comparison to just directly using the first formula, this technique 943 // is much more efficient; using the first formula requires W * K bits, 944 // but this formula less than W + K bits. Also, the first formula requires 945 // a division step, whereas this formula only requires multiplies and shifts. 946 // 947 // It doesn't matter whether the subtraction step is done in the calculation 948 // width or the input iteration count's width; if the subtraction overflows, 949 // the result must be zero anyway. We prefer here to do it in the width of 950 // the induction variable because it helps a lot for certain cases; CodeGen 951 // isn't smart enough to ignore the overflow, which leads to much less 952 // efficient code if the width of the subtraction is wider than the native 953 // register width. 954 // 955 // (It's possible to not widen at all by pulling out factors of 2 before 956 // the multiplication; for example, K=2 can be calculated as 957 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 958 // extra arithmetic, so it's not an obvious win, and it gets 959 // much more complicated for K > 3.) 960 961 // Protection from insane SCEVs; this bound is conservative, 962 // but it probably doesn't matter. 963 if (K > 1000) 964 return SE.getCouldNotCompute(); 965 966 unsigned W = SE.getTypeSizeInBits(ResultTy); 967 968 // Calculate K! / 2^T and T; we divide out the factors of two before 969 // multiplying for calculating K! / 2^T to avoid overflow. 970 // Other overflow doesn't matter because we only care about the bottom 971 // W bits of the result. 972 APInt OddFactorial(W, 1); 973 unsigned T = 1; 974 for (unsigned i = 3; i <= K; ++i) { 975 APInt Mult(W, i); 976 unsigned TwoFactors = Mult.countTrailingZeros(); 977 T += TwoFactors; 978 Mult.lshrInPlace(TwoFactors); 979 OddFactorial *= Mult; 980 } 981 982 // We need at least W + T bits for the multiplication step 983 unsigned CalculationBits = W + T; 984 985 // Calculate 2^T, at width T+W. 986 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 987 988 // Calculate the multiplicative inverse of K! / 2^T; 989 // this multiplication factor will perform the exact division by 990 // K! / 2^T. 991 APInt Mod = APInt::getSignedMinValue(W+1); 992 APInt MultiplyFactor = OddFactorial.zext(W+1); 993 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 994 MultiplyFactor = MultiplyFactor.trunc(W); 995 996 // Calculate the product, at width T+W 997 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 998 CalculationBits); 999 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1000 for (unsigned i = 1; i != K; ++i) { 1001 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1002 Dividend = SE.getMulExpr(Dividend, 1003 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1004 } 1005 1006 // Divide by 2^T 1007 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1008 1009 // Truncate the result, and divide by K! / 2^T. 1010 1011 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1012 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1013 } 1014 1015 /// Return the value of this chain of recurrences at the specified iteration 1016 /// number. We can evaluate this recurrence by multiplying each element in the 1017 /// chain by the binomial coefficient corresponding to it. In other words, we 1018 /// can evaluate {A,+,B,+,C,+,D} as: 1019 /// 1020 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1021 /// 1022 /// where BC(It, k) stands for binomial coefficient. 1023 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1024 ScalarEvolution &SE) const { 1025 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1026 } 1027 1028 const SCEV * 1029 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1030 const SCEV *It, ScalarEvolution &SE) { 1031 assert(Operands.size() > 0); 1032 const SCEV *Result = Operands[0]; 1033 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1034 // The computation is correct in the face of overflow provided that the 1035 // multiplication is performed _after_ the evaluation of the binomial 1036 // coefficient. 1037 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1038 if (isa<SCEVCouldNotCompute>(Coeff)) 1039 return Coeff; 1040 1041 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1042 } 1043 return Result; 1044 } 1045 1046 //===----------------------------------------------------------------------===// 1047 // SCEV Expression folder implementations 1048 //===----------------------------------------------------------------------===// 1049 1050 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1051 unsigned Depth) { 1052 assert(Depth <= 1 && 1053 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1054 1055 // We could be called with an integer-typed operands during SCEV rewrites. 1056 // Since the operand is an integer already, just perform zext/trunc/self cast. 1057 if (!Op->getType()->isPointerTy()) 1058 return Op; 1059 1060 // What would be an ID for such a SCEV cast expression? 1061 FoldingSetNodeID ID; 1062 ID.AddInteger(scPtrToInt); 1063 ID.AddPointer(Op); 1064 1065 void *IP = nullptr; 1066 1067 // Is there already an expression for such a cast? 1068 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1069 return S; 1070 1071 // It isn't legal for optimizations to construct new ptrtoint expressions 1072 // for non-integral pointers. 1073 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1074 return getCouldNotCompute(); 1075 1076 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1077 1078 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1079 // is sufficiently wide to represent all possible pointer values. 1080 // We could theoretically teach SCEV to truncate wider pointers, but 1081 // that isn't implemented for now. 1082 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1083 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1084 return getCouldNotCompute(); 1085 1086 // If not, is this expression something we can't reduce any further? 1087 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1088 // Perform some basic constant folding. If the operand of the ptr2int cast 1089 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1090 // left as-is), but produce a zero constant. 1091 // NOTE: We could handle a more general case, but lack motivational cases. 1092 if (isa<ConstantPointerNull>(U->getValue())) 1093 return getZero(IntPtrTy); 1094 1095 // Create an explicit cast node. 1096 // We can reuse the existing insert position since if we get here, 1097 // we won't have made any changes which would invalidate it. 1098 SCEV *S = new (SCEVAllocator) 1099 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1100 UniqueSCEVs.InsertNode(S, IP); 1101 addToLoopUseLists(S); 1102 registerUser(S, Op); 1103 return S; 1104 } 1105 1106 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1107 "non-SCEVUnknown's."); 1108 1109 // Otherwise, we've got some expression that is more complex than just a 1110 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1111 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1112 // only, and the expressions must otherwise be integer-typed. 1113 // So sink the cast down to the SCEVUnknown's. 1114 1115 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1116 /// which computes a pointer-typed value, and rewrites the whole expression 1117 /// tree so that *all* the computations are done on integers, and the only 1118 /// pointer-typed operands in the expression are SCEVUnknown. 1119 class SCEVPtrToIntSinkingRewriter 1120 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1121 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1122 1123 public: 1124 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1125 1126 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1127 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1128 return Rewriter.visit(Scev); 1129 } 1130 1131 const SCEV *visit(const SCEV *S) { 1132 Type *STy = S->getType(); 1133 // If the expression is not pointer-typed, just keep it as-is. 1134 if (!STy->isPointerTy()) 1135 return S; 1136 // Else, recursively sink the cast down into it. 1137 return Base::visit(S); 1138 } 1139 1140 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1141 SmallVector<const SCEV *, 2> Operands; 1142 bool Changed = false; 1143 for (auto *Op : Expr->operands()) { 1144 Operands.push_back(visit(Op)); 1145 Changed |= Op != Operands.back(); 1146 } 1147 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1148 } 1149 1150 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1151 SmallVector<const SCEV *, 2> Operands; 1152 bool Changed = false; 1153 for (auto *Op : Expr->operands()) { 1154 Operands.push_back(visit(Op)); 1155 Changed |= Op != Operands.back(); 1156 } 1157 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1158 } 1159 1160 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1161 assert(Expr->getType()->isPointerTy() && 1162 "Should only reach pointer-typed SCEVUnknown's."); 1163 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1164 } 1165 }; 1166 1167 // And actually perform the cast sinking. 1168 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1169 assert(IntOp->getType()->isIntegerTy() && 1170 "We must have succeeded in sinking the cast, " 1171 "and ending up with an integer-typed expression!"); 1172 return IntOp; 1173 } 1174 1175 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1176 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1177 1178 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1179 if (isa<SCEVCouldNotCompute>(IntOp)) 1180 return IntOp; 1181 1182 return getTruncateOrZeroExtend(IntOp, Ty); 1183 } 1184 1185 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1186 unsigned Depth) { 1187 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1188 "This is not a truncating conversion!"); 1189 assert(isSCEVable(Ty) && 1190 "This is not a conversion to a SCEVable type!"); 1191 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1192 Ty = getEffectiveSCEVType(Ty); 1193 1194 FoldingSetNodeID ID; 1195 ID.AddInteger(scTruncate); 1196 ID.AddPointer(Op); 1197 ID.AddPointer(Ty); 1198 void *IP = nullptr; 1199 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1200 1201 // Fold if the operand is constant. 1202 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1203 return getConstant( 1204 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1205 1206 // trunc(trunc(x)) --> trunc(x) 1207 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1208 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1209 1210 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1211 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1212 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1213 1214 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1215 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1216 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1217 1218 if (Depth > MaxCastDepth) { 1219 SCEV *S = 1220 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1221 UniqueSCEVs.InsertNode(S, IP); 1222 addToLoopUseLists(S); 1223 registerUser(S, Op); 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 registerUser(S, Op); 1279 return S; 1280 } 1281 1282 // Get the limit of a recurrence such that incrementing by Step cannot cause 1283 // signed overflow as long as the value of the recurrence within the 1284 // loop does not exceed this limit before incrementing. 1285 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1286 ICmpInst::Predicate *Pred, 1287 ScalarEvolution *SE) { 1288 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1289 if (SE->isKnownPositive(Step)) { 1290 *Pred = ICmpInst::ICMP_SLT; 1291 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1292 SE->getSignedRangeMax(Step)); 1293 } 1294 if (SE->isKnownNegative(Step)) { 1295 *Pred = ICmpInst::ICMP_SGT; 1296 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1297 SE->getSignedRangeMin(Step)); 1298 } 1299 return nullptr; 1300 } 1301 1302 // Get the limit of a recurrence such that incrementing by Step cannot cause 1303 // unsigned overflow as long as the value of the recurrence within the loop does 1304 // not exceed this limit before incrementing. 1305 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1306 ICmpInst::Predicate *Pred, 1307 ScalarEvolution *SE) { 1308 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1309 *Pred = ICmpInst::ICMP_ULT; 1310 1311 return SE->getConstant(APInt::getMinValue(BitWidth) - 1312 SE->getUnsignedRangeMax(Step)); 1313 } 1314 1315 namespace { 1316 1317 struct ExtendOpTraitsBase { 1318 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1319 unsigned); 1320 }; 1321 1322 // Used to make code generic over signed and unsigned overflow. 1323 template <typename ExtendOp> struct ExtendOpTraits { 1324 // Members present: 1325 // 1326 // static const SCEV::NoWrapFlags WrapType; 1327 // 1328 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1329 // 1330 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1331 // ICmpInst::Predicate *Pred, 1332 // ScalarEvolution *SE); 1333 }; 1334 1335 template <> 1336 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1337 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1338 1339 static const GetExtendExprTy GetExtendExpr; 1340 1341 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1342 ICmpInst::Predicate *Pred, 1343 ScalarEvolution *SE) { 1344 return getSignedOverflowLimitForStep(Step, Pred, SE); 1345 } 1346 }; 1347 1348 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1349 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1350 1351 template <> 1352 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1353 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1354 1355 static const GetExtendExprTy GetExtendExpr; 1356 1357 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1358 ICmpInst::Predicate *Pred, 1359 ScalarEvolution *SE) { 1360 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1361 } 1362 }; 1363 1364 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1365 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1366 1367 } // end anonymous namespace 1368 1369 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1370 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1371 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1372 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1373 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1374 // expression "Step + sext/zext(PreIncAR)" is congruent with 1375 // "sext/zext(PostIncAR)" 1376 template <typename ExtendOpTy> 1377 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1378 ScalarEvolution *SE, unsigned Depth) { 1379 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1380 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1381 1382 const Loop *L = AR->getLoop(); 1383 const SCEV *Start = AR->getStart(); 1384 const SCEV *Step = AR->getStepRecurrence(*SE); 1385 1386 // Check for a simple looking step prior to loop entry. 1387 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1388 if (!SA) 1389 return nullptr; 1390 1391 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1392 // subtraction is expensive. For this purpose, perform a quick and dirty 1393 // difference, by checking for Step in the operand list. 1394 SmallVector<const SCEV *, 4> DiffOps; 1395 for (const SCEV *Op : SA->operands()) 1396 if (Op != Step) 1397 DiffOps.push_back(Op); 1398 1399 if (DiffOps.size() == SA->getNumOperands()) 1400 return nullptr; 1401 1402 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1403 // `Step`: 1404 1405 // 1. NSW/NUW flags on the step increment. 1406 auto PreStartFlags = 1407 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1408 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1409 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1410 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1411 1412 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1413 // "S+X does not sign/unsign-overflow". 1414 // 1415 1416 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1417 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1418 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1419 return PreStart; 1420 1421 // 2. Direct overflow check on the step operation's expression. 1422 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1423 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1424 const SCEV *OperandExtendedStart = 1425 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1426 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1427 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1428 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1429 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1430 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1431 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1432 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1433 } 1434 return PreStart; 1435 } 1436 1437 // 3. Loop precondition. 1438 ICmpInst::Predicate Pred; 1439 const SCEV *OverflowLimit = 1440 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1441 1442 if (OverflowLimit && 1443 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1444 return PreStart; 1445 1446 return nullptr; 1447 } 1448 1449 // Get the normalized zero or sign extended expression for this AddRec's Start. 1450 template <typename ExtendOpTy> 1451 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1452 ScalarEvolution *SE, 1453 unsigned Depth) { 1454 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1455 1456 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1457 if (!PreStart) 1458 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1459 1460 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1461 Depth), 1462 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1463 } 1464 1465 // Try to prove away overflow by looking at "nearby" add recurrences. A 1466 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1467 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1468 // 1469 // Formally: 1470 // 1471 // {S,+,X} == {S-T,+,X} + T 1472 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1473 // 1474 // If ({S-T,+,X} + T) does not overflow ... (1) 1475 // 1476 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1477 // 1478 // If {S-T,+,X} does not overflow ... (2) 1479 // 1480 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1481 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1482 // 1483 // If (S-T)+T does not overflow ... (3) 1484 // 1485 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1486 // == {Ext(S),+,Ext(X)} == LHS 1487 // 1488 // Thus, if (1), (2) and (3) are true for some T, then 1489 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1490 // 1491 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1492 // does not overflow" restricted to the 0th iteration. Therefore we only need 1493 // to check for (1) and (2). 1494 // 1495 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1496 // is `Delta` (defined below). 1497 template <typename ExtendOpTy> 1498 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1499 const SCEV *Step, 1500 const Loop *L) { 1501 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1502 1503 // We restrict `Start` to a constant to prevent SCEV from spending too much 1504 // time here. It is correct (but more expensive) to continue with a 1505 // non-constant `Start` and do a general SCEV subtraction to compute 1506 // `PreStart` below. 1507 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1508 if (!StartC) 1509 return false; 1510 1511 APInt StartAI = StartC->getAPInt(); 1512 1513 for (unsigned Delta : {-2, -1, 1, 2}) { 1514 const SCEV *PreStart = getConstant(StartAI - Delta); 1515 1516 FoldingSetNodeID ID; 1517 ID.AddInteger(scAddRecExpr); 1518 ID.AddPointer(PreStart); 1519 ID.AddPointer(Step); 1520 ID.AddPointer(L); 1521 void *IP = nullptr; 1522 const auto *PreAR = 1523 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1524 1525 // Give up if we don't already have the add recurrence we need because 1526 // actually constructing an add recurrence is relatively expensive. 1527 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1528 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1529 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1530 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1531 DeltaS, &Pred, this); 1532 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1533 return true; 1534 } 1535 } 1536 1537 return false; 1538 } 1539 1540 // Finds an integer D for an expression (C + x + y + ...) such that the top 1541 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1542 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1543 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1544 // the (C + x + y + ...) expression is \p WholeAddExpr. 1545 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1546 const SCEVConstant *ConstantTerm, 1547 const SCEVAddExpr *WholeAddExpr) { 1548 const APInt &C = ConstantTerm->getAPInt(); 1549 const unsigned BitWidth = C.getBitWidth(); 1550 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1551 uint32_t TZ = BitWidth; 1552 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1553 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1554 if (TZ) { 1555 // Set D to be as many least significant bits of C as possible while still 1556 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1557 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1558 } 1559 return APInt(BitWidth, 0); 1560 } 1561 1562 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1563 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1564 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1565 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1566 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1567 const APInt &ConstantStart, 1568 const SCEV *Step) { 1569 const unsigned BitWidth = ConstantStart.getBitWidth(); 1570 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1571 if (TZ) 1572 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1573 : ConstantStart; 1574 return APInt(BitWidth, 0); 1575 } 1576 1577 const SCEV * 1578 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1579 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1580 "This is not an extending conversion!"); 1581 assert(isSCEVable(Ty) && 1582 "This is not a conversion to a SCEVable type!"); 1583 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1584 Ty = getEffectiveSCEVType(Ty); 1585 1586 // Fold if the operand is constant. 1587 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1588 return getConstant( 1589 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1590 1591 // zext(zext(x)) --> zext(x) 1592 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1593 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1594 1595 // Before doing any expensive analysis, check to see if we've already 1596 // computed a SCEV for this Op and Ty. 1597 FoldingSetNodeID ID; 1598 ID.AddInteger(scZeroExtend); 1599 ID.AddPointer(Op); 1600 ID.AddPointer(Ty); 1601 void *IP = nullptr; 1602 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1603 if (Depth > MaxCastDepth) { 1604 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1605 Op, Ty); 1606 UniqueSCEVs.InsertNode(S, IP); 1607 addToLoopUseLists(S); 1608 registerUser(S, Op); 1609 return S; 1610 } 1611 1612 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1613 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1614 // It's possible the bits taken off by the truncate were all zero bits. If 1615 // so, we should be able to simplify this further. 1616 const SCEV *X = ST->getOperand(); 1617 ConstantRange CR = getUnsignedRange(X); 1618 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1619 unsigned NewBits = getTypeSizeInBits(Ty); 1620 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1621 CR.zextOrTrunc(NewBits))) 1622 return getTruncateOrZeroExtend(X, Ty, Depth); 1623 } 1624 1625 // If the input value is a chrec scev, and we can prove that the value 1626 // did not overflow the old, smaller, value, we can zero extend all of the 1627 // operands (often constants). This allows analysis of something like 1628 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1629 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1630 if (AR->isAffine()) { 1631 const SCEV *Start = AR->getStart(); 1632 const SCEV *Step = AR->getStepRecurrence(*this); 1633 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1634 const Loop *L = AR->getLoop(); 1635 1636 if (!AR->hasNoUnsignedWrap()) { 1637 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1638 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1639 } 1640 1641 // If we have special knowledge that this addrec won't overflow, 1642 // we don't need to do any further analysis. 1643 if (AR->hasNoUnsignedWrap()) 1644 return getAddRecExpr( 1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1646 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1647 1648 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1649 // Note that this serves two purposes: It filters out loops that are 1650 // simply not analyzable, and it covers the case where this code is 1651 // being called from within backedge-taken count analysis, such that 1652 // attempting to ask for the backedge-taken count would likely result 1653 // in infinite recursion. In the later case, the analysis code will 1654 // cope with a conservative value, and it will take care to purge 1655 // that value once it has finished. 1656 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1657 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1658 // Manually compute the final value for AR, checking for overflow. 1659 1660 // Check whether the backedge-taken count can be losslessly casted to 1661 // the addrec's type. The count is always unsigned. 1662 const SCEV *CastedMaxBECount = 1663 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1664 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1665 CastedMaxBECount, MaxBECount->getType(), Depth); 1666 if (MaxBECount == RecastedMaxBECount) { 1667 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1668 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1669 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1670 SCEV::FlagAnyWrap, Depth + 1); 1671 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1672 SCEV::FlagAnyWrap, 1673 Depth + 1), 1674 WideTy, Depth + 1); 1675 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1676 const SCEV *WideMaxBECount = 1677 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1678 const SCEV *OperandExtendedAdd = 1679 getAddExpr(WideStart, 1680 getMulExpr(WideMaxBECount, 1681 getZeroExtendExpr(Step, WideTy, Depth + 1), 1682 SCEV::FlagAnyWrap, Depth + 1), 1683 SCEV::FlagAnyWrap, Depth + 1); 1684 if (ZAdd == OperandExtendedAdd) { 1685 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1686 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1687 // Return the expression with the addrec on the outside. 1688 return getAddRecExpr( 1689 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1690 Depth + 1), 1691 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1692 AR->getNoWrapFlags()); 1693 } 1694 // Similar to above, only this time treat the step value as signed. 1695 // This covers loops that count down. 1696 OperandExtendedAdd = 1697 getAddExpr(WideStart, 1698 getMulExpr(WideMaxBECount, 1699 getSignExtendExpr(Step, WideTy, Depth + 1), 1700 SCEV::FlagAnyWrap, Depth + 1), 1701 SCEV::FlagAnyWrap, Depth + 1); 1702 if (ZAdd == OperandExtendedAdd) { 1703 // Cache knowledge of AR NW, which is propagated to this AddRec. 1704 // Negative step causes unsigned wrap, but it still can't self-wrap. 1705 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1706 // Return the expression with the addrec on the outside. 1707 return getAddRecExpr( 1708 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1709 Depth + 1), 1710 getSignExtendExpr(Step, Ty, Depth + 1), L, 1711 AR->getNoWrapFlags()); 1712 } 1713 } 1714 } 1715 1716 // Normally, in the cases we can prove no-overflow via a 1717 // backedge guarding condition, we can also compute a backedge 1718 // taken count for the loop. The exceptions are assumptions and 1719 // guards present in the loop -- SCEV is not great at exploiting 1720 // these to compute max backedge taken counts, but can still use 1721 // these to prove lack of overflow. Use this fact to avoid 1722 // doing extra work that may not pay off. 1723 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1724 !AC.assumptions().empty()) { 1725 1726 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1727 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1728 if (AR->hasNoUnsignedWrap()) { 1729 // Same as nuw case above - duplicated here to avoid a compile time 1730 // issue. It's not clear that the order of checks does matter, but 1731 // it's one of two issue possible causes for a change which was 1732 // reverted. Be conservative for the moment. 1733 return getAddRecExpr( 1734 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1735 Depth + 1), 1736 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1737 AR->getNoWrapFlags()); 1738 } 1739 1740 // For a negative step, we can extend the operands iff doing so only 1741 // traverses values in the range zext([0,UINT_MAX]). 1742 if (isKnownNegative(Step)) { 1743 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1744 getSignedRangeMin(Step)); 1745 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1746 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1747 // Cache knowledge of AR NW, which is propagated to this 1748 // AddRec. Negative step causes unsigned wrap, but it 1749 // still can't self-wrap. 1750 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1751 // Return the expression with the addrec on the outside. 1752 return getAddRecExpr( 1753 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1754 Depth + 1), 1755 getSignExtendExpr(Step, Ty, Depth + 1), L, 1756 AR->getNoWrapFlags()); 1757 } 1758 } 1759 } 1760 1761 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1762 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1763 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1764 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1765 const APInt &C = SC->getAPInt(); 1766 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1767 if (D != 0) { 1768 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1769 const SCEV *SResidual = 1770 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1771 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1772 return getAddExpr(SZExtD, SZExtR, 1773 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1774 Depth + 1); 1775 } 1776 } 1777 1778 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1779 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1780 return getAddRecExpr( 1781 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1782 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1783 } 1784 } 1785 1786 // zext(A % B) --> zext(A) % zext(B) 1787 { 1788 const SCEV *LHS; 1789 const SCEV *RHS; 1790 if (matchURem(Op, LHS, RHS)) 1791 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1792 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1793 } 1794 1795 // zext(A / B) --> zext(A) / zext(B). 1796 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1797 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1798 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1799 1800 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1801 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1802 if (SA->hasNoUnsignedWrap()) { 1803 // If the addition does not unsign overflow then we can, by definition, 1804 // commute the zero extension with the addition operation. 1805 SmallVector<const SCEV *, 4> Ops; 1806 for (const auto *Op : SA->operands()) 1807 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1808 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1809 } 1810 1811 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1812 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1813 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1814 // 1815 // Often address arithmetics contain expressions like 1816 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1817 // This transformation is useful while proving that such expressions are 1818 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1819 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1820 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1821 if (D != 0) { 1822 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1823 const SCEV *SResidual = 1824 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1825 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1826 return getAddExpr(SZExtD, SZExtR, 1827 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1828 Depth + 1); 1829 } 1830 } 1831 } 1832 1833 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1834 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1835 if (SM->hasNoUnsignedWrap()) { 1836 // If the multiply does not unsign overflow then we can, by definition, 1837 // commute the zero extension with the multiply operation. 1838 SmallVector<const SCEV *, 4> Ops; 1839 for (const auto *Op : SM->operands()) 1840 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1841 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1842 } 1843 1844 // zext(2^K * (trunc X to iN)) to iM -> 1845 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1846 // 1847 // Proof: 1848 // 1849 // zext(2^K * (trunc X to iN)) to iM 1850 // = zext((trunc X to iN) << K) to iM 1851 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1852 // (because shl removes the top K bits) 1853 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1854 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1855 // 1856 if (SM->getNumOperands() == 2) 1857 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1858 if (MulLHS->getAPInt().isPowerOf2()) 1859 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1860 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1861 MulLHS->getAPInt().logBase2(); 1862 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1863 return getMulExpr( 1864 getZeroExtendExpr(MulLHS, Ty), 1865 getZeroExtendExpr( 1866 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1867 SCEV::FlagNUW, Depth + 1); 1868 } 1869 } 1870 1871 // The cast wasn't folded; create an explicit cast node. 1872 // Recompute the insert position, as it may have been invalidated. 1873 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1874 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1875 Op, Ty); 1876 UniqueSCEVs.InsertNode(S, IP); 1877 addToLoopUseLists(S); 1878 registerUser(S, Op); 1879 return S; 1880 } 1881 1882 const SCEV * 1883 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1884 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1885 "This is not an extending conversion!"); 1886 assert(isSCEVable(Ty) && 1887 "This is not a conversion to a SCEVable type!"); 1888 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1889 Ty = getEffectiveSCEVType(Ty); 1890 1891 // Fold if the operand is constant. 1892 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1893 return getConstant( 1894 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1895 1896 // sext(sext(x)) --> sext(x) 1897 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1898 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1899 1900 // sext(zext(x)) --> zext(x) 1901 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1902 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1903 1904 // Before doing any expensive analysis, check to see if we've already 1905 // computed a SCEV for this Op and Ty. 1906 FoldingSetNodeID ID; 1907 ID.AddInteger(scSignExtend); 1908 ID.AddPointer(Op); 1909 ID.AddPointer(Ty); 1910 void *IP = nullptr; 1911 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1912 // Limit recursion depth. 1913 if (Depth > MaxCastDepth) { 1914 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1915 Op, Ty); 1916 UniqueSCEVs.InsertNode(S, IP); 1917 addToLoopUseLists(S); 1918 registerUser(S, Op); 1919 return S; 1920 } 1921 1922 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1923 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1924 // It's possible the bits taken off by the truncate were all sign bits. If 1925 // so, we should be able to simplify this further. 1926 const SCEV *X = ST->getOperand(); 1927 ConstantRange CR = getSignedRange(X); 1928 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1929 unsigned NewBits = getTypeSizeInBits(Ty); 1930 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1931 CR.sextOrTrunc(NewBits))) 1932 return getTruncateOrSignExtend(X, Ty, Depth); 1933 } 1934 1935 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1936 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1937 if (SA->hasNoSignedWrap()) { 1938 // If the addition does not sign overflow then we can, by definition, 1939 // commute the sign extension with the addition operation. 1940 SmallVector<const SCEV *, 4> Ops; 1941 for (const auto *Op : SA->operands()) 1942 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1943 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1944 } 1945 1946 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1947 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1948 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1949 // 1950 // For instance, this will bring two seemingly different expressions: 1951 // 1 + sext(5 + 20 * %x + 24 * %y) and 1952 // sext(6 + 20 * %x + 24 * %y) 1953 // to the same form: 1954 // 2 + sext(4 + 20 * %x + 24 * %y) 1955 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1956 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1957 if (D != 0) { 1958 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1959 const SCEV *SResidual = 1960 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1961 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1962 return getAddExpr(SSExtD, SSExtR, 1963 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1964 Depth + 1); 1965 } 1966 } 1967 } 1968 // If the input value is a chrec scev, and we can prove that the value 1969 // did not overflow the old, smaller, value, we can sign extend all of the 1970 // operands (often constants). This allows analysis of something like 1971 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1972 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1973 if (AR->isAffine()) { 1974 const SCEV *Start = AR->getStart(); 1975 const SCEV *Step = AR->getStepRecurrence(*this); 1976 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1977 const Loop *L = AR->getLoop(); 1978 1979 if (!AR->hasNoSignedWrap()) { 1980 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1981 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1982 } 1983 1984 // If we have special knowledge that this addrec won't overflow, 1985 // we don't need to do any further analysis. 1986 if (AR->hasNoSignedWrap()) 1987 return getAddRecExpr( 1988 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1989 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1990 1991 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1992 // Note that this serves two purposes: It filters out loops that are 1993 // simply not analyzable, and it covers the case where this code is 1994 // being called from within backedge-taken count analysis, such that 1995 // attempting to ask for the backedge-taken count would likely result 1996 // in infinite recursion. In the later case, the analysis code will 1997 // cope with a conservative value, and it will take care to purge 1998 // that value once it has finished. 1999 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2000 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2001 // Manually compute the final value for AR, checking for 2002 // overflow. 2003 2004 // Check whether the backedge-taken count can be losslessly casted to 2005 // the addrec's type. The count is always unsigned. 2006 const SCEV *CastedMaxBECount = 2007 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2008 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2009 CastedMaxBECount, MaxBECount->getType(), Depth); 2010 if (MaxBECount == RecastedMaxBECount) { 2011 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2012 // Check whether Start+Step*MaxBECount has no signed overflow. 2013 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2014 SCEV::FlagAnyWrap, Depth + 1); 2015 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2016 SCEV::FlagAnyWrap, 2017 Depth + 1), 2018 WideTy, Depth + 1); 2019 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2020 const SCEV *WideMaxBECount = 2021 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2022 const SCEV *OperandExtendedAdd = 2023 getAddExpr(WideStart, 2024 getMulExpr(WideMaxBECount, 2025 getSignExtendExpr(Step, WideTy, Depth + 1), 2026 SCEV::FlagAnyWrap, Depth + 1), 2027 SCEV::FlagAnyWrap, Depth + 1); 2028 if (SAdd == OperandExtendedAdd) { 2029 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2030 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2031 // Return the expression with the addrec on the outside. 2032 return getAddRecExpr( 2033 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2034 Depth + 1), 2035 getSignExtendExpr(Step, Ty, Depth + 1), L, 2036 AR->getNoWrapFlags()); 2037 } 2038 // Similar to above, only this time treat the step value as unsigned. 2039 // This covers loops that count up with an unsigned step. 2040 OperandExtendedAdd = 2041 getAddExpr(WideStart, 2042 getMulExpr(WideMaxBECount, 2043 getZeroExtendExpr(Step, WideTy, Depth + 1), 2044 SCEV::FlagAnyWrap, Depth + 1), 2045 SCEV::FlagAnyWrap, Depth + 1); 2046 if (SAdd == OperandExtendedAdd) { 2047 // If AR wraps around then 2048 // 2049 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2050 // => SAdd != OperandExtendedAdd 2051 // 2052 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2053 // (SAdd == OperandExtendedAdd => AR is NW) 2054 2055 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2056 2057 // Return the expression with the addrec on the outside. 2058 return getAddRecExpr( 2059 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2060 Depth + 1), 2061 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2062 AR->getNoWrapFlags()); 2063 } 2064 } 2065 } 2066 2067 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2068 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2069 if (AR->hasNoSignedWrap()) { 2070 // Same as nsw case above - duplicated here to avoid a compile time 2071 // issue. It's not clear that the order of checks does matter, but 2072 // it's one of two issue possible causes for a change which was 2073 // reverted. Be conservative for the moment. 2074 return getAddRecExpr( 2075 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2076 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2077 } 2078 2079 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2080 // if D + (C - D + Step * n) could be proven to not signed wrap 2081 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2082 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2083 const APInt &C = SC->getAPInt(); 2084 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2085 if (D != 0) { 2086 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2087 const SCEV *SResidual = 2088 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2089 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2090 return getAddExpr(SSExtD, SSExtR, 2091 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2092 Depth + 1); 2093 } 2094 } 2095 2096 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2097 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2098 return getAddRecExpr( 2099 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2100 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2101 } 2102 } 2103 2104 // If the input value is provably positive and we could not simplify 2105 // away the sext build a zext instead. 2106 if (isKnownNonNegative(Op)) 2107 return getZeroExtendExpr(Op, Ty, Depth + 1); 2108 2109 // The cast wasn't folded; create an explicit cast node. 2110 // Recompute the insert position, as it may have been invalidated. 2111 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2112 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2113 Op, Ty); 2114 UniqueSCEVs.InsertNode(S, IP); 2115 addToLoopUseLists(S); 2116 registerUser(S, { Op }); 2117 return S; 2118 } 2119 2120 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2121 /// unspecified bits out to the given type. 2122 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2123 Type *Ty) { 2124 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2125 "This is not an extending conversion!"); 2126 assert(isSCEVable(Ty) && 2127 "This is not a conversion to a SCEVable type!"); 2128 Ty = getEffectiveSCEVType(Ty); 2129 2130 // Sign-extend negative constants. 2131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2132 if (SC->getAPInt().isNegative()) 2133 return getSignExtendExpr(Op, Ty); 2134 2135 // Peel off a truncate cast. 2136 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2137 const SCEV *NewOp = T->getOperand(); 2138 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2139 return getAnyExtendExpr(NewOp, Ty); 2140 return getTruncateOrNoop(NewOp, Ty); 2141 } 2142 2143 // Next try a zext cast. If the cast is folded, use it. 2144 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2145 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2146 return ZExt; 2147 2148 // Next try a sext cast. If the cast is folded, use it. 2149 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2150 if (!isa<SCEVSignExtendExpr>(SExt)) 2151 return SExt; 2152 2153 // Force the cast to be folded into the operands of an addrec. 2154 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2155 SmallVector<const SCEV *, 4> Ops; 2156 for (const SCEV *Op : AR->operands()) 2157 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2158 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2159 } 2160 2161 // If the expression is obviously signed, use the sext cast value. 2162 if (isa<SCEVSMaxExpr>(Op)) 2163 return SExt; 2164 2165 // Absent any other information, use the zext cast value. 2166 return ZExt; 2167 } 2168 2169 /// Process the given Ops list, which is a list of operands to be added under 2170 /// the given scale, update the given map. This is a helper function for 2171 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2172 /// that would form an add expression like this: 2173 /// 2174 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2175 /// 2176 /// where A and B are constants, update the map with these values: 2177 /// 2178 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2179 /// 2180 /// and add 13 + A*B*29 to AccumulatedConstant. 2181 /// This will allow getAddRecExpr to produce this: 2182 /// 2183 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2184 /// 2185 /// This form often exposes folding opportunities that are hidden in 2186 /// the original operand list. 2187 /// 2188 /// Return true iff it appears that any interesting folding opportunities 2189 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2190 /// the common case where no interesting opportunities are present, and 2191 /// is also used as a check to avoid infinite recursion. 2192 static bool 2193 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2194 SmallVectorImpl<const SCEV *> &NewOps, 2195 APInt &AccumulatedConstant, 2196 const SCEV *const *Ops, size_t NumOperands, 2197 const APInt &Scale, 2198 ScalarEvolution &SE) { 2199 bool Interesting = false; 2200 2201 // Iterate over the add operands. They are sorted, with constants first. 2202 unsigned i = 0; 2203 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2204 ++i; 2205 // Pull a buried constant out to the outside. 2206 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2207 Interesting = true; 2208 AccumulatedConstant += Scale * C->getAPInt(); 2209 } 2210 2211 // Next comes everything else. We're especially interested in multiplies 2212 // here, but they're in the middle, so just visit the rest with one loop. 2213 for (; i != NumOperands; ++i) { 2214 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2215 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2216 APInt NewScale = 2217 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2218 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2219 // A multiplication of a constant with another add; recurse. 2220 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2221 Interesting |= 2222 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2223 Add->op_begin(), Add->getNumOperands(), 2224 NewScale, SE); 2225 } else { 2226 // A multiplication of a constant with some other value. Update 2227 // the map. 2228 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2229 const SCEV *Key = SE.getMulExpr(MulOps); 2230 auto Pair = M.insert({Key, NewScale}); 2231 if (Pair.second) { 2232 NewOps.push_back(Pair.first->first); 2233 } else { 2234 Pair.first->second += NewScale; 2235 // The map already had an entry for this value, which may indicate 2236 // a folding opportunity. 2237 Interesting = true; 2238 } 2239 } 2240 } else { 2241 // An ordinary operand. Update the map. 2242 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2243 M.insert({Ops[i], Scale}); 2244 if (Pair.second) { 2245 NewOps.push_back(Pair.first->first); 2246 } else { 2247 Pair.first->second += Scale; 2248 // The map already had an entry for this value, which may indicate 2249 // a folding opportunity. 2250 Interesting = true; 2251 } 2252 } 2253 } 2254 2255 return Interesting; 2256 } 2257 2258 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2259 const SCEV *LHS, const SCEV *RHS) { 2260 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2261 SCEV::NoWrapFlags, unsigned); 2262 switch (BinOp) { 2263 default: 2264 llvm_unreachable("Unsupported binary op"); 2265 case Instruction::Add: 2266 Operation = &ScalarEvolution::getAddExpr; 2267 break; 2268 case Instruction::Sub: 2269 Operation = &ScalarEvolution::getMinusSCEV; 2270 break; 2271 case Instruction::Mul: 2272 Operation = &ScalarEvolution::getMulExpr; 2273 break; 2274 } 2275 2276 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2277 Signed ? &ScalarEvolution::getSignExtendExpr 2278 : &ScalarEvolution::getZeroExtendExpr; 2279 2280 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2281 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2282 auto *WideTy = 2283 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2284 2285 const SCEV *A = (this->*Extension)( 2286 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2287 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2288 (this->*Extension)(RHS, WideTy, 0), 2289 SCEV::FlagAnyWrap, 0); 2290 return A == B; 2291 } 2292 2293 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2294 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2295 const OverflowingBinaryOperator *OBO) { 2296 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2297 2298 if (OBO->hasNoUnsignedWrap()) 2299 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2300 if (OBO->hasNoSignedWrap()) 2301 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2302 2303 bool Deduced = false; 2304 2305 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2306 return {Flags, Deduced}; 2307 2308 if (OBO->getOpcode() != Instruction::Add && 2309 OBO->getOpcode() != Instruction::Sub && 2310 OBO->getOpcode() != Instruction::Mul) 2311 return {Flags, Deduced}; 2312 2313 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2314 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2315 2316 if (!OBO->hasNoUnsignedWrap() && 2317 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2318 /* Signed */ false, LHS, RHS)) { 2319 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2320 Deduced = true; 2321 } 2322 2323 if (!OBO->hasNoSignedWrap() && 2324 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2325 /* Signed */ true, LHS, RHS)) { 2326 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2327 Deduced = true; 2328 } 2329 2330 return {Flags, Deduced}; 2331 } 2332 2333 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2334 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2335 // can't-overflow flags for the operation if possible. 2336 static SCEV::NoWrapFlags 2337 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2338 const ArrayRef<const SCEV *> Ops, 2339 SCEV::NoWrapFlags Flags) { 2340 using namespace std::placeholders; 2341 2342 using OBO = OverflowingBinaryOperator; 2343 2344 bool CanAnalyze = 2345 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2346 (void)CanAnalyze; 2347 assert(CanAnalyze && "don't call from other places!"); 2348 2349 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2350 SCEV::NoWrapFlags SignOrUnsignWrap = 2351 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2352 2353 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2354 auto IsKnownNonNegative = [&](const SCEV *S) { 2355 return SE->isKnownNonNegative(S); 2356 }; 2357 2358 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2359 Flags = 2360 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2361 2362 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2363 2364 if (SignOrUnsignWrap != SignOrUnsignMask && 2365 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2366 isa<SCEVConstant>(Ops[0])) { 2367 2368 auto Opcode = [&] { 2369 switch (Type) { 2370 case scAddExpr: 2371 return Instruction::Add; 2372 case scMulExpr: 2373 return Instruction::Mul; 2374 default: 2375 llvm_unreachable("Unexpected SCEV op."); 2376 } 2377 }(); 2378 2379 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2380 2381 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2382 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2383 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2384 Opcode, C, OBO::NoSignedWrap); 2385 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2387 } 2388 2389 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2390 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2391 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2392 Opcode, C, OBO::NoUnsignedWrap); 2393 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2394 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2395 } 2396 } 2397 2398 // <0,+,nonnegative><nw> is also nuw 2399 // TODO: Add corresponding nsw case 2400 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2401 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2402 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2403 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2404 2405 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2406 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2407 Ops.size() == 2) { 2408 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2409 if (UDiv->getOperand(1) == Ops[1]) 2410 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2411 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2412 if (UDiv->getOperand(1) == Ops[0]) 2413 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2414 } 2415 2416 return Flags; 2417 } 2418 2419 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2420 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2421 } 2422 2423 /// Get a canonical add expression, or something simpler if possible. 2424 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2425 SCEV::NoWrapFlags OrigFlags, 2426 unsigned Depth) { 2427 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2428 "only nuw or nsw allowed"); 2429 assert(!Ops.empty() && "Cannot get empty add!"); 2430 if (Ops.size() == 1) return Ops[0]; 2431 #ifndef NDEBUG 2432 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2433 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2434 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2435 "SCEVAddExpr operand types don't match!"); 2436 unsigned NumPtrs = count_if( 2437 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2438 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2439 #endif 2440 2441 // Sort by complexity, this groups all similar expression types together. 2442 GroupByComplexity(Ops, &LI, DT); 2443 2444 // If there are any constants, fold them together. 2445 unsigned Idx = 0; 2446 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2447 ++Idx; 2448 assert(Idx < Ops.size()); 2449 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2450 // We found two constants, fold them together! 2451 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2452 if (Ops.size() == 2) return Ops[0]; 2453 Ops.erase(Ops.begin()+1); // Erase the folded element 2454 LHSC = cast<SCEVConstant>(Ops[0]); 2455 } 2456 2457 // If we are left with a constant zero being added, strip it off. 2458 if (LHSC->getValue()->isZero()) { 2459 Ops.erase(Ops.begin()); 2460 --Idx; 2461 } 2462 2463 if (Ops.size() == 1) return Ops[0]; 2464 } 2465 2466 // Delay expensive flag strengthening until necessary. 2467 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2468 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2469 }; 2470 2471 // Limit recursion calls depth. 2472 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2473 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2474 2475 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2476 // Don't strengthen flags if we have no new information. 2477 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2478 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2479 Add->setNoWrapFlags(ComputeFlags(Ops)); 2480 return S; 2481 } 2482 2483 // Okay, check to see if the same value occurs in the operand list more than 2484 // once. If so, merge them together into an multiply expression. Since we 2485 // sorted the list, these values are required to be adjacent. 2486 Type *Ty = Ops[0]->getType(); 2487 bool FoundMatch = false; 2488 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2489 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2490 // Scan ahead to count how many equal operands there are. 2491 unsigned Count = 2; 2492 while (i+Count != e && Ops[i+Count] == Ops[i]) 2493 ++Count; 2494 // Merge the values into a multiply. 2495 const SCEV *Scale = getConstant(Ty, Count); 2496 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2497 if (Ops.size() == Count) 2498 return Mul; 2499 Ops[i] = Mul; 2500 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2501 --i; e -= Count - 1; 2502 FoundMatch = true; 2503 } 2504 if (FoundMatch) 2505 return getAddExpr(Ops, OrigFlags, Depth + 1); 2506 2507 // Check for truncates. If all the operands are truncated from the same 2508 // type, see if factoring out the truncate would permit the result to be 2509 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2510 // if the contents of the resulting outer trunc fold to something simple. 2511 auto FindTruncSrcType = [&]() -> Type * { 2512 // We're ultimately looking to fold an addrec of truncs and muls of only 2513 // constants and truncs, so if we find any other types of SCEV 2514 // as operands of the addrec then we bail and return nullptr here. 2515 // Otherwise, we return the type of the operand of a trunc that we find. 2516 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2517 return T->getOperand()->getType(); 2518 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2519 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2520 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2521 return T->getOperand()->getType(); 2522 } 2523 return nullptr; 2524 }; 2525 if (auto *SrcType = FindTruncSrcType()) { 2526 SmallVector<const SCEV *, 8> LargeOps; 2527 bool Ok = true; 2528 // Check all the operands to see if they can be represented in the 2529 // source type of the truncate. 2530 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2531 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2532 if (T->getOperand()->getType() != SrcType) { 2533 Ok = false; 2534 break; 2535 } 2536 LargeOps.push_back(T->getOperand()); 2537 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2538 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2539 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2540 SmallVector<const SCEV *, 8> LargeMulOps; 2541 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2542 if (const SCEVTruncateExpr *T = 2543 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2544 if (T->getOperand()->getType() != SrcType) { 2545 Ok = false; 2546 break; 2547 } 2548 LargeMulOps.push_back(T->getOperand()); 2549 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2550 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2551 } else { 2552 Ok = false; 2553 break; 2554 } 2555 } 2556 if (Ok) 2557 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2558 } else { 2559 Ok = false; 2560 break; 2561 } 2562 } 2563 if (Ok) { 2564 // Evaluate the expression in the larger type. 2565 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2566 // If it folds to something simple, use it. Otherwise, don't. 2567 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2568 return getTruncateExpr(Fold, Ty); 2569 } 2570 } 2571 2572 if (Ops.size() == 2) { 2573 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2574 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2575 // C1). 2576 const SCEV *A = Ops[0]; 2577 const SCEV *B = Ops[1]; 2578 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2579 auto *C = dyn_cast<SCEVConstant>(A); 2580 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2581 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2582 auto C2 = C->getAPInt(); 2583 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2584 2585 APInt ConstAdd = C1 + C2; 2586 auto AddFlags = AddExpr->getNoWrapFlags(); 2587 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2588 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2589 ConstAdd.ule(C1)) { 2590 PreservedFlags = 2591 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2592 } 2593 2594 // Adding a constant with the same sign and small magnitude is NSW, if the 2595 // original AddExpr was NSW. 2596 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2597 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2598 ConstAdd.abs().ule(C1.abs())) { 2599 PreservedFlags = 2600 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2601 } 2602 2603 if (PreservedFlags != SCEV::FlagAnyWrap) { 2604 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2605 NewOps[0] = getConstant(ConstAdd); 2606 return getAddExpr(NewOps, PreservedFlags); 2607 } 2608 } 2609 } 2610 2611 // Skip past any other cast SCEVs. 2612 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2613 ++Idx; 2614 2615 // If there are add operands they would be next. 2616 if (Idx < Ops.size()) { 2617 bool DeletedAdd = false; 2618 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2619 // common NUW flag for expression after inlining. Other flags cannot be 2620 // preserved, because they may depend on the original order of operations. 2621 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2622 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2623 if (Ops.size() > AddOpsInlineThreshold || 2624 Add->getNumOperands() > AddOpsInlineThreshold) 2625 break; 2626 // If we have an add, expand the add operands onto the end of the operands 2627 // list. 2628 Ops.erase(Ops.begin()+Idx); 2629 Ops.append(Add->op_begin(), Add->op_end()); 2630 DeletedAdd = true; 2631 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2632 } 2633 2634 // If we deleted at least one add, we added operands to the end of the list, 2635 // and they are not necessarily sorted. Recurse to resort and resimplify 2636 // any operands we just acquired. 2637 if (DeletedAdd) 2638 return getAddExpr(Ops, CommonFlags, Depth + 1); 2639 } 2640 2641 // Skip over the add expression until we get to a multiply. 2642 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2643 ++Idx; 2644 2645 // Check to see if there are any folding opportunities present with 2646 // operands multiplied by constant values. 2647 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2648 uint64_t BitWidth = getTypeSizeInBits(Ty); 2649 DenseMap<const SCEV *, APInt> M; 2650 SmallVector<const SCEV *, 8> NewOps; 2651 APInt AccumulatedConstant(BitWidth, 0); 2652 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2653 Ops.data(), Ops.size(), 2654 APInt(BitWidth, 1), *this)) { 2655 struct APIntCompare { 2656 bool operator()(const APInt &LHS, const APInt &RHS) const { 2657 return LHS.ult(RHS); 2658 } 2659 }; 2660 2661 // Some interesting folding opportunity is present, so its worthwhile to 2662 // re-generate the operands list. Group the operands by constant scale, 2663 // to avoid multiplying by the same constant scale multiple times. 2664 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2665 for (const SCEV *NewOp : NewOps) 2666 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2667 // Re-generate the operands list. 2668 Ops.clear(); 2669 if (AccumulatedConstant != 0) 2670 Ops.push_back(getConstant(AccumulatedConstant)); 2671 for (auto &MulOp : MulOpLists) { 2672 if (MulOp.first == 1) { 2673 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2674 } else if (MulOp.first != 0) { 2675 Ops.push_back(getMulExpr( 2676 getConstant(MulOp.first), 2677 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2678 SCEV::FlagAnyWrap, Depth + 1)); 2679 } 2680 } 2681 if (Ops.empty()) 2682 return getZero(Ty); 2683 if (Ops.size() == 1) 2684 return Ops[0]; 2685 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2686 } 2687 } 2688 2689 // If we are adding something to a multiply expression, make sure the 2690 // something is not already an operand of the multiply. If so, merge it into 2691 // the multiply. 2692 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2693 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2694 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2695 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2696 if (isa<SCEVConstant>(MulOpSCEV)) 2697 continue; 2698 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2699 if (MulOpSCEV == Ops[AddOp]) { 2700 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2701 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2702 if (Mul->getNumOperands() != 2) { 2703 // If the multiply has more than two operands, we must get the 2704 // Y*Z term. 2705 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2706 Mul->op_begin()+MulOp); 2707 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2708 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2709 } 2710 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2711 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2712 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2713 SCEV::FlagAnyWrap, Depth + 1); 2714 if (Ops.size() == 2) return OuterMul; 2715 if (AddOp < Idx) { 2716 Ops.erase(Ops.begin()+AddOp); 2717 Ops.erase(Ops.begin()+Idx-1); 2718 } else { 2719 Ops.erase(Ops.begin()+Idx); 2720 Ops.erase(Ops.begin()+AddOp-1); 2721 } 2722 Ops.push_back(OuterMul); 2723 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2724 } 2725 2726 // Check this multiply against other multiplies being added together. 2727 for (unsigned OtherMulIdx = Idx+1; 2728 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2729 ++OtherMulIdx) { 2730 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2731 // If MulOp occurs in OtherMul, we can fold the two multiplies 2732 // together. 2733 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2734 OMulOp != e; ++OMulOp) 2735 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2736 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2737 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2738 if (Mul->getNumOperands() != 2) { 2739 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2740 Mul->op_begin()+MulOp); 2741 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2742 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2743 } 2744 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2745 if (OtherMul->getNumOperands() != 2) { 2746 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2747 OtherMul->op_begin()+OMulOp); 2748 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2749 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2750 } 2751 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2752 const SCEV *InnerMulSum = 2753 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2754 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2755 SCEV::FlagAnyWrap, Depth + 1); 2756 if (Ops.size() == 2) return OuterMul; 2757 Ops.erase(Ops.begin()+Idx); 2758 Ops.erase(Ops.begin()+OtherMulIdx-1); 2759 Ops.push_back(OuterMul); 2760 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2761 } 2762 } 2763 } 2764 } 2765 2766 // If there are any add recurrences in the operands list, see if any other 2767 // added values are loop invariant. If so, we can fold them into the 2768 // recurrence. 2769 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2770 ++Idx; 2771 2772 // Scan over all recurrences, trying to fold loop invariants into them. 2773 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2774 // Scan all of the other operands to this add and add them to the vector if 2775 // they are loop invariant w.r.t. the recurrence. 2776 SmallVector<const SCEV *, 8> LIOps; 2777 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2778 const Loop *AddRecLoop = AddRec->getLoop(); 2779 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2780 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2781 LIOps.push_back(Ops[i]); 2782 Ops.erase(Ops.begin()+i); 2783 --i; --e; 2784 } 2785 2786 // If we found some loop invariants, fold them into the recurrence. 2787 if (!LIOps.empty()) { 2788 // Compute nowrap flags for the addition of the loop-invariant ops and 2789 // the addrec. Temporarily push it as an operand for that purpose. These 2790 // flags are valid in the scope of the addrec only. 2791 LIOps.push_back(AddRec); 2792 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2793 LIOps.pop_back(); 2794 2795 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2796 LIOps.push_back(AddRec->getStart()); 2797 2798 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2799 2800 // It is not in general safe to propagate flags valid on an add within 2801 // the addrec scope to one outside it. We must prove that the inner 2802 // scope is guaranteed to execute if the outer one does to be able to 2803 // safely propagate. We know the program is undefined if poison is 2804 // produced on the inner scoped addrec. We also know that *for this use* 2805 // the outer scoped add can't overflow (because of the flags we just 2806 // computed for the inner scoped add) without the program being undefined. 2807 // Proving that entry to the outer scope neccesitates entry to the inner 2808 // scope, thus proves the program undefined if the flags would be violated 2809 // in the outer scope. 2810 SCEV::NoWrapFlags AddFlags = Flags; 2811 if (AddFlags != SCEV::FlagAnyWrap) { 2812 auto *DefI = getDefiningScopeBound(LIOps); 2813 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2814 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2815 AddFlags = SCEV::FlagAnyWrap; 2816 } 2817 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2818 2819 // Build the new addrec. Propagate the NUW and NSW flags if both the 2820 // outer add and the inner addrec are guaranteed to have no overflow. 2821 // Always propagate NW. 2822 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2823 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2824 2825 // If all of the other operands were loop invariant, we are done. 2826 if (Ops.size() == 1) return NewRec; 2827 2828 // Otherwise, add the folded AddRec by the non-invariant parts. 2829 for (unsigned i = 0;; ++i) 2830 if (Ops[i] == AddRec) { 2831 Ops[i] = NewRec; 2832 break; 2833 } 2834 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2835 } 2836 2837 // Okay, if there weren't any loop invariants to be folded, check to see if 2838 // there are multiple AddRec's with the same loop induction variable being 2839 // added together. If so, we can fold them. 2840 for (unsigned OtherIdx = Idx+1; 2841 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2842 ++OtherIdx) { 2843 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2844 // so that the 1st found AddRecExpr is dominated by all others. 2845 assert(DT.dominates( 2846 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2847 AddRec->getLoop()->getHeader()) && 2848 "AddRecExprs are not sorted in reverse dominance order?"); 2849 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2850 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2851 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2852 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2853 ++OtherIdx) { 2854 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2855 if (OtherAddRec->getLoop() == AddRecLoop) { 2856 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2857 i != e; ++i) { 2858 if (i >= AddRecOps.size()) { 2859 AddRecOps.append(OtherAddRec->op_begin()+i, 2860 OtherAddRec->op_end()); 2861 break; 2862 } 2863 SmallVector<const SCEV *, 2> TwoOps = { 2864 AddRecOps[i], OtherAddRec->getOperand(i)}; 2865 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2866 } 2867 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2868 } 2869 } 2870 // Step size has changed, so we cannot guarantee no self-wraparound. 2871 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2872 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2873 } 2874 } 2875 2876 // Otherwise couldn't fold anything into this recurrence. Move onto the 2877 // next one. 2878 } 2879 2880 // Okay, it looks like we really DO need an add expr. Check to see if we 2881 // already have one, otherwise create a new one. 2882 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2883 } 2884 2885 const SCEV * 2886 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2887 SCEV::NoWrapFlags Flags) { 2888 FoldingSetNodeID ID; 2889 ID.AddInteger(scAddExpr); 2890 for (const SCEV *Op : Ops) 2891 ID.AddPointer(Op); 2892 void *IP = nullptr; 2893 SCEVAddExpr *S = 2894 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2895 if (!S) { 2896 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2897 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2898 S = new (SCEVAllocator) 2899 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2900 UniqueSCEVs.InsertNode(S, IP); 2901 addToLoopUseLists(S); 2902 registerUser(S, Ops); 2903 } 2904 S->setNoWrapFlags(Flags); 2905 return S; 2906 } 2907 2908 const SCEV * 2909 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2910 const Loop *L, SCEV::NoWrapFlags Flags) { 2911 FoldingSetNodeID ID; 2912 ID.AddInteger(scAddRecExpr); 2913 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2914 ID.AddPointer(Ops[i]); 2915 ID.AddPointer(L); 2916 void *IP = nullptr; 2917 SCEVAddRecExpr *S = 2918 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2919 if (!S) { 2920 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2921 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2922 S = new (SCEVAllocator) 2923 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2924 UniqueSCEVs.InsertNode(S, IP); 2925 addToLoopUseLists(S); 2926 registerUser(S, Ops); 2927 } 2928 setNoWrapFlags(S, Flags); 2929 return S; 2930 } 2931 2932 const SCEV * 2933 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2934 SCEV::NoWrapFlags Flags) { 2935 FoldingSetNodeID ID; 2936 ID.AddInteger(scMulExpr); 2937 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2938 ID.AddPointer(Ops[i]); 2939 void *IP = nullptr; 2940 SCEVMulExpr *S = 2941 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2942 if (!S) { 2943 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2944 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2945 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2946 O, Ops.size()); 2947 UniqueSCEVs.InsertNode(S, IP); 2948 addToLoopUseLists(S); 2949 registerUser(S, Ops); 2950 } 2951 S->setNoWrapFlags(Flags); 2952 return S; 2953 } 2954 2955 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2956 uint64_t k = i*j; 2957 if (j > 1 && k / j != i) Overflow = true; 2958 return k; 2959 } 2960 2961 /// Compute the result of "n choose k", the binomial coefficient. If an 2962 /// intermediate computation overflows, Overflow will be set and the return will 2963 /// be garbage. Overflow is not cleared on absence of overflow. 2964 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2965 // We use the multiplicative formula: 2966 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2967 // At each iteration, we take the n-th term of the numeral and divide by the 2968 // (k-n)th term of the denominator. This division will always produce an 2969 // integral result, and helps reduce the chance of overflow in the 2970 // intermediate computations. However, we can still overflow even when the 2971 // final result would fit. 2972 2973 if (n == 0 || n == k) return 1; 2974 if (k > n) return 0; 2975 2976 if (k > n/2) 2977 k = n-k; 2978 2979 uint64_t r = 1; 2980 for (uint64_t i = 1; i <= k; ++i) { 2981 r = umul_ov(r, n-(i-1), Overflow); 2982 r /= i; 2983 } 2984 return r; 2985 } 2986 2987 /// Determine if any of the operands in this SCEV are a constant or if 2988 /// any of the add or multiply expressions in this SCEV contain a constant. 2989 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2990 struct FindConstantInAddMulChain { 2991 bool FoundConstant = false; 2992 2993 bool follow(const SCEV *S) { 2994 FoundConstant |= isa<SCEVConstant>(S); 2995 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2996 } 2997 2998 bool isDone() const { 2999 return FoundConstant; 3000 } 3001 }; 3002 3003 FindConstantInAddMulChain F; 3004 SCEVTraversal<FindConstantInAddMulChain> ST(F); 3005 ST.visitAll(StartExpr); 3006 return F.FoundConstant; 3007 } 3008 3009 /// Get a canonical multiply expression, or something simpler if possible. 3010 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3011 SCEV::NoWrapFlags OrigFlags, 3012 unsigned Depth) { 3013 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3014 "only nuw or nsw allowed"); 3015 assert(!Ops.empty() && "Cannot get empty mul!"); 3016 if (Ops.size() == 1) return Ops[0]; 3017 #ifndef NDEBUG 3018 Type *ETy = Ops[0]->getType(); 3019 assert(!ETy->isPointerTy()); 3020 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3021 assert(Ops[i]->getType() == ETy && 3022 "SCEVMulExpr operand types don't match!"); 3023 #endif 3024 3025 // Sort by complexity, this groups all similar expression types together. 3026 GroupByComplexity(Ops, &LI, DT); 3027 3028 // If there are any constants, fold them together. 3029 unsigned Idx = 0; 3030 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3031 ++Idx; 3032 assert(Idx < Ops.size()); 3033 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3034 // We found two constants, fold them together! 3035 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3036 if (Ops.size() == 2) return Ops[0]; 3037 Ops.erase(Ops.begin()+1); // Erase the folded element 3038 LHSC = cast<SCEVConstant>(Ops[0]); 3039 } 3040 3041 // If we have a multiply of zero, it will always be zero. 3042 if (LHSC->getValue()->isZero()) 3043 return LHSC; 3044 3045 // If we are left with a constant one being multiplied, strip it off. 3046 if (LHSC->getValue()->isOne()) { 3047 Ops.erase(Ops.begin()); 3048 --Idx; 3049 } 3050 3051 if (Ops.size() == 1) 3052 return Ops[0]; 3053 } 3054 3055 // Delay expensive flag strengthening until necessary. 3056 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3057 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3058 }; 3059 3060 // Limit recursion calls depth. 3061 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3062 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3063 3064 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3065 // Don't strengthen flags if we have no new information. 3066 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3067 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3068 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3069 return S; 3070 } 3071 3072 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3073 if (Ops.size() == 2) { 3074 // C1*(C2+V) -> C1*C2 + C1*V 3075 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3076 // If any of Add's ops are Adds or Muls with a constant, apply this 3077 // transformation as well. 3078 // 3079 // TODO: There are some cases where this transformation is not 3080 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3081 // this transformation should be narrowed down. 3082 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3083 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3084 SCEV::FlagAnyWrap, Depth + 1), 3085 getMulExpr(LHSC, Add->getOperand(1), 3086 SCEV::FlagAnyWrap, Depth + 1), 3087 SCEV::FlagAnyWrap, Depth + 1); 3088 3089 if (Ops[0]->isAllOnesValue()) { 3090 // If we have a mul by -1 of an add, try distributing the -1 among the 3091 // add operands. 3092 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3093 SmallVector<const SCEV *, 4> NewOps; 3094 bool AnyFolded = false; 3095 for (const SCEV *AddOp : Add->operands()) { 3096 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3097 Depth + 1); 3098 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3099 NewOps.push_back(Mul); 3100 } 3101 if (AnyFolded) 3102 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3103 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3104 // Negation preserves a recurrence's no self-wrap property. 3105 SmallVector<const SCEV *, 4> Operands; 3106 for (const SCEV *AddRecOp : AddRec->operands()) 3107 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3108 Depth + 1)); 3109 3110 return getAddRecExpr(Operands, AddRec->getLoop(), 3111 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3112 } 3113 } 3114 } 3115 } 3116 3117 // Skip over the add expression until we get to a multiply. 3118 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3119 ++Idx; 3120 3121 // If there are mul operands inline them all into this expression. 3122 if (Idx < Ops.size()) { 3123 bool DeletedMul = false; 3124 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3125 if (Ops.size() > MulOpsInlineThreshold) 3126 break; 3127 // If we have an mul, expand the mul operands onto the end of the 3128 // operands list. 3129 Ops.erase(Ops.begin()+Idx); 3130 Ops.append(Mul->op_begin(), Mul->op_end()); 3131 DeletedMul = true; 3132 } 3133 3134 // If we deleted at least one mul, we added operands to the end of the 3135 // list, and they are not necessarily sorted. Recurse to resort and 3136 // resimplify any operands we just acquired. 3137 if (DeletedMul) 3138 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3139 } 3140 3141 // If there are any add recurrences in the operands list, see if any other 3142 // added values are loop invariant. If so, we can fold them into the 3143 // recurrence. 3144 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3145 ++Idx; 3146 3147 // Scan over all recurrences, trying to fold loop invariants into them. 3148 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3149 // Scan all of the other operands to this mul and add them to the vector 3150 // if they are loop invariant w.r.t. the recurrence. 3151 SmallVector<const SCEV *, 8> LIOps; 3152 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3153 const Loop *AddRecLoop = AddRec->getLoop(); 3154 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3155 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3156 LIOps.push_back(Ops[i]); 3157 Ops.erase(Ops.begin()+i); 3158 --i; --e; 3159 } 3160 3161 // If we found some loop invariants, fold them into the recurrence. 3162 if (!LIOps.empty()) { 3163 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3164 SmallVector<const SCEV *, 4> NewOps; 3165 NewOps.reserve(AddRec->getNumOperands()); 3166 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3167 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3168 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3169 SCEV::FlagAnyWrap, Depth + 1)); 3170 3171 // Build the new addrec. Propagate the NUW and NSW flags if both the 3172 // outer mul and the inner addrec are guaranteed to have no overflow. 3173 // 3174 // No self-wrap cannot be guaranteed after changing the step size, but 3175 // will be inferred if either NUW or NSW is true. 3176 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3177 const SCEV *NewRec = getAddRecExpr( 3178 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3179 3180 // If all of the other operands were loop invariant, we are done. 3181 if (Ops.size() == 1) return NewRec; 3182 3183 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3184 for (unsigned i = 0;; ++i) 3185 if (Ops[i] == AddRec) { 3186 Ops[i] = NewRec; 3187 break; 3188 } 3189 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3190 } 3191 3192 // Okay, if there weren't any loop invariants to be folded, check to see 3193 // if there are multiple AddRec's with the same loop induction variable 3194 // being multiplied together. If so, we can fold them. 3195 3196 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3197 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3198 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3199 // ]]],+,...up to x=2n}. 3200 // Note that the arguments to choose() are always integers with values 3201 // known at compile time, never SCEV objects. 3202 // 3203 // The implementation avoids pointless extra computations when the two 3204 // addrec's are of different length (mathematically, it's equivalent to 3205 // an infinite stream of zeros on the right). 3206 bool OpsModified = false; 3207 for (unsigned OtherIdx = Idx+1; 3208 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3209 ++OtherIdx) { 3210 const SCEVAddRecExpr *OtherAddRec = 3211 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3212 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3213 continue; 3214 3215 // Limit max number of arguments to avoid creation of unreasonably big 3216 // SCEVAddRecs with very complex operands. 3217 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3218 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3219 continue; 3220 3221 bool Overflow = false; 3222 Type *Ty = AddRec->getType(); 3223 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3224 SmallVector<const SCEV*, 7> AddRecOps; 3225 for (int x = 0, xe = AddRec->getNumOperands() + 3226 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3227 SmallVector <const SCEV *, 7> SumOps; 3228 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3229 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3230 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3231 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3232 z < ze && !Overflow; ++z) { 3233 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3234 uint64_t Coeff; 3235 if (LargerThan64Bits) 3236 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3237 else 3238 Coeff = Coeff1*Coeff2; 3239 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3240 const SCEV *Term1 = AddRec->getOperand(y-z); 3241 const SCEV *Term2 = OtherAddRec->getOperand(z); 3242 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3243 SCEV::FlagAnyWrap, Depth + 1)); 3244 } 3245 } 3246 if (SumOps.empty()) 3247 SumOps.push_back(getZero(Ty)); 3248 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3249 } 3250 if (!Overflow) { 3251 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3252 SCEV::FlagAnyWrap); 3253 if (Ops.size() == 2) return NewAddRec; 3254 Ops[Idx] = NewAddRec; 3255 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3256 OpsModified = true; 3257 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3258 if (!AddRec) 3259 break; 3260 } 3261 } 3262 if (OpsModified) 3263 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3264 3265 // Otherwise couldn't fold anything into this recurrence. Move onto the 3266 // next one. 3267 } 3268 3269 // Okay, it looks like we really DO need an mul expr. Check to see if we 3270 // already have one, otherwise create a new one. 3271 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3272 } 3273 3274 /// Represents an unsigned remainder expression based on unsigned division. 3275 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3276 const SCEV *RHS) { 3277 assert(getEffectiveSCEVType(LHS->getType()) == 3278 getEffectiveSCEVType(RHS->getType()) && 3279 "SCEVURemExpr operand types don't match!"); 3280 3281 // Short-circuit easy cases 3282 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3283 // If constant is one, the result is trivial 3284 if (RHSC->getValue()->isOne()) 3285 return getZero(LHS->getType()); // X urem 1 --> 0 3286 3287 // If constant is a power of two, fold into a zext(trunc(LHS)). 3288 if (RHSC->getAPInt().isPowerOf2()) { 3289 Type *FullTy = LHS->getType(); 3290 Type *TruncTy = 3291 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3292 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3293 } 3294 } 3295 3296 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3297 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3298 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3299 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3300 } 3301 3302 /// Get a canonical unsigned division expression, or something simpler if 3303 /// possible. 3304 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3305 const SCEV *RHS) { 3306 assert(!LHS->getType()->isPointerTy() && 3307 "SCEVUDivExpr operand can't be pointer!"); 3308 assert(LHS->getType() == RHS->getType() && 3309 "SCEVUDivExpr operand types don't match!"); 3310 3311 FoldingSetNodeID ID; 3312 ID.AddInteger(scUDivExpr); 3313 ID.AddPointer(LHS); 3314 ID.AddPointer(RHS); 3315 void *IP = nullptr; 3316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3317 return S; 3318 3319 // 0 udiv Y == 0 3320 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3321 if (LHSC->getValue()->isZero()) 3322 return LHS; 3323 3324 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3325 if (RHSC->getValue()->isOne()) 3326 return LHS; // X udiv 1 --> x 3327 // If the denominator is zero, the result of the udiv is undefined. Don't 3328 // try to analyze it, because the resolution chosen here may differ from 3329 // the resolution chosen in other parts of the compiler. 3330 if (!RHSC->getValue()->isZero()) { 3331 // Determine if the division can be folded into the operands of 3332 // its operands. 3333 // TODO: Generalize this to non-constants by using known-bits information. 3334 Type *Ty = LHS->getType(); 3335 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3336 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3337 // For non-power-of-two values, effectively round the value up to the 3338 // nearest power of two. 3339 if (!RHSC->getAPInt().isPowerOf2()) 3340 ++MaxShiftAmt; 3341 IntegerType *ExtTy = 3342 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3343 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3344 if (const SCEVConstant *Step = 3345 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3346 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3347 const APInt &StepInt = Step->getAPInt(); 3348 const APInt &DivInt = RHSC->getAPInt(); 3349 if (!StepInt.urem(DivInt) && 3350 getZeroExtendExpr(AR, ExtTy) == 3351 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3352 getZeroExtendExpr(Step, ExtTy), 3353 AR->getLoop(), SCEV::FlagAnyWrap)) { 3354 SmallVector<const SCEV *, 4> Operands; 3355 for (const SCEV *Op : AR->operands()) 3356 Operands.push_back(getUDivExpr(Op, RHS)); 3357 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3358 } 3359 /// Get a canonical UDivExpr for a recurrence. 3360 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3361 // We can currently only fold X%N if X is constant. 3362 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3363 if (StartC && !DivInt.urem(StepInt) && 3364 getZeroExtendExpr(AR, ExtTy) == 3365 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3366 getZeroExtendExpr(Step, ExtTy), 3367 AR->getLoop(), SCEV::FlagAnyWrap)) { 3368 const APInt &StartInt = StartC->getAPInt(); 3369 const APInt &StartRem = StartInt.urem(StepInt); 3370 if (StartRem != 0) { 3371 const SCEV *NewLHS = 3372 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3373 AR->getLoop(), SCEV::FlagNW); 3374 if (LHS != NewLHS) { 3375 LHS = NewLHS; 3376 3377 // Reset the ID to include the new LHS, and check if it is 3378 // already cached. 3379 ID.clear(); 3380 ID.AddInteger(scUDivExpr); 3381 ID.AddPointer(LHS); 3382 ID.AddPointer(RHS); 3383 IP = nullptr; 3384 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3385 return S; 3386 } 3387 } 3388 } 3389 } 3390 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3391 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3392 SmallVector<const SCEV *, 4> Operands; 3393 for (const SCEV *Op : M->operands()) 3394 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3395 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3396 // Find an operand that's safely divisible. 3397 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3398 const SCEV *Op = M->getOperand(i); 3399 const SCEV *Div = getUDivExpr(Op, RHSC); 3400 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3401 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3402 Operands[i] = Div; 3403 return getMulExpr(Operands); 3404 } 3405 } 3406 } 3407 3408 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3409 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3410 if (auto *DivisorConstant = 3411 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3412 bool Overflow = false; 3413 APInt NewRHS = 3414 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3415 if (Overflow) { 3416 return getConstant(RHSC->getType(), 0, false); 3417 } 3418 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3419 } 3420 } 3421 3422 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3423 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3424 SmallVector<const SCEV *, 4> Operands; 3425 for (const SCEV *Op : A->operands()) 3426 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3427 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3428 Operands.clear(); 3429 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3430 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3431 if (isa<SCEVUDivExpr>(Op) || 3432 getMulExpr(Op, RHS) != A->getOperand(i)) 3433 break; 3434 Operands.push_back(Op); 3435 } 3436 if (Operands.size() == A->getNumOperands()) 3437 return getAddExpr(Operands); 3438 } 3439 } 3440 3441 // Fold if both operands are constant. 3442 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3443 Constant *LHSCV = LHSC->getValue(); 3444 Constant *RHSCV = RHSC->getValue(); 3445 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3446 RHSCV))); 3447 } 3448 } 3449 } 3450 3451 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3452 // changes). Make sure we get a new one. 3453 IP = nullptr; 3454 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3455 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3456 LHS, RHS); 3457 UniqueSCEVs.InsertNode(S, IP); 3458 addToLoopUseLists(S); 3459 registerUser(S, {LHS, RHS}); 3460 return S; 3461 } 3462 3463 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3464 APInt A = C1->getAPInt().abs(); 3465 APInt B = C2->getAPInt().abs(); 3466 uint32_t ABW = A.getBitWidth(); 3467 uint32_t BBW = B.getBitWidth(); 3468 3469 if (ABW > BBW) 3470 B = B.zext(ABW); 3471 else if (ABW < BBW) 3472 A = A.zext(BBW); 3473 3474 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3475 } 3476 3477 /// Get a canonical unsigned division expression, or something simpler if 3478 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3479 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3480 /// it's not exact because the udiv may be clearing bits. 3481 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3482 const SCEV *RHS) { 3483 // TODO: we could try to find factors in all sorts of things, but for now we 3484 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3485 // end of this file for inspiration. 3486 3487 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3488 if (!Mul || !Mul->hasNoUnsignedWrap()) 3489 return getUDivExpr(LHS, RHS); 3490 3491 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3492 // If the mulexpr multiplies by a constant, then that constant must be the 3493 // first element of the mulexpr. 3494 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3495 if (LHSCst == RHSCst) { 3496 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3497 return getMulExpr(Operands); 3498 } 3499 3500 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3501 // that there's a factor provided by one of the other terms. We need to 3502 // check. 3503 APInt Factor = gcd(LHSCst, RHSCst); 3504 if (!Factor.isIntN(1)) { 3505 LHSCst = 3506 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3507 RHSCst = 3508 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3509 SmallVector<const SCEV *, 2> Operands; 3510 Operands.push_back(LHSCst); 3511 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3512 LHS = getMulExpr(Operands); 3513 RHS = RHSCst; 3514 Mul = dyn_cast<SCEVMulExpr>(LHS); 3515 if (!Mul) 3516 return getUDivExactExpr(LHS, RHS); 3517 } 3518 } 3519 } 3520 3521 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3522 if (Mul->getOperand(i) == RHS) { 3523 SmallVector<const SCEV *, 2> Operands; 3524 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3525 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3526 return getMulExpr(Operands); 3527 } 3528 } 3529 3530 return getUDivExpr(LHS, RHS); 3531 } 3532 3533 /// Get an add recurrence expression for the specified loop. Simplify the 3534 /// expression as much as possible. 3535 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3536 const Loop *L, 3537 SCEV::NoWrapFlags Flags) { 3538 SmallVector<const SCEV *, 4> Operands; 3539 Operands.push_back(Start); 3540 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3541 if (StepChrec->getLoop() == L) { 3542 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3543 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3544 } 3545 3546 Operands.push_back(Step); 3547 return getAddRecExpr(Operands, L, Flags); 3548 } 3549 3550 /// Get an add recurrence expression for the specified loop. Simplify the 3551 /// expression as much as possible. 3552 const SCEV * 3553 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3554 const Loop *L, SCEV::NoWrapFlags Flags) { 3555 if (Operands.size() == 1) return Operands[0]; 3556 #ifndef NDEBUG 3557 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3558 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3559 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3560 "SCEVAddRecExpr operand types don't match!"); 3561 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3562 } 3563 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3564 assert(isLoopInvariant(Operands[i], L) && 3565 "SCEVAddRecExpr operand is not loop-invariant!"); 3566 #endif 3567 3568 if (Operands.back()->isZero()) { 3569 Operands.pop_back(); 3570 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3571 } 3572 3573 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3574 // use that information to infer NUW and NSW flags. However, computing a 3575 // BE count requires calling getAddRecExpr, so we may not yet have a 3576 // meaningful BE count at this point (and if we don't, we'd be stuck 3577 // with a SCEVCouldNotCompute as the cached BE count). 3578 3579 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3580 3581 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3582 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3583 const Loop *NestedLoop = NestedAR->getLoop(); 3584 if (L->contains(NestedLoop) 3585 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3586 : (!NestedLoop->contains(L) && 3587 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3588 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3589 Operands[0] = NestedAR->getStart(); 3590 // AddRecs require their operands be loop-invariant with respect to their 3591 // loops. Don't perform this transformation if it would break this 3592 // requirement. 3593 bool AllInvariant = all_of( 3594 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3595 3596 if (AllInvariant) { 3597 // Create a recurrence for the outer loop with the same step size. 3598 // 3599 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3600 // inner recurrence has the same property. 3601 SCEV::NoWrapFlags OuterFlags = 3602 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3603 3604 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3605 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3606 return isLoopInvariant(Op, NestedLoop); 3607 }); 3608 3609 if (AllInvariant) { 3610 // Ok, both add recurrences are valid after the transformation. 3611 // 3612 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3613 // the outer recurrence has the same property. 3614 SCEV::NoWrapFlags InnerFlags = 3615 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3616 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3617 } 3618 } 3619 // Reset Operands to its original state. 3620 Operands[0] = NestedAR; 3621 } 3622 } 3623 3624 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3625 // already have one, otherwise create a new one. 3626 return getOrCreateAddRecExpr(Operands, L, Flags); 3627 } 3628 3629 const SCEV * 3630 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3631 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3632 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3633 // getSCEV(Base)->getType() has the same address space as Base->getType() 3634 // because SCEV::getType() preserves the address space. 3635 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3636 const bool AssumeInBoundsFlags = [&]() { 3637 if (!GEP->isInBounds()) 3638 return false; 3639 3640 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3641 // but to do that, we have to ensure that said flag is valid in the entire 3642 // defined scope of the SCEV. 3643 auto *GEPI = dyn_cast<Instruction>(GEP); 3644 // TODO: non-instructions have global scope. We might be able to prove 3645 // some global scope cases 3646 return GEPI && isSCEVExprNeverPoison(GEPI); 3647 }(); 3648 3649 SCEV::NoWrapFlags OffsetWrap = 3650 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3651 3652 Type *CurTy = GEP->getType(); 3653 bool FirstIter = true; 3654 SmallVector<const SCEV *, 4> Offsets; 3655 for (const SCEV *IndexExpr : IndexExprs) { 3656 // Compute the (potentially symbolic) offset in bytes for this index. 3657 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3658 // For a struct, add the member offset. 3659 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3660 unsigned FieldNo = Index->getZExtValue(); 3661 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3662 Offsets.push_back(FieldOffset); 3663 3664 // Update CurTy to the type of the field at Index. 3665 CurTy = STy->getTypeAtIndex(Index); 3666 } else { 3667 // Update CurTy to its element type. 3668 if (FirstIter) { 3669 assert(isa<PointerType>(CurTy) && 3670 "The first index of a GEP indexes a pointer"); 3671 CurTy = GEP->getSourceElementType(); 3672 FirstIter = false; 3673 } else { 3674 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3675 } 3676 // For an array, add the element offset, explicitly scaled. 3677 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3678 // Getelementptr indices are signed. 3679 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3680 3681 // Multiply the index by the element size to compute the element offset. 3682 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3683 Offsets.push_back(LocalOffset); 3684 } 3685 } 3686 3687 // Handle degenerate case of GEP without offsets. 3688 if (Offsets.empty()) 3689 return BaseExpr; 3690 3691 // Add the offsets together, assuming nsw if inbounds. 3692 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3693 // Add the base address and the offset. We cannot use the nsw flag, as the 3694 // base address is unsigned. However, if we know that the offset is 3695 // non-negative, we can use nuw. 3696 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3697 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3698 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3699 assert(BaseExpr->getType() == GEPExpr->getType() && 3700 "GEP should not change type mid-flight."); 3701 return GEPExpr; 3702 } 3703 3704 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3705 ArrayRef<const SCEV *> Ops) { 3706 FoldingSetNodeID ID; 3707 ID.AddInteger(SCEVType); 3708 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3709 ID.AddPointer(Ops[i]); 3710 void *IP = nullptr; 3711 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3712 } 3713 3714 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3715 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3716 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3717 } 3718 3719 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3720 SmallVectorImpl<const SCEV *> &Ops) { 3721 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3722 if (Ops.size() == 1) return Ops[0]; 3723 #ifndef NDEBUG 3724 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3725 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3726 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3727 "Operand types don't match!"); 3728 assert(Ops[0]->getType()->isPointerTy() == 3729 Ops[i]->getType()->isPointerTy() && 3730 "min/max should be consistently pointerish"); 3731 } 3732 #endif 3733 3734 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3735 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3736 3737 // Sort by complexity, this groups all similar expression types together. 3738 GroupByComplexity(Ops, &LI, DT); 3739 3740 // Check if we have created the same expression before. 3741 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3742 return S; 3743 } 3744 3745 // If there are any constants, fold them together. 3746 unsigned Idx = 0; 3747 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3748 ++Idx; 3749 assert(Idx < Ops.size()); 3750 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3751 if (Kind == scSMaxExpr) 3752 return APIntOps::smax(LHS, RHS); 3753 else if (Kind == scSMinExpr) 3754 return APIntOps::smin(LHS, RHS); 3755 else if (Kind == scUMaxExpr) 3756 return APIntOps::umax(LHS, RHS); 3757 else if (Kind == scUMinExpr) 3758 return APIntOps::umin(LHS, RHS); 3759 llvm_unreachable("Unknown SCEV min/max opcode"); 3760 }; 3761 3762 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3763 // We found two constants, fold them together! 3764 ConstantInt *Fold = ConstantInt::get( 3765 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3766 Ops[0] = getConstant(Fold); 3767 Ops.erase(Ops.begin()+1); // Erase the folded element 3768 if (Ops.size() == 1) return Ops[0]; 3769 LHSC = cast<SCEVConstant>(Ops[0]); 3770 } 3771 3772 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3773 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3774 3775 if (IsMax ? IsMinV : IsMaxV) { 3776 // If we are left with a constant minimum(/maximum)-int, strip it off. 3777 Ops.erase(Ops.begin()); 3778 --Idx; 3779 } else if (IsMax ? IsMaxV : IsMinV) { 3780 // If we have a max(/min) with a constant maximum(/minimum)-int, 3781 // it will always be the extremum. 3782 return LHSC; 3783 } 3784 3785 if (Ops.size() == 1) return Ops[0]; 3786 } 3787 3788 // Find the first operation of the same kind 3789 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3790 ++Idx; 3791 3792 // Check to see if one of the operands is of the same kind. If so, expand its 3793 // operands onto our operand list, and recurse to simplify. 3794 if (Idx < Ops.size()) { 3795 bool DeletedAny = false; 3796 while (Ops[Idx]->getSCEVType() == Kind) { 3797 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3798 Ops.erase(Ops.begin()+Idx); 3799 Ops.append(SMME->op_begin(), SMME->op_end()); 3800 DeletedAny = true; 3801 } 3802 3803 if (DeletedAny) 3804 return getMinMaxExpr(Kind, Ops); 3805 } 3806 3807 // Okay, check to see if the same value occurs in the operand list twice. If 3808 // so, delete one. Since we sorted the list, these values are required to 3809 // be adjacent. 3810 llvm::CmpInst::Predicate GEPred = 3811 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3812 llvm::CmpInst::Predicate LEPred = 3813 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3814 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3815 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3816 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3817 if (Ops[i] == Ops[i + 1] || 3818 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3819 // X op Y op Y --> X op Y 3820 // X op Y --> X, if we know X, Y are ordered appropriately 3821 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3822 --i; 3823 --e; 3824 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3825 Ops[i + 1])) { 3826 // X op Y --> Y, if we know X, Y are ordered appropriately 3827 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3828 --i; 3829 --e; 3830 } 3831 } 3832 3833 if (Ops.size() == 1) return Ops[0]; 3834 3835 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3836 3837 // Okay, it looks like we really DO need an expr. Check to see if we 3838 // already have one, otherwise create a new one. 3839 FoldingSetNodeID ID; 3840 ID.AddInteger(Kind); 3841 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3842 ID.AddPointer(Ops[i]); 3843 void *IP = nullptr; 3844 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3845 if (ExistingSCEV) 3846 return ExistingSCEV; 3847 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3848 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3849 SCEV *S = new (SCEVAllocator) 3850 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3851 3852 UniqueSCEVs.InsertNode(S, IP); 3853 addToLoopUseLists(S); 3854 registerUser(S, Ops); 3855 return S; 3856 } 3857 3858 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3859 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3860 return getSMaxExpr(Ops); 3861 } 3862 3863 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3864 return getMinMaxExpr(scSMaxExpr, Ops); 3865 } 3866 3867 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3868 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3869 return getUMaxExpr(Ops); 3870 } 3871 3872 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3873 return getMinMaxExpr(scUMaxExpr, Ops); 3874 } 3875 3876 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3877 const SCEV *RHS) { 3878 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3879 return getSMinExpr(Ops); 3880 } 3881 3882 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3883 return getMinMaxExpr(scSMinExpr, Ops); 3884 } 3885 3886 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3887 const SCEV *RHS) { 3888 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3889 return getUMinExpr(Ops); 3890 } 3891 3892 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3893 return getMinMaxExpr(scUMinExpr, Ops); 3894 } 3895 3896 const SCEV * 3897 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3898 ScalableVectorType *ScalableTy) { 3899 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3900 Constant *One = ConstantInt::get(IntTy, 1); 3901 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3902 // Note that the expression we created is the final expression, we don't 3903 // want to simplify it any further Also, if we call a normal getSCEV(), 3904 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3905 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3906 } 3907 3908 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3909 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3910 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3911 // We can bypass creating a target-independent constant expression and then 3912 // folding it back into a ConstantInt. This is just a compile-time 3913 // optimization. 3914 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3915 } 3916 3917 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3918 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3919 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3920 // We can bypass creating a target-independent constant expression and then 3921 // folding it back into a ConstantInt. This is just a compile-time 3922 // optimization. 3923 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3924 } 3925 3926 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3927 StructType *STy, 3928 unsigned FieldNo) { 3929 // We can bypass creating a target-independent constant expression and then 3930 // folding it back into a ConstantInt. This is just a compile-time 3931 // optimization. 3932 return getConstant( 3933 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3934 } 3935 3936 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3937 // Don't attempt to do anything other than create a SCEVUnknown object 3938 // here. createSCEV only calls getUnknown after checking for all other 3939 // interesting possibilities, and any other code that calls getUnknown 3940 // is doing so in order to hide a value from SCEV canonicalization. 3941 3942 FoldingSetNodeID ID; 3943 ID.AddInteger(scUnknown); 3944 ID.AddPointer(V); 3945 void *IP = nullptr; 3946 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3947 assert(cast<SCEVUnknown>(S)->getValue() == V && 3948 "Stale SCEVUnknown in uniquing map!"); 3949 return S; 3950 } 3951 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3952 FirstUnknown); 3953 FirstUnknown = cast<SCEVUnknown>(S); 3954 UniqueSCEVs.InsertNode(S, IP); 3955 return S; 3956 } 3957 3958 //===----------------------------------------------------------------------===// 3959 // Basic SCEV Analysis and PHI Idiom Recognition Code 3960 // 3961 3962 /// Test if values of the given type are analyzable within the SCEV 3963 /// framework. This primarily includes integer types, and it can optionally 3964 /// include pointer types if the ScalarEvolution class has access to 3965 /// target-specific information. 3966 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3967 // Integers and pointers are always SCEVable. 3968 return Ty->isIntOrPtrTy(); 3969 } 3970 3971 /// Return the size in bits of the specified type, for which isSCEVable must 3972 /// return true. 3973 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3974 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3975 if (Ty->isPointerTy()) 3976 return getDataLayout().getIndexTypeSizeInBits(Ty); 3977 return getDataLayout().getTypeSizeInBits(Ty); 3978 } 3979 3980 /// Return a type with the same bitwidth as the given type and which represents 3981 /// how SCEV will treat the given type, for which isSCEVable must return 3982 /// true. For pointer types, this is the pointer index sized integer type. 3983 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3984 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3985 3986 if (Ty->isIntegerTy()) 3987 return Ty; 3988 3989 // The only other support type is pointer. 3990 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3991 return getDataLayout().getIndexType(Ty); 3992 } 3993 3994 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3995 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3996 } 3997 3998 const SCEV *ScalarEvolution::getCouldNotCompute() { 3999 return CouldNotCompute.get(); 4000 } 4001 4002 bool ScalarEvolution::checkValidity(const SCEV *S) const { 4003 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 4004 auto *SU = dyn_cast<SCEVUnknown>(S); 4005 return SU && SU->getValue() == nullptr; 4006 }); 4007 4008 return !ContainsNulls; 4009 } 4010 4011 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4012 HasRecMapType::iterator I = HasRecMap.find(S); 4013 if (I != HasRecMap.end()) 4014 return I->second; 4015 4016 bool FoundAddRec = 4017 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4018 HasRecMap.insert({S, FoundAddRec}); 4019 return FoundAddRec; 4020 } 4021 4022 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 4023 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 4024 /// offset I, then return {S', I}, else return {\p S, nullptr}. 4025 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4026 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4027 if (!Add) 4028 return {S, nullptr}; 4029 4030 if (Add->getNumOperands() != 2) 4031 return {S, nullptr}; 4032 4033 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4034 if (!ConstOp) 4035 return {S, nullptr}; 4036 4037 return {Add->getOperand(1), ConstOp->getValue()}; 4038 } 4039 4040 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4041 /// by the value and offset from any ValueOffsetPair in the set. 4042 ScalarEvolution::ValueOffsetPairSetVector * 4043 ScalarEvolution::getSCEVValues(const SCEV *S) { 4044 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4045 if (SI == ExprValueMap.end()) 4046 return nullptr; 4047 #ifndef NDEBUG 4048 if (VerifySCEVMap) { 4049 // Check there is no dangling Value in the set returned. 4050 for (const auto &VE : SI->second) 4051 assert(ValueExprMap.count(VE.first)); 4052 } 4053 #endif 4054 return &SI->second; 4055 } 4056 4057 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4058 /// cannot be used separately. eraseValueFromMap should be used to remove 4059 /// V from ValueExprMap and ExprValueMap at the same time. 4060 void ScalarEvolution::eraseValueFromMap(Value *V) { 4061 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4062 if (I != ValueExprMap.end()) { 4063 const SCEV *S = I->second; 4064 // Remove {V, 0} from the set of ExprValueMap[S] 4065 if (auto *SV = getSCEVValues(S)) 4066 SV->remove({V, nullptr}); 4067 4068 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4069 const SCEV *Stripped; 4070 ConstantInt *Offset; 4071 std::tie(Stripped, Offset) = splitAddExpr(S); 4072 if (Offset != nullptr) { 4073 if (auto *SV = getSCEVValues(Stripped)) 4074 SV->remove({V, Offset}); 4075 } 4076 ValueExprMap.erase(V); 4077 } 4078 } 4079 4080 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4081 /// create a new one. 4082 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4083 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4084 4085 const SCEV *S = getExistingSCEV(V); 4086 if (S == nullptr) { 4087 S = createSCEV(V); 4088 // During PHI resolution, it is possible to create two SCEVs for the same 4089 // V, so it is needed to double check whether V->S is inserted into 4090 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4091 std::pair<ValueExprMapType::iterator, bool> Pair = 4092 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4093 if (Pair.second) { 4094 ExprValueMap[S].insert({V, nullptr}); 4095 4096 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4097 // ExprValueMap. 4098 const SCEV *Stripped = S; 4099 ConstantInt *Offset = nullptr; 4100 std::tie(Stripped, Offset) = splitAddExpr(S); 4101 // If stripped is SCEVUnknown, don't bother to save 4102 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4103 // increase the complexity of the expansion code. 4104 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4105 // because it may generate add/sub instead of GEP in SCEV expansion. 4106 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4107 !isa<GetElementPtrInst>(V)) 4108 ExprValueMap[Stripped].insert({V, Offset}); 4109 } 4110 } 4111 return S; 4112 } 4113 4114 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4115 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4116 4117 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4118 if (I != ValueExprMap.end()) { 4119 const SCEV *S = I->second; 4120 if (checkValidity(S)) 4121 return S; 4122 eraseValueFromMap(V); 4123 forgetMemoizedResults(S); 4124 } 4125 return nullptr; 4126 } 4127 4128 /// Return a SCEV corresponding to -V = -1*V 4129 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4130 SCEV::NoWrapFlags Flags) { 4131 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4132 return getConstant( 4133 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4134 4135 Type *Ty = V->getType(); 4136 Ty = getEffectiveSCEVType(Ty); 4137 return getMulExpr(V, getMinusOne(Ty), Flags); 4138 } 4139 4140 /// If Expr computes ~A, return A else return nullptr 4141 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4142 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4143 if (!Add || Add->getNumOperands() != 2 || 4144 !Add->getOperand(0)->isAllOnesValue()) 4145 return nullptr; 4146 4147 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4148 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4149 !AddRHS->getOperand(0)->isAllOnesValue()) 4150 return nullptr; 4151 4152 return AddRHS->getOperand(1); 4153 } 4154 4155 /// Return a SCEV corresponding to ~V = -1-V 4156 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4157 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4158 4159 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4160 return getConstant( 4161 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4162 4163 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4164 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4165 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4166 SmallVector<const SCEV *, 2> MatchedOperands; 4167 for (const SCEV *Operand : MME->operands()) { 4168 const SCEV *Matched = MatchNotExpr(Operand); 4169 if (!Matched) 4170 return (const SCEV *)nullptr; 4171 MatchedOperands.push_back(Matched); 4172 } 4173 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4174 MatchedOperands); 4175 }; 4176 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4177 return Replaced; 4178 } 4179 4180 Type *Ty = V->getType(); 4181 Ty = getEffectiveSCEVType(Ty); 4182 return getMinusSCEV(getMinusOne(Ty), V); 4183 } 4184 4185 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4186 assert(P->getType()->isPointerTy()); 4187 4188 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4189 // The base of an AddRec is the first operand. 4190 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4191 Ops[0] = removePointerBase(Ops[0]); 4192 // Don't try to transfer nowrap flags for now. We could in some cases 4193 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4194 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4195 } 4196 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4197 // The base of an Add is the pointer operand. 4198 SmallVector<const SCEV *> Ops{Add->operands()}; 4199 const SCEV **PtrOp = nullptr; 4200 for (const SCEV *&AddOp : Ops) { 4201 if (AddOp->getType()->isPointerTy()) { 4202 assert(!PtrOp && "Cannot have multiple pointer ops"); 4203 PtrOp = &AddOp; 4204 } 4205 } 4206 *PtrOp = removePointerBase(*PtrOp); 4207 // Don't try to transfer nowrap flags for now. We could in some cases 4208 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4209 return getAddExpr(Ops); 4210 } 4211 // Any other expression must be a pointer base. 4212 return getZero(P->getType()); 4213 } 4214 4215 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4216 SCEV::NoWrapFlags Flags, 4217 unsigned Depth) { 4218 // Fast path: X - X --> 0. 4219 if (LHS == RHS) 4220 return getZero(LHS->getType()); 4221 4222 // If we subtract two pointers with different pointer bases, bail. 4223 // Eventually, we're going to add an assertion to getMulExpr that we 4224 // can't multiply by a pointer. 4225 if (RHS->getType()->isPointerTy()) { 4226 if (!LHS->getType()->isPointerTy() || 4227 getPointerBase(LHS) != getPointerBase(RHS)) 4228 return getCouldNotCompute(); 4229 LHS = removePointerBase(LHS); 4230 RHS = removePointerBase(RHS); 4231 } 4232 4233 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4234 // makes it so that we cannot make much use of NUW. 4235 auto AddFlags = SCEV::FlagAnyWrap; 4236 const bool RHSIsNotMinSigned = 4237 !getSignedRangeMin(RHS).isMinSignedValue(); 4238 if (hasFlags(Flags, SCEV::FlagNSW)) { 4239 // Let M be the minimum representable signed value. Then (-1)*RHS 4240 // signed-wraps if and only if RHS is M. That can happen even for 4241 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4242 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4243 // (-1)*RHS, we need to prove that RHS != M. 4244 // 4245 // If LHS is non-negative and we know that LHS - RHS does not 4246 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4247 // either by proving that RHS > M or that LHS >= 0. 4248 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4249 AddFlags = SCEV::FlagNSW; 4250 } 4251 } 4252 4253 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4254 // RHS is NSW and LHS >= 0. 4255 // 4256 // The difficulty here is that the NSW flag may have been proven 4257 // relative to a loop that is to be found in a recurrence in LHS and 4258 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4259 // larger scope than intended. 4260 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4261 4262 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4263 } 4264 4265 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4266 unsigned Depth) { 4267 Type *SrcTy = V->getType(); 4268 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4269 "Cannot truncate or zero extend with non-integer arguments!"); 4270 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4271 return V; // No conversion 4272 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4273 return getTruncateExpr(V, Ty, Depth); 4274 return getZeroExtendExpr(V, Ty, Depth); 4275 } 4276 4277 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4278 unsigned Depth) { 4279 Type *SrcTy = V->getType(); 4280 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4281 "Cannot truncate or zero extend with non-integer arguments!"); 4282 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4283 return V; // No conversion 4284 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4285 return getTruncateExpr(V, Ty, Depth); 4286 return getSignExtendExpr(V, Ty, Depth); 4287 } 4288 4289 const SCEV * 4290 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4291 Type *SrcTy = V->getType(); 4292 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4293 "Cannot noop or zero extend with non-integer arguments!"); 4294 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4295 "getNoopOrZeroExtend cannot truncate!"); 4296 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4297 return V; // No conversion 4298 return getZeroExtendExpr(V, Ty); 4299 } 4300 4301 const SCEV * 4302 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4303 Type *SrcTy = V->getType(); 4304 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4305 "Cannot noop or sign extend with non-integer arguments!"); 4306 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4307 "getNoopOrSignExtend cannot truncate!"); 4308 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4309 return V; // No conversion 4310 return getSignExtendExpr(V, Ty); 4311 } 4312 4313 const SCEV * 4314 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4315 Type *SrcTy = V->getType(); 4316 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4317 "Cannot noop or any extend with non-integer arguments!"); 4318 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4319 "getNoopOrAnyExtend cannot truncate!"); 4320 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4321 return V; // No conversion 4322 return getAnyExtendExpr(V, Ty); 4323 } 4324 4325 const SCEV * 4326 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4327 Type *SrcTy = V->getType(); 4328 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4329 "Cannot truncate or noop with non-integer arguments!"); 4330 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4331 "getTruncateOrNoop cannot extend!"); 4332 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4333 return V; // No conversion 4334 return getTruncateExpr(V, Ty); 4335 } 4336 4337 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4338 const SCEV *RHS) { 4339 const SCEV *PromotedLHS = LHS; 4340 const SCEV *PromotedRHS = RHS; 4341 4342 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4343 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4344 else 4345 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4346 4347 return getUMaxExpr(PromotedLHS, PromotedRHS); 4348 } 4349 4350 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4351 const SCEV *RHS) { 4352 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4353 return getUMinFromMismatchedTypes(Ops); 4354 } 4355 4356 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4357 SmallVectorImpl<const SCEV *> &Ops) { 4358 assert(!Ops.empty() && "At least one operand must be!"); 4359 // Trivial case. 4360 if (Ops.size() == 1) 4361 return Ops[0]; 4362 4363 // Find the max type first. 4364 Type *MaxType = nullptr; 4365 for (auto *S : Ops) 4366 if (MaxType) 4367 MaxType = getWiderType(MaxType, S->getType()); 4368 else 4369 MaxType = S->getType(); 4370 assert(MaxType && "Failed to find maximum type!"); 4371 4372 // Extend all ops to max type. 4373 SmallVector<const SCEV *, 2> PromotedOps; 4374 for (auto *S : Ops) 4375 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4376 4377 // Generate umin. 4378 return getUMinExpr(PromotedOps); 4379 } 4380 4381 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4382 // A pointer operand may evaluate to a nonpointer expression, such as null. 4383 if (!V->getType()->isPointerTy()) 4384 return V; 4385 4386 while (true) { 4387 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4388 V = AddRec->getStart(); 4389 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4390 const SCEV *PtrOp = nullptr; 4391 for (const SCEV *AddOp : Add->operands()) { 4392 if (AddOp->getType()->isPointerTy()) { 4393 assert(!PtrOp && "Cannot have multiple pointer ops"); 4394 PtrOp = AddOp; 4395 } 4396 } 4397 assert(PtrOp && "Must have pointer op"); 4398 V = PtrOp; 4399 } else // Not something we can look further into. 4400 return V; 4401 } 4402 } 4403 4404 /// Push users of the given Instruction onto the given Worklist. 4405 static void PushDefUseChildren(Instruction *I, 4406 SmallVectorImpl<Instruction *> &Worklist, 4407 SmallPtrSetImpl<Instruction *> &Visited) { 4408 // Push the def-use children onto the Worklist stack. 4409 for (User *U : I->users()) { 4410 auto *UserInsn = cast<Instruction>(U); 4411 if (Visited.insert(UserInsn).second) 4412 Worklist.push_back(UserInsn); 4413 } 4414 } 4415 4416 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4417 SmallVector<Instruction *, 16> Worklist; 4418 SmallPtrSet<Instruction *, 8> Visited; 4419 SmallVector<const SCEV *, 8> ToForget; 4420 Visited.insert(PN); 4421 Worklist.push_back(PN); 4422 while (!Worklist.empty()) { 4423 Instruction *I = Worklist.pop_back_val(); 4424 4425 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4426 if (It != ValueExprMap.end()) { 4427 const SCEV *Old = It->second; 4428 4429 // Short-circuit the def-use traversal if the symbolic name 4430 // ceases to appear in expressions. 4431 if (Old != SymName && !hasOperand(Old, SymName)) 4432 continue; 4433 4434 // SCEVUnknown for a PHI either means that it has an unrecognized 4435 // structure, it's a PHI that's in the progress of being computed 4436 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4437 // additional loop trip count information isn't going to change anything. 4438 // In the second case, createNodeForPHI will perform the necessary 4439 // updates on its own when it gets to that point. In the third, we do 4440 // want to forget the SCEVUnknown. 4441 if (!isa<PHINode>(I) || 4442 !isa<SCEVUnknown>(Old) || 4443 (I != PN && Old == SymName)) { 4444 eraseValueFromMap(It->first); 4445 ToForget.push_back(Old); 4446 } 4447 } 4448 4449 PushDefUseChildren(I, Worklist, Visited); 4450 } 4451 forgetMemoizedResults(ToForget); 4452 } 4453 4454 namespace { 4455 4456 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4457 /// expression in case its Loop is L. If it is not L then 4458 /// if IgnoreOtherLoops is true then use AddRec itself 4459 /// otherwise rewrite cannot be done. 4460 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4461 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4462 public: 4463 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4464 bool IgnoreOtherLoops = true) { 4465 SCEVInitRewriter Rewriter(L, SE); 4466 const SCEV *Result = Rewriter.visit(S); 4467 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4468 return SE.getCouldNotCompute(); 4469 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4470 ? SE.getCouldNotCompute() 4471 : Result; 4472 } 4473 4474 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4475 if (!SE.isLoopInvariant(Expr, L)) 4476 SeenLoopVariantSCEVUnknown = true; 4477 return Expr; 4478 } 4479 4480 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4481 // Only re-write AddRecExprs for this loop. 4482 if (Expr->getLoop() == L) 4483 return Expr->getStart(); 4484 SeenOtherLoops = true; 4485 return Expr; 4486 } 4487 4488 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4489 4490 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4491 4492 private: 4493 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4494 : SCEVRewriteVisitor(SE), L(L) {} 4495 4496 const Loop *L; 4497 bool SeenLoopVariantSCEVUnknown = false; 4498 bool SeenOtherLoops = false; 4499 }; 4500 4501 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4502 /// increment expression in case its Loop is L. If it is not L then 4503 /// use AddRec itself. 4504 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4505 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4506 public: 4507 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4508 SCEVPostIncRewriter Rewriter(L, SE); 4509 const SCEV *Result = Rewriter.visit(S); 4510 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4511 ? SE.getCouldNotCompute() 4512 : Result; 4513 } 4514 4515 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4516 if (!SE.isLoopInvariant(Expr, L)) 4517 SeenLoopVariantSCEVUnknown = true; 4518 return Expr; 4519 } 4520 4521 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4522 // Only re-write AddRecExprs for this loop. 4523 if (Expr->getLoop() == L) 4524 return Expr->getPostIncExpr(SE); 4525 SeenOtherLoops = true; 4526 return Expr; 4527 } 4528 4529 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4530 4531 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4532 4533 private: 4534 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4535 : SCEVRewriteVisitor(SE), L(L) {} 4536 4537 const Loop *L; 4538 bool SeenLoopVariantSCEVUnknown = false; 4539 bool SeenOtherLoops = false; 4540 }; 4541 4542 /// This class evaluates the compare condition by matching it against the 4543 /// condition of loop latch. If there is a match we assume a true value 4544 /// for the condition while building SCEV nodes. 4545 class SCEVBackedgeConditionFolder 4546 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4547 public: 4548 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4549 ScalarEvolution &SE) { 4550 bool IsPosBECond = false; 4551 Value *BECond = nullptr; 4552 if (BasicBlock *Latch = L->getLoopLatch()) { 4553 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4554 if (BI && BI->isConditional()) { 4555 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4556 "Both outgoing branches should not target same header!"); 4557 BECond = BI->getCondition(); 4558 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4559 } else { 4560 return S; 4561 } 4562 } 4563 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4564 return Rewriter.visit(S); 4565 } 4566 4567 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4568 const SCEV *Result = Expr; 4569 bool InvariantF = SE.isLoopInvariant(Expr, L); 4570 4571 if (!InvariantF) { 4572 Instruction *I = cast<Instruction>(Expr->getValue()); 4573 switch (I->getOpcode()) { 4574 case Instruction::Select: { 4575 SelectInst *SI = cast<SelectInst>(I); 4576 Optional<const SCEV *> Res = 4577 compareWithBackedgeCondition(SI->getCondition()); 4578 if (Res.hasValue()) { 4579 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4580 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4581 } 4582 break; 4583 } 4584 default: { 4585 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4586 if (Res.hasValue()) 4587 Result = Res.getValue(); 4588 break; 4589 } 4590 } 4591 } 4592 return Result; 4593 } 4594 4595 private: 4596 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4597 bool IsPosBECond, ScalarEvolution &SE) 4598 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4599 IsPositiveBECond(IsPosBECond) {} 4600 4601 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4602 4603 const Loop *L; 4604 /// Loop back condition. 4605 Value *BackedgeCond = nullptr; 4606 /// Set to true if loop back is on positive branch condition. 4607 bool IsPositiveBECond; 4608 }; 4609 4610 Optional<const SCEV *> 4611 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4612 4613 // If value matches the backedge condition for loop latch, 4614 // then return a constant evolution node based on loopback 4615 // branch taken. 4616 if (BackedgeCond == IC) 4617 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4618 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4619 return None; 4620 } 4621 4622 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4623 public: 4624 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4625 ScalarEvolution &SE) { 4626 SCEVShiftRewriter Rewriter(L, SE); 4627 const SCEV *Result = Rewriter.visit(S); 4628 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4629 } 4630 4631 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4632 // Only allow AddRecExprs for this loop. 4633 if (!SE.isLoopInvariant(Expr, L)) 4634 Valid = false; 4635 return Expr; 4636 } 4637 4638 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4639 if (Expr->getLoop() == L && Expr->isAffine()) 4640 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4641 Valid = false; 4642 return Expr; 4643 } 4644 4645 bool isValid() { return Valid; } 4646 4647 private: 4648 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4649 : SCEVRewriteVisitor(SE), L(L) {} 4650 4651 const Loop *L; 4652 bool Valid = true; 4653 }; 4654 4655 } // end anonymous namespace 4656 4657 SCEV::NoWrapFlags 4658 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4659 if (!AR->isAffine()) 4660 return SCEV::FlagAnyWrap; 4661 4662 using OBO = OverflowingBinaryOperator; 4663 4664 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4665 4666 if (!AR->hasNoSignedWrap()) { 4667 ConstantRange AddRecRange = getSignedRange(AR); 4668 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4669 4670 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4671 Instruction::Add, IncRange, OBO::NoSignedWrap); 4672 if (NSWRegion.contains(AddRecRange)) 4673 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4674 } 4675 4676 if (!AR->hasNoUnsignedWrap()) { 4677 ConstantRange AddRecRange = getUnsignedRange(AR); 4678 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4679 4680 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4681 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4682 if (NUWRegion.contains(AddRecRange)) 4683 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4684 } 4685 4686 return Result; 4687 } 4688 4689 SCEV::NoWrapFlags 4690 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4691 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4692 4693 if (AR->hasNoSignedWrap()) 4694 return Result; 4695 4696 if (!AR->isAffine()) 4697 return Result; 4698 4699 const SCEV *Step = AR->getStepRecurrence(*this); 4700 const Loop *L = AR->getLoop(); 4701 4702 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4703 // Note that this serves two purposes: It filters out loops that are 4704 // simply not analyzable, and it covers the case where this code is 4705 // being called from within backedge-taken count analysis, such that 4706 // attempting to ask for the backedge-taken count would likely result 4707 // in infinite recursion. In the later case, the analysis code will 4708 // cope with a conservative value, and it will take care to purge 4709 // that value once it has finished. 4710 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4711 4712 // Normally, in the cases we can prove no-overflow via a 4713 // backedge guarding condition, we can also compute a backedge 4714 // taken count for the loop. The exceptions are assumptions and 4715 // guards present in the loop -- SCEV is not great at exploiting 4716 // these to compute max backedge taken counts, but can still use 4717 // these to prove lack of overflow. Use this fact to avoid 4718 // doing extra work that may not pay off. 4719 4720 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4721 AC.assumptions().empty()) 4722 return Result; 4723 4724 // If the backedge is guarded by a comparison with the pre-inc value the 4725 // addrec is safe. Also, if the entry is guarded by a comparison with the 4726 // start value and the backedge is guarded by a comparison with the post-inc 4727 // value, the addrec is safe. 4728 ICmpInst::Predicate Pred; 4729 const SCEV *OverflowLimit = 4730 getSignedOverflowLimitForStep(Step, &Pred, this); 4731 if (OverflowLimit && 4732 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4733 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4734 Result = setFlags(Result, SCEV::FlagNSW); 4735 } 4736 return Result; 4737 } 4738 SCEV::NoWrapFlags 4739 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4740 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4741 4742 if (AR->hasNoUnsignedWrap()) 4743 return Result; 4744 4745 if (!AR->isAffine()) 4746 return Result; 4747 4748 const SCEV *Step = AR->getStepRecurrence(*this); 4749 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4750 const Loop *L = AR->getLoop(); 4751 4752 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4753 // Note that this serves two purposes: It filters out loops that are 4754 // simply not analyzable, and it covers the case where this code is 4755 // being called from within backedge-taken count analysis, such that 4756 // attempting to ask for the backedge-taken count would likely result 4757 // in infinite recursion. In the later case, the analysis code will 4758 // cope with a conservative value, and it will take care to purge 4759 // that value once it has finished. 4760 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4761 4762 // Normally, in the cases we can prove no-overflow via a 4763 // backedge guarding condition, we can also compute a backedge 4764 // taken count for the loop. The exceptions are assumptions and 4765 // guards present in the loop -- SCEV is not great at exploiting 4766 // these to compute max backedge taken counts, but can still use 4767 // these to prove lack of overflow. Use this fact to avoid 4768 // doing extra work that may not pay off. 4769 4770 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4771 AC.assumptions().empty()) 4772 return Result; 4773 4774 // If the backedge is guarded by a comparison with the pre-inc value the 4775 // addrec is safe. Also, if the entry is guarded by a comparison with the 4776 // start value and the backedge is guarded by a comparison with the post-inc 4777 // value, the addrec is safe. 4778 if (isKnownPositive(Step)) { 4779 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4780 getUnsignedRangeMax(Step)); 4781 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4782 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4783 Result = setFlags(Result, SCEV::FlagNUW); 4784 } 4785 } 4786 4787 return Result; 4788 } 4789 4790 namespace { 4791 4792 /// Represents an abstract binary operation. This may exist as a 4793 /// normal instruction or constant expression, or may have been 4794 /// derived from an expression tree. 4795 struct BinaryOp { 4796 unsigned Opcode; 4797 Value *LHS; 4798 Value *RHS; 4799 bool IsNSW = false; 4800 bool IsNUW = false; 4801 4802 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4803 /// constant expression. 4804 Operator *Op = nullptr; 4805 4806 explicit BinaryOp(Operator *Op) 4807 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4808 Op(Op) { 4809 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4810 IsNSW = OBO->hasNoSignedWrap(); 4811 IsNUW = OBO->hasNoUnsignedWrap(); 4812 } 4813 } 4814 4815 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4816 bool IsNUW = false) 4817 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4818 }; 4819 4820 } // end anonymous namespace 4821 4822 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4823 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4824 auto *Op = dyn_cast<Operator>(V); 4825 if (!Op) 4826 return None; 4827 4828 // Implementation detail: all the cleverness here should happen without 4829 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4830 // SCEV expressions when possible, and we should not break that. 4831 4832 switch (Op->getOpcode()) { 4833 case Instruction::Add: 4834 case Instruction::Sub: 4835 case Instruction::Mul: 4836 case Instruction::UDiv: 4837 case Instruction::URem: 4838 case Instruction::And: 4839 case Instruction::Or: 4840 case Instruction::AShr: 4841 case Instruction::Shl: 4842 return BinaryOp(Op); 4843 4844 case Instruction::Xor: 4845 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4846 // If the RHS of the xor is a signmask, then this is just an add. 4847 // Instcombine turns add of signmask into xor as a strength reduction step. 4848 if (RHSC->getValue().isSignMask()) 4849 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4850 return BinaryOp(Op); 4851 4852 case Instruction::LShr: 4853 // Turn logical shift right of a constant into a unsigned divide. 4854 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4855 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4856 4857 // If the shift count is not less than the bitwidth, the result of 4858 // the shift is undefined. Don't try to analyze it, because the 4859 // resolution chosen here may differ from the resolution chosen in 4860 // other parts of the compiler. 4861 if (SA->getValue().ult(BitWidth)) { 4862 Constant *X = 4863 ConstantInt::get(SA->getContext(), 4864 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4865 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4866 } 4867 } 4868 return BinaryOp(Op); 4869 4870 case Instruction::ExtractValue: { 4871 auto *EVI = cast<ExtractValueInst>(Op); 4872 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4873 break; 4874 4875 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4876 if (!WO) 4877 break; 4878 4879 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4880 bool Signed = WO->isSigned(); 4881 // TODO: Should add nuw/nsw flags for mul as well. 4882 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4883 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4884 4885 // Now that we know that all uses of the arithmetic-result component of 4886 // CI are guarded by the overflow check, we can go ahead and pretend 4887 // that the arithmetic is non-overflowing. 4888 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4889 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4890 } 4891 4892 default: 4893 break; 4894 } 4895 4896 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4897 // semantics as a Sub, return a binary sub expression. 4898 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4899 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4900 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4901 4902 return None; 4903 } 4904 4905 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4906 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4907 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4908 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4909 /// follows one of the following patterns: 4910 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4911 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4912 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4913 /// we return the type of the truncation operation, and indicate whether the 4914 /// truncated type should be treated as signed/unsigned by setting 4915 /// \p Signed to true/false, respectively. 4916 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4917 bool &Signed, ScalarEvolution &SE) { 4918 // The case where Op == SymbolicPHI (that is, with no type conversions on 4919 // the way) is handled by the regular add recurrence creating logic and 4920 // would have already been triggered in createAddRecForPHI. Reaching it here 4921 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4922 // because one of the other operands of the SCEVAddExpr updating this PHI is 4923 // not invariant). 4924 // 4925 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4926 // this case predicates that allow us to prove that Op == SymbolicPHI will 4927 // be added. 4928 if (Op == SymbolicPHI) 4929 return nullptr; 4930 4931 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4932 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4933 if (SourceBits != NewBits) 4934 return nullptr; 4935 4936 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4937 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4938 if (!SExt && !ZExt) 4939 return nullptr; 4940 const SCEVTruncateExpr *Trunc = 4941 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4942 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4943 if (!Trunc) 4944 return nullptr; 4945 const SCEV *X = Trunc->getOperand(); 4946 if (X != SymbolicPHI) 4947 return nullptr; 4948 Signed = SExt != nullptr; 4949 return Trunc->getType(); 4950 } 4951 4952 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4953 if (!PN->getType()->isIntegerTy()) 4954 return nullptr; 4955 const Loop *L = LI.getLoopFor(PN->getParent()); 4956 if (!L || L->getHeader() != PN->getParent()) 4957 return nullptr; 4958 return L; 4959 } 4960 4961 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4962 // computation that updates the phi follows the following pattern: 4963 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4964 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4965 // If so, try to see if it can be rewritten as an AddRecExpr under some 4966 // Predicates. If successful, return them as a pair. Also cache the results 4967 // of the analysis. 4968 // 4969 // Example usage scenario: 4970 // Say the Rewriter is called for the following SCEV: 4971 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4972 // where: 4973 // %X = phi i64 (%Start, %BEValue) 4974 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4975 // and call this function with %SymbolicPHI = %X. 4976 // 4977 // The analysis will find that the value coming around the backedge has 4978 // the following SCEV: 4979 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4980 // Upon concluding that this matches the desired pattern, the function 4981 // will return the pair {NewAddRec, SmallPredsVec} where: 4982 // NewAddRec = {%Start,+,%Step} 4983 // SmallPredsVec = {P1, P2, P3} as follows: 4984 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4985 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4986 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4987 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4988 // under the predicates {P1,P2,P3}. 4989 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4990 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4991 // 4992 // TODO's: 4993 // 4994 // 1) Extend the Induction descriptor to also support inductions that involve 4995 // casts: When needed (namely, when we are called in the context of the 4996 // vectorizer induction analysis), a Set of cast instructions will be 4997 // populated by this method, and provided back to isInductionPHI. This is 4998 // needed to allow the vectorizer to properly record them to be ignored by 4999 // the cost model and to avoid vectorizing them (otherwise these casts, 5000 // which are redundant under the runtime overflow checks, will be 5001 // vectorized, which can be costly). 5002 // 5003 // 2) Support additional induction/PHISCEV patterns: We also want to support 5004 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5005 // after the induction update operation (the induction increment): 5006 // 5007 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5008 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5009 // 5010 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5011 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5012 // 5013 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5014 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5015 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5016 SmallVector<const SCEVPredicate *, 3> Predicates; 5017 5018 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5019 // return an AddRec expression under some predicate. 5020 5021 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5022 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5023 assert(L && "Expecting an integer loop header phi"); 5024 5025 // The loop may have multiple entrances or multiple exits; we can analyze 5026 // this phi as an addrec if it has a unique entry value and a unique 5027 // backedge value. 5028 Value *BEValueV = nullptr, *StartValueV = nullptr; 5029 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5030 Value *V = PN->getIncomingValue(i); 5031 if (L->contains(PN->getIncomingBlock(i))) { 5032 if (!BEValueV) { 5033 BEValueV = V; 5034 } else if (BEValueV != V) { 5035 BEValueV = nullptr; 5036 break; 5037 } 5038 } else if (!StartValueV) { 5039 StartValueV = V; 5040 } else if (StartValueV != V) { 5041 StartValueV = nullptr; 5042 break; 5043 } 5044 } 5045 if (!BEValueV || !StartValueV) 5046 return None; 5047 5048 const SCEV *BEValue = getSCEV(BEValueV); 5049 5050 // If the value coming around the backedge is an add with the symbolic 5051 // value we just inserted, possibly with casts that we can ignore under 5052 // an appropriate runtime guard, then we found a simple induction variable! 5053 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5054 if (!Add) 5055 return None; 5056 5057 // If there is a single occurrence of the symbolic value, possibly 5058 // casted, replace it with a recurrence. 5059 unsigned FoundIndex = Add->getNumOperands(); 5060 Type *TruncTy = nullptr; 5061 bool Signed; 5062 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5063 if ((TruncTy = 5064 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5065 if (FoundIndex == e) { 5066 FoundIndex = i; 5067 break; 5068 } 5069 5070 if (FoundIndex == Add->getNumOperands()) 5071 return None; 5072 5073 // Create an add with everything but the specified operand. 5074 SmallVector<const SCEV *, 8> Ops; 5075 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5076 if (i != FoundIndex) 5077 Ops.push_back(Add->getOperand(i)); 5078 const SCEV *Accum = getAddExpr(Ops); 5079 5080 // The runtime checks will not be valid if the step amount is 5081 // varying inside the loop. 5082 if (!isLoopInvariant(Accum, L)) 5083 return None; 5084 5085 // *** Part2: Create the predicates 5086 5087 // Analysis was successful: we have a phi-with-cast pattern for which we 5088 // can return an AddRec expression under the following predicates: 5089 // 5090 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5091 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5092 // P2: An Equal predicate that guarantees that 5093 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5094 // P3: An Equal predicate that guarantees that 5095 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5096 // 5097 // As we next prove, the above predicates guarantee that: 5098 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5099 // 5100 // 5101 // More formally, we want to prove that: 5102 // Expr(i+1) = Start + (i+1) * Accum 5103 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5104 // 5105 // Given that: 5106 // 1) Expr(0) = Start 5107 // 2) Expr(1) = Start + Accum 5108 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5109 // 3) Induction hypothesis (step i): 5110 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5111 // 5112 // Proof: 5113 // Expr(i+1) = 5114 // = Start + (i+1)*Accum 5115 // = (Start + i*Accum) + Accum 5116 // = Expr(i) + Accum 5117 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5118 // :: from step i 5119 // 5120 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5121 // 5122 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5123 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5124 // + Accum :: from P3 5125 // 5126 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5127 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5128 // 5129 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5130 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5131 // 5132 // By induction, the same applies to all iterations 1<=i<n: 5133 // 5134 5135 // Create a truncated addrec for which we will add a no overflow check (P1). 5136 const SCEV *StartVal = getSCEV(StartValueV); 5137 const SCEV *PHISCEV = 5138 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5139 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5140 5141 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5142 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5143 // will be constant. 5144 // 5145 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5146 // add P1. 5147 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5148 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5149 Signed ? SCEVWrapPredicate::IncrementNSSW 5150 : SCEVWrapPredicate::IncrementNUSW; 5151 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5152 Predicates.push_back(AddRecPred); 5153 } 5154 5155 // Create the Equal Predicates P2,P3: 5156 5157 // It is possible that the predicates P2 and/or P3 are computable at 5158 // compile time due to StartVal and/or Accum being constants. 5159 // If either one is, then we can check that now and escape if either P2 5160 // or P3 is false. 5161 5162 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5163 // for each of StartVal and Accum 5164 auto getExtendedExpr = [&](const SCEV *Expr, 5165 bool CreateSignExtend) -> const SCEV * { 5166 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5167 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5168 const SCEV *ExtendedExpr = 5169 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5170 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5171 return ExtendedExpr; 5172 }; 5173 5174 // Given: 5175 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5176 // = getExtendedExpr(Expr) 5177 // Determine whether the predicate P: Expr == ExtendedExpr 5178 // is known to be false at compile time 5179 auto PredIsKnownFalse = [&](const SCEV *Expr, 5180 const SCEV *ExtendedExpr) -> bool { 5181 return Expr != ExtendedExpr && 5182 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5183 }; 5184 5185 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5186 if (PredIsKnownFalse(StartVal, StartExtended)) { 5187 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5188 return None; 5189 } 5190 5191 // The Step is always Signed (because the overflow checks are either 5192 // NSSW or NUSW) 5193 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5194 if (PredIsKnownFalse(Accum, AccumExtended)) { 5195 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5196 return None; 5197 } 5198 5199 auto AppendPredicate = [&](const SCEV *Expr, 5200 const SCEV *ExtendedExpr) -> void { 5201 if (Expr != ExtendedExpr && 5202 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5203 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5204 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5205 Predicates.push_back(Pred); 5206 } 5207 }; 5208 5209 AppendPredicate(StartVal, StartExtended); 5210 AppendPredicate(Accum, AccumExtended); 5211 5212 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5213 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5214 // into NewAR if it will also add the runtime overflow checks specified in 5215 // Predicates. 5216 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5217 5218 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5219 std::make_pair(NewAR, Predicates); 5220 // Remember the result of the analysis for this SCEV at this locayyytion. 5221 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5222 return PredRewrite; 5223 } 5224 5225 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5226 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5227 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5228 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5229 if (!L) 5230 return None; 5231 5232 // Check to see if we already analyzed this PHI. 5233 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5234 if (I != PredicatedSCEVRewrites.end()) { 5235 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5236 I->second; 5237 // Analysis was done before and failed to create an AddRec: 5238 if (Rewrite.first == SymbolicPHI) 5239 return None; 5240 // Analysis was done before and succeeded to create an AddRec under 5241 // a predicate: 5242 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5243 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5244 return Rewrite; 5245 } 5246 5247 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5248 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5249 5250 // Record in the cache that the analysis failed 5251 if (!Rewrite) { 5252 SmallVector<const SCEVPredicate *, 3> Predicates; 5253 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5254 return None; 5255 } 5256 5257 return Rewrite; 5258 } 5259 5260 // FIXME: This utility is currently required because the Rewriter currently 5261 // does not rewrite this expression: 5262 // {0, +, (sext ix (trunc iy to ix) to iy)} 5263 // into {0, +, %step}, 5264 // even when the following Equal predicate exists: 5265 // "%step == (sext ix (trunc iy to ix) to iy)". 5266 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5267 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5268 if (AR1 == AR2) 5269 return true; 5270 5271 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5272 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5273 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5274 return false; 5275 return true; 5276 }; 5277 5278 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5279 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5280 return false; 5281 return true; 5282 } 5283 5284 /// A helper function for createAddRecFromPHI to handle simple cases. 5285 /// 5286 /// This function tries to find an AddRec expression for the simplest (yet most 5287 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5288 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5289 /// technique for finding the AddRec expression. 5290 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5291 Value *BEValueV, 5292 Value *StartValueV) { 5293 const Loop *L = LI.getLoopFor(PN->getParent()); 5294 assert(L && L->getHeader() == PN->getParent()); 5295 assert(BEValueV && StartValueV); 5296 5297 auto BO = MatchBinaryOp(BEValueV, DT); 5298 if (!BO) 5299 return nullptr; 5300 5301 if (BO->Opcode != Instruction::Add) 5302 return nullptr; 5303 5304 const SCEV *Accum = nullptr; 5305 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5306 Accum = getSCEV(BO->RHS); 5307 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5308 Accum = getSCEV(BO->LHS); 5309 5310 if (!Accum) 5311 return nullptr; 5312 5313 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5314 if (BO->IsNUW) 5315 Flags = setFlags(Flags, SCEV::FlagNUW); 5316 if (BO->IsNSW) 5317 Flags = setFlags(Flags, SCEV::FlagNSW); 5318 5319 const SCEV *StartVal = getSCEV(StartValueV); 5320 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5321 5322 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5323 5324 // We can add Flags to the post-inc expression only if we 5325 // know that it is *undefined behavior* for BEValueV to 5326 // overflow. 5327 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5328 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5329 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5330 5331 return PHISCEV; 5332 } 5333 5334 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5335 const Loop *L = LI.getLoopFor(PN->getParent()); 5336 if (!L || L->getHeader() != PN->getParent()) 5337 return nullptr; 5338 5339 // The loop may have multiple entrances or multiple exits; we can analyze 5340 // this phi as an addrec if it has a unique entry value and a unique 5341 // backedge value. 5342 Value *BEValueV = nullptr, *StartValueV = nullptr; 5343 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5344 Value *V = PN->getIncomingValue(i); 5345 if (L->contains(PN->getIncomingBlock(i))) { 5346 if (!BEValueV) { 5347 BEValueV = V; 5348 } else if (BEValueV != V) { 5349 BEValueV = nullptr; 5350 break; 5351 } 5352 } else if (!StartValueV) { 5353 StartValueV = V; 5354 } else if (StartValueV != V) { 5355 StartValueV = nullptr; 5356 break; 5357 } 5358 } 5359 if (!BEValueV || !StartValueV) 5360 return nullptr; 5361 5362 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5363 "PHI node already processed?"); 5364 5365 // First, try to find AddRec expression without creating a fictituos symbolic 5366 // value for PN. 5367 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5368 return S; 5369 5370 // Handle PHI node value symbolically. 5371 const SCEV *SymbolicName = getUnknown(PN); 5372 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5373 5374 // Using this symbolic name for the PHI, analyze the value coming around 5375 // the back-edge. 5376 const SCEV *BEValue = getSCEV(BEValueV); 5377 5378 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5379 // has a special value for the first iteration of the loop. 5380 5381 // If the value coming around the backedge is an add with the symbolic 5382 // value we just inserted, then we found a simple induction variable! 5383 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5384 // If there is a single occurrence of the symbolic value, replace it 5385 // with a recurrence. 5386 unsigned FoundIndex = Add->getNumOperands(); 5387 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5388 if (Add->getOperand(i) == SymbolicName) 5389 if (FoundIndex == e) { 5390 FoundIndex = i; 5391 break; 5392 } 5393 5394 if (FoundIndex != Add->getNumOperands()) { 5395 // Create an add with everything but the specified operand. 5396 SmallVector<const SCEV *, 8> Ops; 5397 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5398 if (i != FoundIndex) 5399 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5400 L, *this)); 5401 const SCEV *Accum = getAddExpr(Ops); 5402 5403 // This is not a valid addrec if the step amount is varying each 5404 // loop iteration, but is not itself an addrec in this loop. 5405 if (isLoopInvariant(Accum, L) || 5406 (isa<SCEVAddRecExpr>(Accum) && 5407 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5408 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5409 5410 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5411 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5412 if (BO->IsNUW) 5413 Flags = setFlags(Flags, SCEV::FlagNUW); 5414 if (BO->IsNSW) 5415 Flags = setFlags(Flags, SCEV::FlagNSW); 5416 } 5417 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5418 // If the increment is an inbounds GEP, then we know the address 5419 // space cannot be wrapped around. We cannot make any guarantee 5420 // about signed or unsigned overflow because pointers are 5421 // unsigned but we may have a negative index from the base 5422 // pointer. We can guarantee that no unsigned wrap occurs if the 5423 // indices form a positive value. 5424 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5425 Flags = setFlags(Flags, SCEV::FlagNW); 5426 5427 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5428 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5429 Flags = setFlags(Flags, SCEV::FlagNUW); 5430 } 5431 5432 // We cannot transfer nuw and nsw flags from subtraction 5433 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5434 // for instance. 5435 } 5436 5437 const SCEV *StartVal = getSCEV(StartValueV); 5438 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5439 5440 // Okay, for the entire analysis of this edge we assumed the PHI 5441 // to be symbolic. We now need to go back and purge all of the 5442 // entries for the scalars that use the symbolic expression. 5443 forgetSymbolicName(PN, SymbolicName); 5444 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5445 5446 // We can add Flags to the post-inc expression only if we 5447 // know that it is *undefined behavior* for BEValueV to 5448 // overflow. 5449 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5450 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5451 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5452 5453 return PHISCEV; 5454 } 5455 } 5456 } else { 5457 // Otherwise, this could be a loop like this: 5458 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5459 // In this case, j = {1,+,1} and BEValue is j. 5460 // Because the other in-value of i (0) fits the evolution of BEValue 5461 // i really is an addrec evolution. 5462 // 5463 // We can generalize this saying that i is the shifted value of BEValue 5464 // by one iteration: 5465 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5466 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5467 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5468 if (Shifted != getCouldNotCompute() && 5469 Start != getCouldNotCompute()) { 5470 const SCEV *StartVal = getSCEV(StartValueV); 5471 if (Start == StartVal) { 5472 // Okay, for the entire analysis of this edge we assumed the PHI 5473 // to be symbolic. We now need to go back and purge all of the 5474 // entries for the scalars that use the symbolic expression. 5475 forgetSymbolicName(PN, SymbolicName); 5476 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5477 return Shifted; 5478 } 5479 } 5480 } 5481 5482 // Remove the temporary PHI node SCEV that has been inserted while intending 5483 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5484 // as it will prevent later (possibly simpler) SCEV expressions to be added 5485 // to the ValueExprMap. 5486 eraseValueFromMap(PN); 5487 5488 return nullptr; 5489 } 5490 5491 // Checks if the SCEV S is available at BB. S is considered available at BB 5492 // if S can be materialized at BB without introducing a fault. 5493 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5494 BasicBlock *BB) { 5495 struct CheckAvailable { 5496 bool TraversalDone = false; 5497 bool Available = true; 5498 5499 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5500 BasicBlock *BB = nullptr; 5501 DominatorTree &DT; 5502 5503 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5504 : L(L), BB(BB), DT(DT) {} 5505 5506 bool setUnavailable() { 5507 TraversalDone = true; 5508 Available = false; 5509 return false; 5510 } 5511 5512 bool follow(const SCEV *S) { 5513 switch (S->getSCEVType()) { 5514 case scConstant: 5515 case scPtrToInt: 5516 case scTruncate: 5517 case scZeroExtend: 5518 case scSignExtend: 5519 case scAddExpr: 5520 case scMulExpr: 5521 case scUMaxExpr: 5522 case scSMaxExpr: 5523 case scUMinExpr: 5524 case scSMinExpr: 5525 // These expressions are available if their operand(s) is/are. 5526 return true; 5527 5528 case scAddRecExpr: { 5529 // We allow add recurrences that are on the loop BB is in, or some 5530 // outer loop. This guarantees availability because the value of the 5531 // add recurrence at BB is simply the "current" value of the induction 5532 // variable. We can relax this in the future; for instance an add 5533 // recurrence on a sibling dominating loop is also available at BB. 5534 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5535 if (L && (ARLoop == L || ARLoop->contains(L))) 5536 return true; 5537 5538 return setUnavailable(); 5539 } 5540 5541 case scUnknown: { 5542 // For SCEVUnknown, we check for simple dominance. 5543 const auto *SU = cast<SCEVUnknown>(S); 5544 Value *V = SU->getValue(); 5545 5546 if (isa<Argument>(V)) 5547 return false; 5548 5549 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5550 return false; 5551 5552 return setUnavailable(); 5553 } 5554 5555 case scUDivExpr: 5556 case scCouldNotCompute: 5557 // We do not try to smart about these at all. 5558 return setUnavailable(); 5559 } 5560 llvm_unreachable("Unknown SCEV kind!"); 5561 } 5562 5563 bool isDone() { return TraversalDone; } 5564 }; 5565 5566 CheckAvailable CA(L, BB, DT); 5567 SCEVTraversal<CheckAvailable> ST(CA); 5568 5569 ST.visitAll(S); 5570 return CA.Available; 5571 } 5572 5573 // Try to match a control flow sequence that branches out at BI and merges back 5574 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5575 // match. 5576 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5577 Value *&C, Value *&LHS, Value *&RHS) { 5578 C = BI->getCondition(); 5579 5580 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5581 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5582 5583 if (!LeftEdge.isSingleEdge()) 5584 return false; 5585 5586 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5587 5588 Use &LeftUse = Merge->getOperandUse(0); 5589 Use &RightUse = Merge->getOperandUse(1); 5590 5591 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5592 LHS = LeftUse; 5593 RHS = RightUse; 5594 return true; 5595 } 5596 5597 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5598 LHS = RightUse; 5599 RHS = LeftUse; 5600 return true; 5601 } 5602 5603 return false; 5604 } 5605 5606 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5607 auto IsReachable = 5608 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5609 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5610 const Loop *L = LI.getLoopFor(PN->getParent()); 5611 5612 // We don't want to break LCSSA, even in a SCEV expression tree. 5613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5614 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5615 return nullptr; 5616 5617 // Try to match 5618 // 5619 // br %cond, label %left, label %right 5620 // left: 5621 // br label %merge 5622 // right: 5623 // br label %merge 5624 // merge: 5625 // V = phi [ %x, %left ], [ %y, %right ] 5626 // 5627 // as "select %cond, %x, %y" 5628 5629 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5630 assert(IDom && "At least the entry block should dominate PN"); 5631 5632 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5633 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5634 5635 if (BI && BI->isConditional() && 5636 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5637 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5638 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5639 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5640 } 5641 5642 return nullptr; 5643 } 5644 5645 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5646 if (const SCEV *S = createAddRecFromPHI(PN)) 5647 return S; 5648 5649 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5650 return S; 5651 5652 // If the PHI has a single incoming value, follow that value, unless the 5653 // PHI's incoming blocks are in a different loop, in which case doing so 5654 // risks breaking LCSSA form. Instcombine would normally zap these, but 5655 // it doesn't have DominatorTree information, so it may miss cases. 5656 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5657 if (LI.replacementPreservesLCSSAForm(PN, V)) 5658 return getSCEV(V); 5659 5660 // If it's not a loop phi, we can't handle it yet. 5661 return getUnknown(PN); 5662 } 5663 5664 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5665 Value *Cond, 5666 Value *TrueVal, 5667 Value *FalseVal) { 5668 // Handle "constant" branch or select. This can occur for instance when a 5669 // loop pass transforms an inner loop and moves on to process the outer loop. 5670 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5671 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5672 5673 // Try to match some simple smax or umax patterns. 5674 auto *ICI = dyn_cast<ICmpInst>(Cond); 5675 if (!ICI) 5676 return getUnknown(I); 5677 5678 Value *LHS = ICI->getOperand(0); 5679 Value *RHS = ICI->getOperand(1); 5680 5681 switch (ICI->getPredicate()) { 5682 case ICmpInst::ICMP_SLT: 5683 case ICmpInst::ICMP_SLE: 5684 case ICmpInst::ICMP_ULT: 5685 case ICmpInst::ICMP_ULE: 5686 std::swap(LHS, RHS); 5687 LLVM_FALLTHROUGH; 5688 case ICmpInst::ICMP_SGT: 5689 case ICmpInst::ICMP_SGE: 5690 case ICmpInst::ICMP_UGT: 5691 case ICmpInst::ICMP_UGE: 5692 // a > b ? a+x : b+x -> max(a, b)+x 5693 // a > b ? b+x : a+x -> min(a, b)+x 5694 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5695 bool Signed = ICI->isSigned(); 5696 const SCEV *LA = getSCEV(TrueVal); 5697 const SCEV *RA = getSCEV(FalseVal); 5698 const SCEV *LS = getSCEV(LHS); 5699 const SCEV *RS = getSCEV(RHS); 5700 if (LA->getType()->isPointerTy()) { 5701 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5702 // Need to make sure we can't produce weird expressions involving 5703 // negated pointers. 5704 if (LA == LS && RA == RS) 5705 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5706 if (LA == RS && RA == LS) 5707 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5708 } 5709 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5710 if (Op->getType()->isPointerTy()) { 5711 Op = getLosslessPtrToIntExpr(Op); 5712 if (isa<SCEVCouldNotCompute>(Op)) 5713 return Op; 5714 } 5715 if (Signed) 5716 Op = getNoopOrSignExtend(Op, I->getType()); 5717 else 5718 Op = getNoopOrZeroExtend(Op, I->getType()); 5719 return Op; 5720 }; 5721 LS = CoerceOperand(LS); 5722 RS = CoerceOperand(RS); 5723 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5724 break; 5725 const SCEV *LDiff = getMinusSCEV(LA, LS); 5726 const SCEV *RDiff = getMinusSCEV(RA, RS); 5727 if (LDiff == RDiff) 5728 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5729 LDiff); 5730 LDiff = getMinusSCEV(LA, RS); 5731 RDiff = getMinusSCEV(RA, LS); 5732 if (LDiff == RDiff) 5733 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5734 LDiff); 5735 } 5736 break; 5737 case ICmpInst::ICMP_NE: 5738 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5739 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5740 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5741 const SCEV *One = getOne(I->getType()); 5742 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5743 const SCEV *LA = getSCEV(TrueVal); 5744 const SCEV *RA = getSCEV(FalseVal); 5745 const SCEV *LDiff = getMinusSCEV(LA, LS); 5746 const SCEV *RDiff = getMinusSCEV(RA, One); 5747 if (LDiff == RDiff) 5748 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5749 } 5750 break; 5751 case ICmpInst::ICMP_EQ: 5752 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5753 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5754 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5755 const SCEV *One = getOne(I->getType()); 5756 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5757 const SCEV *LA = getSCEV(TrueVal); 5758 const SCEV *RA = getSCEV(FalseVal); 5759 const SCEV *LDiff = getMinusSCEV(LA, One); 5760 const SCEV *RDiff = getMinusSCEV(RA, LS); 5761 if (LDiff == RDiff) 5762 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5763 } 5764 break; 5765 default: 5766 break; 5767 } 5768 5769 return getUnknown(I); 5770 } 5771 5772 /// Expand GEP instructions into add and multiply operations. This allows them 5773 /// to be analyzed by regular SCEV code. 5774 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5775 // Don't attempt to analyze GEPs over unsized objects. 5776 if (!GEP->getSourceElementType()->isSized()) 5777 return getUnknown(GEP); 5778 5779 SmallVector<const SCEV *, 4> IndexExprs; 5780 for (Value *Index : GEP->indices()) 5781 IndexExprs.push_back(getSCEV(Index)); 5782 return getGEPExpr(GEP, IndexExprs); 5783 } 5784 5785 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5786 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5787 return C->getAPInt().countTrailingZeros(); 5788 5789 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5790 return GetMinTrailingZeros(I->getOperand()); 5791 5792 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5793 return std::min(GetMinTrailingZeros(T->getOperand()), 5794 (uint32_t)getTypeSizeInBits(T->getType())); 5795 5796 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5797 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5798 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5799 ? getTypeSizeInBits(E->getType()) 5800 : OpRes; 5801 } 5802 5803 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5804 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5805 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5806 ? getTypeSizeInBits(E->getType()) 5807 : OpRes; 5808 } 5809 5810 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5811 // The result is the min of all operands results. 5812 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5813 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5814 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5815 return MinOpRes; 5816 } 5817 5818 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5819 // The result is the sum of all operands results. 5820 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5821 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5822 for (unsigned i = 1, e = M->getNumOperands(); 5823 SumOpRes != BitWidth && i != e; ++i) 5824 SumOpRes = 5825 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5826 return SumOpRes; 5827 } 5828 5829 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5830 // The result is the min of all operands results. 5831 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5832 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5833 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5834 return MinOpRes; 5835 } 5836 5837 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5838 // The result is the min of all operands results. 5839 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5840 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5841 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5842 return MinOpRes; 5843 } 5844 5845 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5846 // The result is the min of all operands results. 5847 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5848 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5849 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5850 return MinOpRes; 5851 } 5852 5853 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5854 // For a SCEVUnknown, ask ValueTracking. 5855 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5856 return Known.countMinTrailingZeros(); 5857 } 5858 5859 // SCEVUDivExpr 5860 return 0; 5861 } 5862 5863 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5864 auto I = MinTrailingZerosCache.find(S); 5865 if (I != MinTrailingZerosCache.end()) 5866 return I->second; 5867 5868 uint32_t Result = GetMinTrailingZerosImpl(S); 5869 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5870 assert(InsertPair.second && "Should insert a new key"); 5871 return InsertPair.first->second; 5872 } 5873 5874 /// Helper method to assign a range to V from metadata present in the IR. 5875 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5876 if (Instruction *I = dyn_cast<Instruction>(V)) 5877 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5878 return getConstantRangeFromMetadata(*MD); 5879 5880 return None; 5881 } 5882 5883 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5884 SCEV::NoWrapFlags Flags) { 5885 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5886 AddRec->setNoWrapFlags(Flags); 5887 UnsignedRanges.erase(AddRec); 5888 SignedRanges.erase(AddRec); 5889 } 5890 } 5891 5892 ConstantRange ScalarEvolution:: 5893 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5894 const DataLayout &DL = getDataLayout(); 5895 5896 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5897 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5898 5899 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5900 // use information about the trip count to improve our available range. Note 5901 // that the trip count independent cases are already handled by known bits. 5902 // WARNING: The definition of recurrence used here is subtly different than 5903 // the one used by AddRec (and thus most of this file). Step is allowed to 5904 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5905 // and other addrecs in the same loop (for non-affine addrecs). The code 5906 // below intentionally handles the case where step is not loop invariant. 5907 auto *P = dyn_cast<PHINode>(U->getValue()); 5908 if (!P) 5909 return FullSet; 5910 5911 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5912 // even the values that are not available in these blocks may come from them, 5913 // and this leads to false-positive recurrence test. 5914 for (auto *Pred : predecessors(P->getParent())) 5915 if (!DT.isReachableFromEntry(Pred)) 5916 return FullSet; 5917 5918 BinaryOperator *BO; 5919 Value *Start, *Step; 5920 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5921 return FullSet; 5922 5923 // If we found a recurrence in reachable code, we must be in a loop. Note 5924 // that BO might be in some subloop of L, and that's completely okay. 5925 auto *L = LI.getLoopFor(P->getParent()); 5926 assert(L && L->getHeader() == P->getParent()); 5927 if (!L->contains(BO->getParent())) 5928 // NOTE: This bailout should be an assert instead. However, asserting 5929 // the condition here exposes a case where LoopFusion is querying SCEV 5930 // with malformed loop information during the midst of the transform. 5931 // There doesn't appear to be an obvious fix, so for the moment bailout 5932 // until the caller issue can be fixed. PR49566 tracks the bug. 5933 return FullSet; 5934 5935 // TODO: Extend to other opcodes such as mul, and div 5936 switch (BO->getOpcode()) { 5937 default: 5938 return FullSet; 5939 case Instruction::AShr: 5940 case Instruction::LShr: 5941 case Instruction::Shl: 5942 break; 5943 }; 5944 5945 if (BO->getOperand(0) != P) 5946 // TODO: Handle the power function forms some day. 5947 return FullSet; 5948 5949 unsigned TC = getSmallConstantMaxTripCount(L); 5950 if (!TC || TC >= BitWidth) 5951 return FullSet; 5952 5953 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5954 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5955 assert(KnownStart.getBitWidth() == BitWidth && 5956 KnownStep.getBitWidth() == BitWidth); 5957 5958 // Compute total shift amount, being careful of overflow and bitwidths. 5959 auto MaxShiftAmt = KnownStep.getMaxValue(); 5960 APInt TCAP(BitWidth, TC-1); 5961 bool Overflow = false; 5962 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5963 if (Overflow) 5964 return FullSet; 5965 5966 switch (BO->getOpcode()) { 5967 default: 5968 llvm_unreachable("filtered out above"); 5969 case Instruction::AShr: { 5970 // For each ashr, three cases: 5971 // shift = 0 => unchanged value 5972 // saturation => 0 or -1 5973 // other => a value closer to zero (of the same sign) 5974 // Thus, the end value is closer to zero than the start. 5975 auto KnownEnd = KnownBits::ashr(KnownStart, 5976 KnownBits::makeConstant(TotalShift)); 5977 if (KnownStart.isNonNegative()) 5978 // Analogous to lshr (simply not yet canonicalized) 5979 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5980 KnownStart.getMaxValue() + 1); 5981 if (KnownStart.isNegative()) 5982 // End >=u Start && End <=s Start 5983 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5984 KnownEnd.getMaxValue() + 1); 5985 break; 5986 } 5987 case Instruction::LShr: { 5988 // For each lshr, three cases: 5989 // shift = 0 => unchanged value 5990 // saturation => 0 5991 // other => a smaller positive number 5992 // Thus, the low end of the unsigned range is the last value produced. 5993 auto KnownEnd = KnownBits::lshr(KnownStart, 5994 KnownBits::makeConstant(TotalShift)); 5995 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5996 KnownStart.getMaxValue() + 1); 5997 } 5998 case Instruction::Shl: { 5999 // Iff no bits are shifted out, value increases on every shift. 6000 auto KnownEnd = KnownBits::shl(KnownStart, 6001 KnownBits::makeConstant(TotalShift)); 6002 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6003 return ConstantRange(KnownStart.getMinValue(), 6004 KnownEnd.getMaxValue() + 1); 6005 break; 6006 } 6007 }; 6008 return FullSet; 6009 } 6010 6011 /// Determine the range for a particular SCEV. If SignHint is 6012 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6013 /// with a "cleaner" unsigned (resp. signed) representation. 6014 const ConstantRange & 6015 ScalarEvolution::getRangeRef(const SCEV *S, 6016 ScalarEvolution::RangeSignHint SignHint) { 6017 DenseMap<const SCEV *, ConstantRange> &Cache = 6018 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6019 : SignedRanges; 6020 ConstantRange::PreferredRangeType RangeType = 6021 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6022 ? ConstantRange::Unsigned : ConstantRange::Signed; 6023 6024 // See if we've computed this range already. 6025 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6026 if (I != Cache.end()) 6027 return I->second; 6028 6029 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6030 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6031 6032 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6033 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6034 using OBO = OverflowingBinaryOperator; 6035 6036 // If the value has known zeros, the maximum value will have those known zeros 6037 // as well. 6038 uint32_t TZ = GetMinTrailingZeros(S); 6039 if (TZ != 0) { 6040 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6041 ConservativeResult = 6042 ConstantRange(APInt::getMinValue(BitWidth), 6043 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6044 else 6045 ConservativeResult = ConstantRange( 6046 APInt::getSignedMinValue(BitWidth), 6047 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6048 } 6049 6050 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6051 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6052 unsigned WrapType = OBO::AnyWrap; 6053 if (Add->hasNoSignedWrap()) 6054 WrapType |= OBO::NoSignedWrap; 6055 if (Add->hasNoUnsignedWrap()) 6056 WrapType |= OBO::NoUnsignedWrap; 6057 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6058 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6059 WrapType, RangeType); 6060 return setRange(Add, SignHint, 6061 ConservativeResult.intersectWith(X, RangeType)); 6062 } 6063 6064 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6065 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6066 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6067 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6068 return setRange(Mul, SignHint, 6069 ConservativeResult.intersectWith(X, RangeType)); 6070 } 6071 6072 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6073 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6074 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6075 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6076 return setRange(SMax, SignHint, 6077 ConservativeResult.intersectWith(X, RangeType)); 6078 } 6079 6080 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6081 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6082 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6083 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6084 return setRange(UMax, SignHint, 6085 ConservativeResult.intersectWith(X, RangeType)); 6086 } 6087 6088 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6089 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6090 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6091 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6092 return setRange(SMin, SignHint, 6093 ConservativeResult.intersectWith(X, RangeType)); 6094 } 6095 6096 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6097 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6098 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6099 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6100 return setRange(UMin, SignHint, 6101 ConservativeResult.intersectWith(X, RangeType)); 6102 } 6103 6104 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6105 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6106 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6107 return setRange(UDiv, SignHint, 6108 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6109 } 6110 6111 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6112 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6113 return setRange(ZExt, SignHint, 6114 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6115 RangeType)); 6116 } 6117 6118 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6119 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6120 return setRange(SExt, SignHint, 6121 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6122 RangeType)); 6123 } 6124 6125 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6126 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6127 return setRange(PtrToInt, SignHint, X); 6128 } 6129 6130 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6131 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6132 return setRange(Trunc, SignHint, 6133 ConservativeResult.intersectWith(X.truncate(BitWidth), 6134 RangeType)); 6135 } 6136 6137 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6138 // If there's no unsigned wrap, the value will never be less than its 6139 // initial value. 6140 if (AddRec->hasNoUnsignedWrap()) { 6141 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6142 if (!UnsignedMinValue.isZero()) 6143 ConservativeResult = ConservativeResult.intersectWith( 6144 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6145 } 6146 6147 // If there's no signed wrap, and all the operands except initial value have 6148 // the same sign or zero, the value won't ever be: 6149 // 1: smaller than initial value if operands are non negative, 6150 // 2: bigger than initial value if operands are non positive. 6151 // For both cases, value can not cross signed min/max boundary. 6152 if (AddRec->hasNoSignedWrap()) { 6153 bool AllNonNeg = true; 6154 bool AllNonPos = true; 6155 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6156 if (!isKnownNonNegative(AddRec->getOperand(i))) 6157 AllNonNeg = false; 6158 if (!isKnownNonPositive(AddRec->getOperand(i))) 6159 AllNonPos = false; 6160 } 6161 if (AllNonNeg) 6162 ConservativeResult = ConservativeResult.intersectWith( 6163 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6164 APInt::getSignedMinValue(BitWidth)), 6165 RangeType); 6166 else if (AllNonPos) 6167 ConservativeResult = ConservativeResult.intersectWith( 6168 ConstantRange::getNonEmpty( 6169 APInt::getSignedMinValue(BitWidth), 6170 getSignedRangeMax(AddRec->getStart()) + 1), 6171 RangeType); 6172 } 6173 6174 // TODO: non-affine addrec 6175 if (AddRec->isAffine()) { 6176 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6177 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6178 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6179 auto RangeFromAffine = getRangeForAffineAR( 6180 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6181 BitWidth); 6182 ConservativeResult = 6183 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6184 6185 auto RangeFromFactoring = getRangeViaFactoring( 6186 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6187 BitWidth); 6188 ConservativeResult = 6189 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6190 } 6191 6192 // Now try symbolic BE count and more powerful methods. 6193 if (UseExpensiveRangeSharpening) { 6194 const SCEV *SymbolicMaxBECount = 6195 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6196 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6197 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6198 AddRec->hasNoSelfWrap()) { 6199 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6200 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6201 ConservativeResult = 6202 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6203 } 6204 } 6205 } 6206 6207 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6208 } 6209 6210 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6211 6212 // Check if the IR explicitly contains !range metadata. 6213 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6214 if (MDRange.hasValue()) 6215 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6216 RangeType); 6217 6218 // Use facts about recurrences in the underlying IR. Note that add 6219 // recurrences are AddRecExprs and thus don't hit this path. This 6220 // primarily handles shift recurrences. 6221 auto CR = getRangeForUnknownRecurrence(U); 6222 ConservativeResult = ConservativeResult.intersectWith(CR); 6223 6224 // See if ValueTracking can give us a useful range. 6225 const DataLayout &DL = getDataLayout(); 6226 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6227 if (Known.getBitWidth() != BitWidth) 6228 Known = Known.zextOrTrunc(BitWidth); 6229 6230 // ValueTracking may be able to compute a tighter result for the number of 6231 // sign bits than for the value of those sign bits. 6232 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6233 if (U->getType()->isPointerTy()) { 6234 // If the pointer size is larger than the index size type, this can cause 6235 // NS to be larger than BitWidth. So compensate for this. 6236 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6237 int ptrIdxDiff = ptrSize - BitWidth; 6238 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6239 NS -= ptrIdxDiff; 6240 } 6241 6242 if (NS > 1) { 6243 // If we know any of the sign bits, we know all of the sign bits. 6244 if (!Known.Zero.getHiBits(NS).isZero()) 6245 Known.Zero.setHighBits(NS); 6246 if (!Known.One.getHiBits(NS).isZero()) 6247 Known.One.setHighBits(NS); 6248 } 6249 6250 if (Known.getMinValue() != Known.getMaxValue() + 1) 6251 ConservativeResult = ConservativeResult.intersectWith( 6252 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6253 RangeType); 6254 if (NS > 1) 6255 ConservativeResult = ConservativeResult.intersectWith( 6256 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6257 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6258 RangeType); 6259 6260 // A range of Phi is a subset of union of all ranges of its input. 6261 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6262 // Make sure that we do not run over cycled Phis. 6263 if (PendingPhiRanges.insert(Phi).second) { 6264 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6265 for (auto &Op : Phi->operands()) { 6266 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6267 RangeFromOps = RangeFromOps.unionWith(OpRange); 6268 // No point to continue if we already have a full set. 6269 if (RangeFromOps.isFullSet()) 6270 break; 6271 } 6272 ConservativeResult = 6273 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6274 bool Erased = PendingPhiRanges.erase(Phi); 6275 assert(Erased && "Failed to erase Phi properly?"); 6276 (void) Erased; 6277 } 6278 } 6279 6280 return setRange(U, SignHint, std::move(ConservativeResult)); 6281 } 6282 6283 return setRange(S, SignHint, std::move(ConservativeResult)); 6284 } 6285 6286 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6287 // values that the expression can take. Initially, the expression has a value 6288 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6289 // argument defines if we treat Step as signed or unsigned. 6290 static ConstantRange getRangeForAffineARHelper(APInt Step, 6291 const ConstantRange &StartRange, 6292 const APInt &MaxBECount, 6293 unsigned BitWidth, bool Signed) { 6294 // If either Step or MaxBECount is 0, then the expression won't change, and we 6295 // just need to return the initial range. 6296 if (Step == 0 || MaxBECount == 0) 6297 return StartRange; 6298 6299 // If we don't know anything about the initial value (i.e. StartRange is 6300 // FullRange), then we don't know anything about the final range either. 6301 // Return FullRange. 6302 if (StartRange.isFullSet()) 6303 return ConstantRange::getFull(BitWidth); 6304 6305 // If Step is signed and negative, then we use its absolute value, but we also 6306 // note that we're moving in the opposite direction. 6307 bool Descending = Signed && Step.isNegative(); 6308 6309 if (Signed) 6310 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6311 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6312 // This equations hold true due to the well-defined wrap-around behavior of 6313 // APInt. 6314 Step = Step.abs(); 6315 6316 // Check if Offset is more than full span of BitWidth. If it is, the 6317 // expression is guaranteed to overflow. 6318 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6319 return ConstantRange::getFull(BitWidth); 6320 6321 // Offset is by how much the expression can change. Checks above guarantee no 6322 // overflow here. 6323 APInt Offset = Step * MaxBECount; 6324 6325 // Minimum value of the final range will match the minimal value of StartRange 6326 // if the expression is increasing and will be decreased by Offset otherwise. 6327 // Maximum value of the final range will match the maximal value of StartRange 6328 // if the expression is decreasing and will be increased by Offset otherwise. 6329 APInt StartLower = StartRange.getLower(); 6330 APInt StartUpper = StartRange.getUpper() - 1; 6331 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6332 : (StartUpper + std::move(Offset)); 6333 6334 // It's possible that the new minimum/maximum value will fall into the initial 6335 // range (due to wrap around). This means that the expression can take any 6336 // value in this bitwidth, and we have to return full range. 6337 if (StartRange.contains(MovedBoundary)) 6338 return ConstantRange::getFull(BitWidth); 6339 6340 APInt NewLower = 6341 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6342 APInt NewUpper = 6343 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6344 NewUpper += 1; 6345 6346 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6347 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6348 } 6349 6350 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6351 const SCEV *Step, 6352 const SCEV *MaxBECount, 6353 unsigned BitWidth) { 6354 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6355 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6356 "Precondition!"); 6357 6358 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6359 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6360 6361 // First, consider step signed. 6362 ConstantRange StartSRange = getSignedRange(Start); 6363 ConstantRange StepSRange = getSignedRange(Step); 6364 6365 // If Step can be both positive and negative, we need to find ranges for the 6366 // maximum absolute step values in both directions and union them. 6367 ConstantRange SR = 6368 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6369 MaxBECountValue, BitWidth, /* Signed = */ true); 6370 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6371 StartSRange, MaxBECountValue, 6372 BitWidth, /* Signed = */ true)); 6373 6374 // Next, consider step unsigned. 6375 ConstantRange UR = getRangeForAffineARHelper( 6376 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6377 MaxBECountValue, BitWidth, /* Signed = */ false); 6378 6379 // Finally, intersect signed and unsigned ranges. 6380 return SR.intersectWith(UR, ConstantRange::Smallest); 6381 } 6382 6383 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6384 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6385 ScalarEvolution::RangeSignHint SignHint) { 6386 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6387 assert(AddRec->hasNoSelfWrap() && 6388 "This only works for non-self-wrapping AddRecs!"); 6389 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6390 const SCEV *Step = AddRec->getStepRecurrence(*this); 6391 // Only deal with constant step to save compile time. 6392 if (!isa<SCEVConstant>(Step)) 6393 return ConstantRange::getFull(BitWidth); 6394 // Let's make sure that we can prove that we do not self-wrap during 6395 // MaxBECount iterations. We need this because MaxBECount is a maximum 6396 // iteration count estimate, and we might infer nw from some exit for which we 6397 // do not know max exit count (or any other side reasoning). 6398 // TODO: Turn into assert at some point. 6399 if (getTypeSizeInBits(MaxBECount->getType()) > 6400 getTypeSizeInBits(AddRec->getType())) 6401 return ConstantRange::getFull(BitWidth); 6402 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6403 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6404 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6405 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6406 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6407 MaxItersWithoutWrap)) 6408 return ConstantRange::getFull(BitWidth); 6409 6410 ICmpInst::Predicate LEPred = 6411 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6412 ICmpInst::Predicate GEPred = 6413 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6414 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6415 6416 // We know that there is no self-wrap. Let's take Start and End values and 6417 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6418 // the iteration. They either lie inside the range [Min(Start, End), 6419 // Max(Start, End)] or outside it: 6420 // 6421 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6422 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6423 // 6424 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6425 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6426 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6427 // Start <= End and step is positive, or Start >= End and step is negative. 6428 const SCEV *Start = AddRec->getStart(); 6429 ConstantRange StartRange = getRangeRef(Start, SignHint); 6430 ConstantRange EndRange = getRangeRef(End, SignHint); 6431 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6432 // If they already cover full iteration space, we will know nothing useful 6433 // even if we prove what we want to prove. 6434 if (RangeBetween.isFullSet()) 6435 return RangeBetween; 6436 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6437 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6438 : RangeBetween.isWrappedSet(); 6439 if (IsWrappedSet) 6440 return ConstantRange::getFull(BitWidth); 6441 6442 if (isKnownPositive(Step) && 6443 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6444 return RangeBetween; 6445 else if (isKnownNegative(Step) && 6446 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6447 return RangeBetween; 6448 return ConstantRange::getFull(BitWidth); 6449 } 6450 6451 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6452 const SCEV *Step, 6453 const SCEV *MaxBECount, 6454 unsigned BitWidth) { 6455 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6456 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6457 6458 struct SelectPattern { 6459 Value *Condition = nullptr; 6460 APInt TrueValue; 6461 APInt FalseValue; 6462 6463 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6464 const SCEV *S) { 6465 Optional<unsigned> CastOp; 6466 APInt Offset(BitWidth, 0); 6467 6468 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6469 "Should be!"); 6470 6471 // Peel off a constant offset: 6472 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6473 // In the future we could consider being smarter here and handle 6474 // {Start+Step,+,Step} too. 6475 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6476 return; 6477 6478 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6479 S = SA->getOperand(1); 6480 } 6481 6482 // Peel off a cast operation 6483 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6484 CastOp = SCast->getSCEVType(); 6485 S = SCast->getOperand(); 6486 } 6487 6488 using namespace llvm::PatternMatch; 6489 6490 auto *SU = dyn_cast<SCEVUnknown>(S); 6491 const APInt *TrueVal, *FalseVal; 6492 if (!SU || 6493 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6494 m_APInt(FalseVal)))) { 6495 Condition = nullptr; 6496 return; 6497 } 6498 6499 TrueValue = *TrueVal; 6500 FalseValue = *FalseVal; 6501 6502 // Re-apply the cast we peeled off earlier 6503 if (CastOp.hasValue()) 6504 switch (*CastOp) { 6505 default: 6506 llvm_unreachable("Unknown SCEV cast type!"); 6507 6508 case scTruncate: 6509 TrueValue = TrueValue.trunc(BitWidth); 6510 FalseValue = FalseValue.trunc(BitWidth); 6511 break; 6512 case scZeroExtend: 6513 TrueValue = TrueValue.zext(BitWidth); 6514 FalseValue = FalseValue.zext(BitWidth); 6515 break; 6516 case scSignExtend: 6517 TrueValue = TrueValue.sext(BitWidth); 6518 FalseValue = FalseValue.sext(BitWidth); 6519 break; 6520 } 6521 6522 // Re-apply the constant offset we peeled off earlier 6523 TrueValue += Offset; 6524 FalseValue += Offset; 6525 } 6526 6527 bool isRecognized() { return Condition != nullptr; } 6528 }; 6529 6530 SelectPattern StartPattern(*this, BitWidth, Start); 6531 if (!StartPattern.isRecognized()) 6532 return ConstantRange::getFull(BitWidth); 6533 6534 SelectPattern StepPattern(*this, BitWidth, Step); 6535 if (!StepPattern.isRecognized()) 6536 return ConstantRange::getFull(BitWidth); 6537 6538 if (StartPattern.Condition != StepPattern.Condition) { 6539 // We don't handle this case today; but we could, by considering four 6540 // possibilities below instead of two. I'm not sure if there are cases where 6541 // that will help over what getRange already does, though. 6542 return ConstantRange::getFull(BitWidth); 6543 } 6544 6545 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6546 // construct arbitrary general SCEV expressions here. This function is called 6547 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6548 // say) can end up caching a suboptimal value. 6549 6550 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6551 // C2352 and C2512 (otherwise it isn't needed). 6552 6553 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6554 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6555 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6556 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6557 6558 ConstantRange TrueRange = 6559 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6560 ConstantRange FalseRange = 6561 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6562 6563 return TrueRange.unionWith(FalseRange); 6564 } 6565 6566 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6567 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6568 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6569 6570 // Return early if there are no flags to propagate to the SCEV. 6571 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6572 if (BinOp->hasNoUnsignedWrap()) 6573 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6574 if (BinOp->hasNoSignedWrap()) 6575 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6576 if (Flags == SCEV::FlagAnyWrap) 6577 return SCEV::FlagAnyWrap; 6578 6579 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6580 } 6581 6582 const Instruction * 6583 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6584 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6585 return &*AddRec->getLoop()->getHeader()->begin(); 6586 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6587 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6588 return I; 6589 return nullptr; 6590 } 6591 6592 const Instruction * 6593 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6594 // Do a bounded search of the def relation of the requested SCEVs. 6595 SmallSet<const SCEV *, 16> Visited; 6596 SmallVector<const SCEV *> Worklist; 6597 auto pushOp = [&](const SCEV *S) { 6598 if (!Visited.insert(S).second) 6599 return; 6600 // Threshold of 30 here is arbitrary. 6601 if (Visited.size() > 30) 6602 return; 6603 Worklist.push_back(S); 6604 }; 6605 6606 for (auto *S : Ops) 6607 pushOp(S); 6608 6609 const Instruction *Bound = nullptr; 6610 while (!Worklist.empty()) { 6611 auto *S = Worklist.pop_back_val(); 6612 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6613 if (!Bound || DT.dominates(Bound, DefI)) 6614 Bound = DefI; 6615 } else if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6616 for (auto *Op : S2->operands()) 6617 pushOp(Op); 6618 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6619 for (auto *Op : S2->operands()) 6620 pushOp(Op); 6621 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6622 for (auto *Op : S2->operands()) 6623 pushOp(Op); 6624 } 6625 return Bound ? Bound : &*F.getEntryBlock().begin(); 6626 } 6627 6628 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6629 const Instruction *B) { 6630 if (A->getParent() == B->getParent() && 6631 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6632 B->getIterator())) 6633 return true; 6634 6635 auto *BLoop = LI.getLoopFor(B->getParent()); 6636 if (BLoop && BLoop->getHeader() == B->getParent() && 6637 BLoop->getLoopPreheader() == A->getParent() && 6638 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6639 A->getParent()->end()) && 6640 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6641 B->getIterator())) 6642 return true; 6643 return false; 6644 } 6645 6646 6647 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6648 // Only proceed if we can prove that I does not yield poison. 6649 if (!programUndefinedIfPoison(I)) 6650 return false; 6651 6652 // At this point we know that if I is executed, then it does not wrap 6653 // according to at least one of NSW or NUW. If I is not executed, then we do 6654 // not know if the calculation that I represents would wrap. Multiple 6655 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6656 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6657 // derived from other instructions that map to the same SCEV. We cannot make 6658 // that guarantee for cases where I is not executed. So we need to find a 6659 // upper bound on the defining scope for the SCEV, and prove that I is 6660 // executed every time we enter that scope. When the bounding scope is a 6661 // loop (the common case), this is equivalent to proving I executes on every 6662 // iteration of that loop. 6663 SmallVector<const SCEV *> SCEVOps; 6664 for (const Use &Op : I->operands()) { 6665 // I could be an extractvalue from a call to an overflow intrinsic. 6666 // TODO: We can do better here in some cases. 6667 if (isSCEVable(Op->getType())) 6668 SCEVOps.push_back(getSCEV(Op)); 6669 } 6670 auto *DefI = getDefiningScopeBound(SCEVOps); 6671 return isGuaranteedToTransferExecutionTo(DefI, I); 6672 } 6673 6674 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6675 // If we know that \c I can never be poison period, then that's enough. 6676 if (isSCEVExprNeverPoison(I)) 6677 return true; 6678 6679 // For an add recurrence specifically, we assume that infinite loops without 6680 // side effects are undefined behavior, and then reason as follows: 6681 // 6682 // If the add recurrence is poison in any iteration, it is poison on all 6683 // future iterations (since incrementing poison yields poison). If the result 6684 // of the add recurrence is fed into the loop latch condition and the loop 6685 // does not contain any throws or exiting blocks other than the latch, we now 6686 // have the ability to "choose" whether the backedge is taken or not (by 6687 // choosing a sufficiently evil value for the poison feeding into the branch) 6688 // for every iteration including and after the one in which \p I first became 6689 // poison. There are two possibilities (let's call the iteration in which \p 6690 // I first became poison as K): 6691 // 6692 // 1. In the set of iterations including and after K, the loop body executes 6693 // no side effects. In this case executing the backege an infinte number 6694 // of times will yield undefined behavior. 6695 // 6696 // 2. In the set of iterations including and after K, the loop body executes 6697 // at least one side effect. In this case, that specific instance of side 6698 // effect is control dependent on poison, which also yields undefined 6699 // behavior. 6700 6701 auto *ExitingBB = L->getExitingBlock(); 6702 auto *LatchBB = L->getLoopLatch(); 6703 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6704 return false; 6705 6706 SmallPtrSet<const Instruction *, 16> Pushed; 6707 SmallVector<const Instruction *, 8> PoisonStack; 6708 6709 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6710 // things that are known to be poison under that assumption go on the 6711 // PoisonStack. 6712 Pushed.insert(I); 6713 PoisonStack.push_back(I); 6714 6715 bool LatchControlDependentOnPoison = false; 6716 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6717 const Instruction *Poison = PoisonStack.pop_back_val(); 6718 6719 for (auto *PoisonUser : Poison->users()) { 6720 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6721 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6722 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6723 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6724 assert(BI->isConditional() && "Only possibility!"); 6725 if (BI->getParent() == LatchBB) { 6726 LatchControlDependentOnPoison = true; 6727 break; 6728 } 6729 } 6730 } 6731 } 6732 6733 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6734 } 6735 6736 ScalarEvolution::LoopProperties 6737 ScalarEvolution::getLoopProperties(const Loop *L) { 6738 using LoopProperties = ScalarEvolution::LoopProperties; 6739 6740 auto Itr = LoopPropertiesCache.find(L); 6741 if (Itr == LoopPropertiesCache.end()) { 6742 auto HasSideEffects = [](Instruction *I) { 6743 if (auto *SI = dyn_cast<StoreInst>(I)) 6744 return !SI->isSimple(); 6745 6746 return I->mayThrow() || I->mayWriteToMemory(); 6747 }; 6748 6749 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6750 /*HasNoSideEffects*/ true}; 6751 6752 for (auto *BB : L->getBlocks()) 6753 for (auto &I : *BB) { 6754 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6755 LP.HasNoAbnormalExits = false; 6756 if (HasSideEffects(&I)) 6757 LP.HasNoSideEffects = false; 6758 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6759 break; // We're already as pessimistic as we can get. 6760 } 6761 6762 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6763 assert(InsertPair.second && "We just checked!"); 6764 Itr = InsertPair.first; 6765 } 6766 6767 return Itr->second; 6768 } 6769 6770 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6771 // A mustprogress loop without side effects must be finite. 6772 // TODO: The check used here is very conservative. It's only *specific* 6773 // side effects which are well defined in infinite loops. 6774 return isMustProgress(L) && loopHasNoSideEffects(L); 6775 } 6776 6777 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6778 if (!isSCEVable(V->getType())) 6779 return getUnknown(V); 6780 6781 if (Instruction *I = dyn_cast<Instruction>(V)) { 6782 // Don't attempt to analyze instructions in blocks that aren't 6783 // reachable. Such instructions don't matter, and they aren't required 6784 // to obey basic rules for definitions dominating uses which this 6785 // analysis depends on. 6786 if (!DT.isReachableFromEntry(I->getParent())) 6787 return getUnknown(UndefValue::get(V->getType())); 6788 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6789 return getConstant(CI); 6790 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6791 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6792 else if (!isa<ConstantExpr>(V)) 6793 return getUnknown(V); 6794 6795 Operator *U = cast<Operator>(V); 6796 if (auto BO = MatchBinaryOp(U, DT)) { 6797 switch (BO->Opcode) { 6798 case Instruction::Add: { 6799 // The simple thing to do would be to just call getSCEV on both operands 6800 // and call getAddExpr with the result. However if we're looking at a 6801 // bunch of things all added together, this can be quite inefficient, 6802 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6803 // Instead, gather up all the operands and make a single getAddExpr call. 6804 // LLVM IR canonical form means we need only traverse the left operands. 6805 SmallVector<const SCEV *, 4> AddOps; 6806 do { 6807 if (BO->Op) { 6808 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6809 AddOps.push_back(OpSCEV); 6810 break; 6811 } 6812 6813 // If a NUW or NSW flag can be applied to the SCEV for this 6814 // addition, then compute the SCEV for this addition by itself 6815 // with a separate call to getAddExpr. We need to do that 6816 // instead of pushing the operands of the addition onto AddOps, 6817 // since the flags are only known to apply to this particular 6818 // addition - they may not apply to other additions that can be 6819 // formed with operands from AddOps. 6820 const SCEV *RHS = getSCEV(BO->RHS); 6821 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6822 if (Flags != SCEV::FlagAnyWrap) { 6823 const SCEV *LHS = getSCEV(BO->LHS); 6824 if (BO->Opcode == Instruction::Sub) 6825 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6826 else 6827 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6828 break; 6829 } 6830 } 6831 6832 if (BO->Opcode == Instruction::Sub) 6833 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6834 else 6835 AddOps.push_back(getSCEV(BO->RHS)); 6836 6837 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6838 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6839 NewBO->Opcode != Instruction::Sub)) { 6840 AddOps.push_back(getSCEV(BO->LHS)); 6841 break; 6842 } 6843 BO = NewBO; 6844 } while (true); 6845 6846 return getAddExpr(AddOps); 6847 } 6848 6849 case Instruction::Mul: { 6850 SmallVector<const SCEV *, 4> MulOps; 6851 do { 6852 if (BO->Op) { 6853 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6854 MulOps.push_back(OpSCEV); 6855 break; 6856 } 6857 6858 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6859 if (Flags != SCEV::FlagAnyWrap) { 6860 MulOps.push_back( 6861 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6862 break; 6863 } 6864 } 6865 6866 MulOps.push_back(getSCEV(BO->RHS)); 6867 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6868 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6869 MulOps.push_back(getSCEV(BO->LHS)); 6870 break; 6871 } 6872 BO = NewBO; 6873 } while (true); 6874 6875 return getMulExpr(MulOps); 6876 } 6877 case Instruction::UDiv: 6878 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6879 case Instruction::URem: 6880 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6881 case Instruction::Sub: { 6882 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6883 if (BO->Op) 6884 Flags = getNoWrapFlagsFromUB(BO->Op); 6885 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6886 } 6887 case Instruction::And: 6888 // For an expression like x&255 that merely masks off the high bits, 6889 // use zext(trunc(x)) as the SCEV expression. 6890 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6891 if (CI->isZero()) 6892 return getSCEV(BO->RHS); 6893 if (CI->isMinusOne()) 6894 return getSCEV(BO->LHS); 6895 const APInt &A = CI->getValue(); 6896 6897 // Instcombine's ShrinkDemandedConstant may strip bits out of 6898 // constants, obscuring what would otherwise be a low-bits mask. 6899 // Use computeKnownBits to compute what ShrinkDemandedConstant 6900 // knew about to reconstruct a low-bits mask value. 6901 unsigned LZ = A.countLeadingZeros(); 6902 unsigned TZ = A.countTrailingZeros(); 6903 unsigned BitWidth = A.getBitWidth(); 6904 KnownBits Known(BitWidth); 6905 computeKnownBits(BO->LHS, Known, getDataLayout(), 6906 0, &AC, nullptr, &DT); 6907 6908 APInt EffectiveMask = 6909 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6910 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6911 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6912 const SCEV *LHS = getSCEV(BO->LHS); 6913 const SCEV *ShiftedLHS = nullptr; 6914 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6915 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6916 // For an expression like (x * 8) & 8, simplify the multiply. 6917 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6918 unsigned GCD = std::min(MulZeros, TZ); 6919 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6920 SmallVector<const SCEV*, 4> MulOps; 6921 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6922 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6923 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6924 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6925 } 6926 } 6927 if (!ShiftedLHS) 6928 ShiftedLHS = getUDivExpr(LHS, MulCount); 6929 return getMulExpr( 6930 getZeroExtendExpr( 6931 getTruncateExpr(ShiftedLHS, 6932 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6933 BO->LHS->getType()), 6934 MulCount); 6935 } 6936 } 6937 break; 6938 6939 case Instruction::Or: 6940 // If the RHS of the Or is a constant, we may have something like: 6941 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6942 // optimizations will transparently handle this case. 6943 // 6944 // In order for this transformation to be safe, the LHS must be of the 6945 // form X*(2^n) and the Or constant must be less than 2^n. 6946 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6947 const SCEV *LHS = getSCEV(BO->LHS); 6948 const APInt &CIVal = CI->getValue(); 6949 if (GetMinTrailingZeros(LHS) >= 6950 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6951 // Build a plain add SCEV. 6952 return getAddExpr(LHS, getSCEV(CI), 6953 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6954 } 6955 } 6956 break; 6957 6958 case Instruction::Xor: 6959 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6960 // If the RHS of xor is -1, then this is a not operation. 6961 if (CI->isMinusOne()) 6962 return getNotSCEV(getSCEV(BO->LHS)); 6963 6964 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6965 // This is a variant of the check for xor with -1, and it handles 6966 // the case where instcombine has trimmed non-demanded bits out 6967 // of an xor with -1. 6968 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6969 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6970 if (LBO->getOpcode() == Instruction::And && 6971 LCI->getValue() == CI->getValue()) 6972 if (const SCEVZeroExtendExpr *Z = 6973 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6974 Type *UTy = BO->LHS->getType(); 6975 const SCEV *Z0 = Z->getOperand(); 6976 Type *Z0Ty = Z0->getType(); 6977 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6978 6979 // If C is a low-bits mask, the zero extend is serving to 6980 // mask off the high bits. Complement the operand and 6981 // re-apply the zext. 6982 if (CI->getValue().isMask(Z0TySize)) 6983 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6984 6985 // If C is a single bit, it may be in the sign-bit position 6986 // before the zero-extend. In this case, represent the xor 6987 // using an add, which is equivalent, and re-apply the zext. 6988 APInt Trunc = CI->getValue().trunc(Z0TySize); 6989 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6990 Trunc.isSignMask()) 6991 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6992 UTy); 6993 } 6994 } 6995 break; 6996 6997 case Instruction::Shl: 6998 // Turn shift left of a constant amount into a multiply. 6999 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7000 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7001 7002 // If the shift count is not less than the bitwidth, the result of 7003 // the shift is undefined. Don't try to analyze it, because the 7004 // resolution chosen here may differ from the resolution chosen in 7005 // other parts of the compiler. 7006 if (SA->getValue().uge(BitWidth)) 7007 break; 7008 7009 // We can safely preserve the nuw flag in all cases. It's also safe to 7010 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7011 // requires special handling. It can be preserved as long as we're not 7012 // left shifting by bitwidth - 1. 7013 auto Flags = SCEV::FlagAnyWrap; 7014 if (BO->Op) { 7015 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7016 if ((MulFlags & SCEV::FlagNSW) && 7017 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7018 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7019 if (MulFlags & SCEV::FlagNUW) 7020 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7021 } 7022 7023 Constant *X = ConstantInt::get( 7024 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7025 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7026 } 7027 break; 7028 7029 case Instruction::AShr: { 7030 // AShr X, C, where C is a constant. 7031 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7032 if (!CI) 7033 break; 7034 7035 Type *OuterTy = BO->LHS->getType(); 7036 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7037 // If the shift count is not less than the bitwidth, the result of 7038 // the shift is undefined. Don't try to analyze it, because the 7039 // resolution chosen here may differ from the resolution chosen in 7040 // other parts of the compiler. 7041 if (CI->getValue().uge(BitWidth)) 7042 break; 7043 7044 if (CI->isZero()) 7045 return getSCEV(BO->LHS); // shift by zero --> noop 7046 7047 uint64_t AShrAmt = CI->getZExtValue(); 7048 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7049 7050 Operator *L = dyn_cast<Operator>(BO->LHS); 7051 if (L && L->getOpcode() == Instruction::Shl) { 7052 // X = Shl A, n 7053 // Y = AShr X, m 7054 // Both n and m are constant. 7055 7056 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7057 if (L->getOperand(1) == BO->RHS) 7058 // For a two-shift sext-inreg, i.e. n = m, 7059 // use sext(trunc(x)) as the SCEV expression. 7060 return getSignExtendExpr( 7061 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7062 7063 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7064 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7065 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7066 if (ShlAmt > AShrAmt) { 7067 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7068 // expression. We already checked that ShlAmt < BitWidth, so 7069 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7070 // ShlAmt - AShrAmt < Amt. 7071 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7072 ShlAmt - AShrAmt); 7073 return getSignExtendExpr( 7074 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7075 getConstant(Mul)), OuterTy); 7076 } 7077 } 7078 } 7079 break; 7080 } 7081 } 7082 } 7083 7084 switch (U->getOpcode()) { 7085 case Instruction::Trunc: 7086 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7087 7088 case Instruction::ZExt: 7089 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7090 7091 case Instruction::SExt: 7092 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7093 // The NSW flag of a subtract does not always survive the conversion to 7094 // A + (-1)*B. By pushing sign extension onto its operands we are much 7095 // more likely to preserve NSW and allow later AddRec optimisations. 7096 // 7097 // NOTE: This is effectively duplicating this logic from getSignExtend: 7098 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7099 // but by that point the NSW information has potentially been lost. 7100 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7101 Type *Ty = U->getType(); 7102 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7103 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7104 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7105 } 7106 } 7107 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7108 7109 case Instruction::BitCast: 7110 // BitCasts are no-op casts so we just eliminate the cast. 7111 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7112 return getSCEV(U->getOperand(0)); 7113 break; 7114 7115 case Instruction::PtrToInt: { 7116 // Pointer to integer cast is straight-forward, so do model it. 7117 const SCEV *Op = getSCEV(U->getOperand(0)); 7118 Type *DstIntTy = U->getType(); 7119 // But only if effective SCEV (integer) type is wide enough to represent 7120 // all possible pointer values. 7121 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7122 if (isa<SCEVCouldNotCompute>(IntOp)) 7123 return getUnknown(V); 7124 return IntOp; 7125 } 7126 case Instruction::IntToPtr: 7127 // Just don't deal with inttoptr casts. 7128 return getUnknown(V); 7129 7130 case Instruction::SDiv: 7131 // If both operands are non-negative, this is just an udiv. 7132 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7133 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7134 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7135 break; 7136 7137 case Instruction::SRem: 7138 // If both operands are non-negative, this is just an urem. 7139 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7140 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7141 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7142 break; 7143 7144 case Instruction::GetElementPtr: 7145 return createNodeForGEP(cast<GEPOperator>(U)); 7146 7147 case Instruction::PHI: 7148 return createNodeForPHI(cast<PHINode>(U)); 7149 7150 case Instruction::Select: 7151 // U can also be a select constant expr, which let fall through. Since 7152 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7153 // constant expressions cannot have instructions as operands, we'd have 7154 // returned getUnknown for a select constant expressions anyway. 7155 if (isa<Instruction>(U)) 7156 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7157 U->getOperand(1), U->getOperand(2)); 7158 break; 7159 7160 case Instruction::Call: 7161 case Instruction::Invoke: 7162 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7163 return getSCEV(RV); 7164 7165 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7166 switch (II->getIntrinsicID()) { 7167 case Intrinsic::abs: 7168 return getAbsExpr( 7169 getSCEV(II->getArgOperand(0)), 7170 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7171 case Intrinsic::umax: 7172 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7173 getSCEV(II->getArgOperand(1))); 7174 case Intrinsic::umin: 7175 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7176 getSCEV(II->getArgOperand(1))); 7177 case Intrinsic::smax: 7178 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7179 getSCEV(II->getArgOperand(1))); 7180 case Intrinsic::smin: 7181 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7182 getSCEV(II->getArgOperand(1))); 7183 case Intrinsic::usub_sat: { 7184 const SCEV *X = getSCEV(II->getArgOperand(0)); 7185 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7186 const SCEV *ClampedY = getUMinExpr(X, Y); 7187 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7188 } 7189 case Intrinsic::uadd_sat: { 7190 const SCEV *X = getSCEV(II->getArgOperand(0)); 7191 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7192 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7193 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7194 } 7195 case Intrinsic::start_loop_iterations: 7196 // A start_loop_iterations is just equivalent to the first operand for 7197 // SCEV purposes. 7198 return getSCEV(II->getArgOperand(0)); 7199 default: 7200 break; 7201 } 7202 } 7203 break; 7204 } 7205 7206 return getUnknown(V); 7207 } 7208 7209 //===----------------------------------------------------------------------===// 7210 // Iteration Count Computation Code 7211 // 7212 7213 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7214 bool Extend) { 7215 if (isa<SCEVCouldNotCompute>(ExitCount)) 7216 return getCouldNotCompute(); 7217 7218 auto *ExitCountType = ExitCount->getType(); 7219 assert(ExitCountType->isIntegerTy()); 7220 7221 if (!Extend) 7222 return getAddExpr(ExitCount, getOne(ExitCountType)); 7223 7224 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7225 1 + ExitCountType->getScalarSizeInBits()); 7226 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7227 getOne(WiderType)); 7228 } 7229 7230 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7231 if (!ExitCount) 7232 return 0; 7233 7234 ConstantInt *ExitConst = ExitCount->getValue(); 7235 7236 // Guard against huge trip counts. 7237 if (ExitConst->getValue().getActiveBits() > 32) 7238 return 0; 7239 7240 // In case of integer overflow, this returns 0, which is correct. 7241 return ((unsigned)ExitConst->getZExtValue()) + 1; 7242 } 7243 7244 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7245 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7246 return getConstantTripCount(ExitCount); 7247 } 7248 7249 unsigned 7250 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7251 const BasicBlock *ExitingBlock) { 7252 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7253 assert(L->isLoopExiting(ExitingBlock) && 7254 "Exiting block must actually branch out of the loop!"); 7255 const SCEVConstant *ExitCount = 7256 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7257 return getConstantTripCount(ExitCount); 7258 } 7259 7260 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7261 const auto *MaxExitCount = 7262 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7263 return getConstantTripCount(MaxExitCount); 7264 } 7265 7266 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7267 SmallVector<BasicBlock *, 8> ExitingBlocks; 7268 L->getExitingBlocks(ExitingBlocks); 7269 7270 Optional<unsigned> Res = None; 7271 for (auto *ExitingBB : ExitingBlocks) { 7272 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7273 if (!Res) 7274 Res = Multiple; 7275 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7276 } 7277 return Res.getValueOr(1); 7278 } 7279 7280 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7281 const SCEV *ExitCount) { 7282 if (ExitCount == getCouldNotCompute()) 7283 return 1; 7284 7285 // Get the trip count 7286 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7287 7288 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7289 if (!TC) 7290 // Attempt to factor more general cases. Returns the greatest power of 7291 // two divisor. If overflow happens, the trip count expression is still 7292 // divisible by the greatest power of 2 divisor returned. 7293 return 1U << std::min((uint32_t)31, 7294 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7295 7296 ConstantInt *Result = TC->getValue(); 7297 7298 // Guard against huge trip counts (this requires checking 7299 // for zero to handle the case where the trip count == -1 and the 7300 // addition wraps). 7301 if (!Result || Result->getValue().getActiveBits() > 32 || 7302 Result->getValue().getActiveBits() == 0) 7303 return 1; 7304 7305 return (unsigned)Result->getZExtValue(); 7306 } 7307 7308 /// Returns the largest constant divisor of the trip count of this loop as a 7309 /// normal unsigned value, if possible. This means that the actual trip count is 7310 /// always a multiple of the returned value (don't forget the trip count could 7311 /// very well be zero as well!). 7312 /// 7313 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7314 /// multiple of a constant (which is also the case if the trip count is simply 7315 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7316 /// if the trip count is very large (>= 2^32). 7317 /// 7318 /// As explained in the comments for getSmallConstantTripCount, this assumes 7319 /// that control exits the loop via ExitingBlock. 7320 unsigned 7321 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7322 const BasicBlock *ExitingBlock) { 7323 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7324 assert(L->isLoopExiting(ExitingBlock) && 7325 "Exiting block must actually branch out of the loop!"); 7326 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7327 return getSmallConstantTripMultiple(L, ExitCount); 7328 } 7329 7330 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7331 const BasicBlock *ExitingBlock, 7332 ExitCountKind Kind) { 7333 switch (Kind) { 7334 case Exact: 7335 case SymbolicMaximum: 7336 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7337 case ConstantMaximum: 7338 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7339 }; 7340 llvm_unreachable("Invalid ExitCountKind!"); 7341 } 7342 7343 const SCEV * 7344 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7345 SCEVUnionPredicate &Preds) { 7346 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7347 } 7348 7349 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7350 ExitCountKind Kind) { 7351 switch (Kind) { 7352 case Exact: 7353 return getBackedgeTakenInfo(L).getExact(L, this); 7354 case ConstantMaximum: 7355 return getBackedgeTakenInfo(L).getConstantMax(this); 7356 case SymbolicMaximum: 7357 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7358 }; 7359 llvm_unreachable("Invalid ExitCountKind!"); 7360 } 7361 7362 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7363 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7364 } 7365 7366 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7367 static void PushLoopPHIs(const Loop *L, 7368 SmallVectorImpl<Instruction *> &Worklist, 7369 SmallPtrSetImpl<Instruction *> &Visited) { 7370 BasicBlock *Header = L->getHeader(); 7371 7372 // Push all Loop-header PHIs onto the Worklist stack. 7373 for (PHINode &PN : Header->phis()) 7374 if (Visited.insert(&PN).second) 7375 Worklist.push_back(&PN); 7376 } 7377 7378 const ScalarEvolution::BackedgeTakenInfo & 7379 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7380 auto &BTI = getBackedgeTakenInfo(L); 7381 if (BTI.hasFullInfo()) 7382 return BTI; 7383 7384 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7385 7386 if (!Pair.second) 7387 return Pair.first->second; 7388 7389 BackedgeTakenInfo Result = 7390 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7391 7392 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7393 } 7394 7395 ScalarEvolution::BackedgeTakenInfo & 7396 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7397 // Initially insert an invalid entry for this loop. If the insertion 7398 // succeeds, proceed to actually compute a backedge-taken count and 7399 // update the value. The temporary CouldNotCompute value tells SCEV 7400 // code elsewhere that it shouldn't attempt to request a new 7401 // backedge-taken count, which could result in infinite recursion. 7402 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7403 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7404 if (!Pair.second) 7405 return Pair.first->second; 7406 7407 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7408 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7409 // must be cleared in this scope. 7410 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7411 7412 // In product build, there are no usage of statistic. 7413 (void)NumTripCountsComputed; 7414 (void)NumTripCountsNotComputed; 7415 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7416 const SCEV *BEExact = Result.getExact(L, this); 7417 if (BEExact != getCouldNotCompute()) { 7418 assert(isLoopInvariant(BEExact, L) && 7419 isLoopInvariant(Result.getConstantMax(this), L) && 7420 "Computed backedge-taken count isn't loop invariant for loop!"); 7421 ++NumTripCountsComputed; 7422 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7423 isa<PHINode>(L->getHeader()->begin())) { 7424 // Only count loops that have phi nodes as not being computable. 7425 ++NumTripCountsNotComputed; 7426 } 7427 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7428 7429 // Now that we know more about the trip count for this loop, forget any 7430 // existing SCEV values for PHI nodes in this loop since they are only 7431 // conservative estimates made without the benefit of trip count 7432 // information. This is similar to the code in forgetLoop, except that 7433 // it handles SCEVUnknown PHI nodes specially. 7434 if (Result.hasAnyInfo()) { 7435 SmallVector<Instruction *, 16> Worklist; 7436 SmallPtrSet<Instruction *, 8> Discovered; 7437 SmallVector<const SCEV *, 8> ToForget; 7438 PushLoopPHIs(L, Worklist, Discovered); 7439 while (!Worklist.empty()) { 7440 Instruction *I = Worklist.pop_back_val(); 7441 7442 ValueExprMapType::iterator It = 7443 ValueExprMap.find_as(static_cast<Value *>(I)); 7444 if (It != ValueExprMap.end()) { 7445 const SCEV *Old = It->second; 7446 7447 // SCEVUnknown for a PHI either means that it has an unrecognized 7448 // structure, or it's a PHI that's in the progress of being computed 7449 // by createNodeForPHI. In the former case, additional loop trip 7450 // count information isn't going to change anything. In the later 7451 // case, createNodeForPHI will perform the necessary updates on its 7452 // own when it gets to that point. 7453 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7454 eraseValueFromMap(It->first); 7455 ToForget.push_back(Old); 7456 } 7457 if (PHINode *PN = dyn_cast<PHINode>(I)) 7458 ConstantEvolutionLoopExitValue.erase(PN); 7459 } 7460 7461 // Since we don't need to invalidate anything for correctness and we're 7462 // only invalidating to make SCEV's results more precise, we get to stop 7463 // early to avoid invalidating too much. This is especially important in 7464 // cases like: 7465 // 7466 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7467 // loop0: 7468 // %pn0 = phi 7469 // ... 7470 // loop1: 7471 // %pn1 = phi 7472 // ... 7473 // 7474 // where both loop0 and loop1's backedge taken count uses the SCEV 7475 // expression for %v. If we don't have the early stop below then in cases 7476 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7477 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7478 // count for loop1, effectively nullifying SCEV's trip count cache. 7479 for (auto *U : I->users()) 7480 if (auto *I = dyn_cast<Instruction>(U)) { 7481 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7482 if (LoopForUser && L->contains(LoopForUser) && 7483 Discovered.insert(I).second) 7484 Worklist.push_back(I); 7485 } 7486 } 7487 forgetMemoizedResults(ToForget); 7488 } 7489 7490 // Re-lookup the insert position, since the call to 7491 // computeBackedgeTakenCount above could result in a 7492 // recusive call to getBackedgeTakenInfo (on a different 7493 // loop), which would invalidate the iterator computed 7494 // earlier. 7495 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7496 } 7497 7498 void ScalarEvolution::forgetAllLoops() { 7499 // This method is intended to forget all info about loops. It should 7500 // invalidate caches as if the following happened: 7501 // - The trip counts of all loops have changed arbitrarily 7502 // - Every llvm::Value has been updated in place to produce a different 7503 // result. 7504 BackedgeTakenCounts.clear(); 7505 PredicatedBackedgeTakenCounts.clear(); 7506 LoopPropertiesCache.clear(); 7507 ConstantEvolutionLoopExitValue.clear(); 7508 ValueExprMap.clear(); 7509 ValuesAtScopes.clear(); 7510 LoopDispositions.clear(); 7511 BlockDispositions.clear(); 7512 UnsignedRanges.clear(); 7513 SignedRanges.clear(); 7514 ExprValueMap.clear(); 7515 HasRecMap.clear(); 7516 MinTrailingZerosCache.clear(); 7517 PredicatedSCEVRewrites.clear(); 7518 } 7519 7520 void ScalarEvolution::forgetLoop(const Loop *L) { 7521 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7522 SmallVector<Instruction *, 32> Worklist; 7523 SmallPtrSet<Instruction *, 16> Visited; 7524 SmallVector<const SCEV *, 16> ToForget; 7525 7526 // Iterate over all the loops and sub-loops to drop SCEV information. 7527 while (!LoopWorklist.empty()) { 7528 auto *CurrL = LoopWorklist.pop_back_val(); 7529 7530 // Drop any stored trip count value. 7531 BackedgeTakenCounts.erase(CurrL); 7532 PredicatedBackedgeTakenCounts.erase(CurrL); 7533 7534 // Drop information about predicated SCEV rewrites for this loop. 7535 for (auto I = PredicatedSCEVRewrites.begin(); 7536 I != PredicatedSCEVRewrites.end();) { 7537 std::pair<const SCEV *, const Loop *> Entry = I->first; 7538 if (Entry.second == CurrL) 7539 PredicatedSCEVRewrites.erase(I++); 7540 else 7541 ++I; 7542 } 7543 7544 auto LoopUsersItr = LoopUsers.find(CurrL); 7545 if (LoopUsersItr != LoopUsers.end()) { 7546 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 7547 LoopUsersItr->second.end()); 7548 LoopUsers.erase(LoopUsersItr); 7549 } 7550 7551 // Drop information about expressions based on loop-header PHIs. 7552 PushLoopPHIs(CurrL, Worklist, Visited); 7553 7554 while (!Worklist.empty()) { 7555 Instruction *I = Worklist.pop_back_val(); 7556 7557 ValueExprMapType::iterator It = 7558 ValueExprMap.find_as(static_cast<Value *>(I)); 7559 if (It != ValueExprMap.end()) { 7560 eraseValueFromMap(It->first); 7561 ToForget.push_back(It->second); 7562 if (PHINode *PN = dyn_cast<PHINode>(I)) 7563 ConstantEvolutionLoopExitValue.erase(PN); 7564 } 7565 7566 PushDefUseChildren(I, Worklist, Visited); 7567 } 7568 7569 LoopPropertiesCache.erase(CurrL); 7570 // Forget all contained loops too, to avoid dangling entries in the 7571 // ValuesAtScopes map. 7572 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7573 } 7574 forgetMemoizedResults(ToForget); 7575 } 7576 7577 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7578 while (Loop *Parent = L->getParentLoop()) 7579 L = Parent; 7580 forgetLoop(L); 7581 } 7582 7583 void ScalarEvolution::forgetValue(Value *V) { 7584 Instruction *I = dyn_cast<Instruction>(V); 7585 if (!I) return; 7586 7587 // Drop information about expressions based on loop-header PHIs. 7588 SmallVector<Instruction *, 16> Worklist; 7589 SmallPtrSet<Instruction *, 8> Visited; 7590 SmallVector<const SCEV *, 8> ToForget; 7591 Worklist.push_back(I); 7592 Visited.insert(I); 7593 7594 while (!Worklist.empty()) { 7595 I = Worklist.pop_back_val(); 7596 ValueExprMapType::iterator It = 7597 ValueExprMap.find_as(static_cast<Value *>(I)); 7598 if (It != ValueExprMap.end()) { 7599 eraseValueFromMap(It->first); 7600 ToForget.push_back(It->second); 7601 if (PHINode *PN = dyn_cast<PHINode>(I)) 7602 ConstantEvolutionLoopExitValue.erase(PN); 7603 } 7604 7605 PushDefUseChildren(I, Worklist, Visited); 7606 } 7607 forgetMemoizedResults(ToForget); 7608 } 7609 7610 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7611 LoopDispositions.clear(); 7612 } 7613 7614 /// Get the exact loop backedge taken count considering all loop exits. A 7615 /// computable result can only be returned for loops with all exiting blocks 7616 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7617 /// is never skipped. This is a valid assumption as long as the loop exits via 7618 /// that test. For precise results, it is the caller's responsibility to specify 7619 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7620 const SCEV * 7621 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7622 SCEVUnionPredicate *Preds) const { 7623 // If any exits were not computable, the loop is not computable. 7624 if (!isComplete() || ExitNotTaken.empty()) 7625 return SE->getCouldNotCompute(); 7626 7627 const BasicBlock *Latch = L->getLoopLatch(); 7628 // All exiting blocks we have collected must dominate the only backedge. 7629 if (!Latch) 7630 return SE->getCouldNotCompute(); 7631 7632 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7633 // count is simply a minimum out of all these calculated exit counts. 7634 SmallVector<const SCEV *, 2> Ops; 7635 for (auto &ENT : ExitNotTaken) { 7636 const SCEV *BECount = ENT.ExactNotTaken; 7637 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7638 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7639 "We should only have known counts for exiting blocks that dominate " 7640 "latch!"); 7641 7642 Ops.push_back(BECount); 7643 7644 if (Preds && !ENT.hasAlwaysTruePredicate()) 7645 Preds->add(ENT.Predicate.get()); 7646 7647 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7648 "Predicate should be always true!"); 7649 } 7650 7651 return SE->getUMinFromMismatchedTypes(Ops); 7652 } 7653 7654 /// Get the exact not taken count for this loop exit. 7655 const SCEV * 7656 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7657 ScalarEvolution *SE) const { 7658 for (auto &ENT : ExitNotTaken) 7659 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7660 return ENT.ExactNotTaken; 7661 7662 return SE->getCouldNotCompute(); 7663 } 7664 7665 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7666 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7667 for (auto &ENT : ExitNotTaken) 7668 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7669 return ENT.MaxNotTaken; 7670 7671 return SE->getCouldNotCompute(); 7672 } 7673 7674 /// getConstantMax - Get the constant max backedge taken count for the loop. 7675 const SCEV * 7676 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7677 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7678 return !ENT.hasAlwaysTruePredicate(); 7679 }; 7680 7681 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 7682 return SE->getCouldNotCompute(); 7683 7684 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7685 isa<SCEVConstant>(getConstantMax())) && 7686 "No point in having a non-constant max backedge taken count!"); 7687 return getConstantMax(); 7688 } 7689 7690 const SCEV * 7691 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7692 ScalarEvolution *SE) { 7693 if (!SymbolicMax) 7694 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7695 return SymbolicMax; 7696 } 7697 7698 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7699 ScalarEvolution *SE) const { 7700 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7701 return !ENT.hasAlwaysTruePredicate(); 7702 }; 7703 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7704 } 7705 7706 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7707 return Operands.contains(S); 7708 } 7709 7710 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7711 : ExitLimit(E, E, false, None) { 7712 } 7713 7714 ScalarEvolution::ExitLimit::ExitLimit( 7715 const SCEV *E, const SCEV *M, bool MaxOrZero, 7716 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7717 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7718 // If we prove the max count is zero, so is the symbolic bound. This happens 7719 // in practice due to differences in a) how context sensitive we've chosen 7720 // to be and b) how we reason about bounds impied by UB. 7721 if (MaxNotTaken->isZero()) 7722 ExactNotTaken = MaxNotTaken; 7723 7724 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7725 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7726 "Exact is not allowed to be less precise than Max"); 7727 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7728 isa<SCEVConstant>(MaxNotTaken)) && 7729 "No point in having a non-constant max backedge taken count!"); 7730 for (auto *PredSet : PredSetList) 7731 for (auto *P : *PredSet) 7732 addPredicate(P); 7733 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7734 "Backedge count should be int"); 7735 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7736 "Max backedge count should be int"); 7737 } 7738 7739 ScalarEvolution::ExitLimit::ExitLimit( 7740 const SCEV *E, const SCEV *M, bool MaxOrZero, 7741 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7742 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7743 } 7744 7745 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7746 bool MaxOrZero) 7747 : ExitLimit(E, M, MaxOrZero, None) { 7748 } 7749 7750 class SCEVRecordOperands { 7751 SmallPtrSetImpl<const SCEV *> &Operands; 7752 7753 public: 7754 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7755 : Operands(Operands) {} 7756 bool follow(const SCEV *S) { 7757 Operands.insert(S); 7758 return true; 7759 } 7760 bool isDone() { return false; } 7761 }; 7762 7763 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7764 /// computable exit into a persistent ExitNotTakenInfo array. 7765 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7766 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7767 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7768 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7769 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7770 7771 ExitNotTaken.reserve(ExitCounts.size()); 7772 std::transform( 7773 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7774 [&](const EdgeExitInfo &EEI) { 7775 BasicBlock *ExitBB = EEI.first; 7776 const ExitLimit &EL = EEI.second; 7777 if (EL.Predicates.empty()) 7778 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7779 nullptr); 7780 7781 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7782 for (auto *Pred : EL.Predicates) 7783 Predicate->add(Pred); 7784 7785 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7786 std::move(Predicate)); 7787 }); 7788 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7789 isa<SCEVConstant>(ConstantMax)) && 7790 "No point in having a non-constant max backedge taken count!"); 7791 7792 SCEVRecordOperands RecordOperands(Operands); 7793 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7794 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7795 ST.visitAll(ConstantMax); 7796 for (auto &ENT : ExitNotTaken) 7797 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7798 ST.visitAll(ENT.ExactNotTaken); 7799 } 7800 7801 /// Compute the number of times the backedge of the specified loop will execute. 7802 ScalarEvolution::BackedgeTakenInfo 7803 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7804 bool AllowPredicates) { 7805 SmallVector<BasicBlock *, 8> ExitingBlocks; 7806 L->getExitingBlocks(ExitingBlocks); 7807 7808 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7809 7810 SmallVector<EdgeExitInfo, 4> ExitCounts; 7811 bool CouldComputeBECount = true; 7812 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7813 const SCEV *MustExitMaxBECount = nullptr; 7814 const SCEV *MayExitMaxBECount = nullptr; 7815 bool MustExitMaxOrZero = false; 7816 7817 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7818 // and compute maxBECount. 7819 // Do a union of all the predicates here. 7820 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7821 BasicBlock *ExitBB = ExitingBlocks[i]; 7822 7823 // We canonicalize untaken exits to br (constant), ignore them so that 7824 // proving an exit untaken doesn't negatively impact our ability to reason 7825 // about the loop as whole. 7826 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7827 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7828 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7829 if (ExitIfTrue == CI->isZero()) 7830 continue; 7831 } 7832 7833 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7834 7835 assert((AllowPredicates || EL.Predicates.empty()) && 7836 "Predicated exit limit when predicates are not allowed!"); 7837 7838 // 1. For each exit that can be computed, add an entry to ExitCounts. 7839 // CouldComputeBECount is true only if all exits can be computed. 7840 if (EL.ExactNotTaken == getCouldNotCompute()) 7841 // We couldn't compute an exact value for this exit, so 7842 // we won't be able to compute an exact value for the loop. 7843 CouldComputeBECount = false; 7844 else 7845 ExitCounts.emplace_back(ExitBB, EL); 7846 7847 // 2. Derive the loop's MaxBECount from each exit's max number of 7848 // non-exiting iterations. Partition the loop exits into two kinds: 7849 // LoopMustExits and LoopMayExits. 7850 // 7851 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7852 // is a LoopMayExit. If any computable LoopMustExit is found, then 7853 // MaxBECount is the minimum EL.MaxNotTaken of computable 7854 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7855 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7856 // computable EL.MaxNotTaken. 7857 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7858 DT.dominates(ExitBB, Latch)) { 7859 if (!MustExitMaxBECount) { 7860 MustExitMaxBECount = EL.MaxNotTaken; 7861 MustExitMaxOrZero = EL.MaxOrZero; 7862 } else { 7863 MustExitMaxBECount = 7864 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7865 } 7866 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7867 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7868 MayExitMaxBECount = EL.MaxNotTaken; 7869 else { 7870 MayExitMaxBECount = 7871 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7872 } 7873 } 7874 } 7875 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7876 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7877 // The loop backedge will be taken the maximum or zero times if there's 7878 // a single exit that must be taken the maximum or zero times. 7879 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7880 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7881 MaxBECount, MaxOrZero); 7882 } 7883 7884 ScalarEvolution::ExitLimit 7885 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7886 bool AllowPredicates) { 7887 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7888 // If our exiting block does not dominate the latch, then its connection with 7889 // loop's exit limit may be far from trivial. 7890 const BasicBlock *Latch = L->getLoopLatch(); 7891 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7892 return getCouldNotCompute(); 7893 7894 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7895 Instruction *Term = ExitingBlock->getTerminator(); 7896 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7897 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7898 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7899 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7900 "It should have one successor in loop and one exit block!"); 7901 // Proceed to the next level to examine the exit condition expression. 7902 return computeExitLimitFromCond( 7903 L, BI->getCondition(), ExitIfTrue, 7904 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7905 } 7906 7907 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7908 // For switch, make sure that there is a single exit from the loop. 7909 BasicBlock *Exit = nullptr; 7910 for (auto *SBB : successors(ExitingBlock)) 7911 if (!L->contains(SBB)) { 7912 if (Exit) // Multiple exit successors. 7913 return getCouldNotCompute(); 7914 Exit = SBB; 7915 } 7916 assert(Exit && "Exiting block must have at least one exit"); 7917 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7918 /*ControlsExit=*/IsOnlyExit); 7919 } 7920 7921 return getCouldNotCompute(); 7922 } 7923 7924 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7925 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7926 bool ControlsExit, bool AllowPredicates) { 7927 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7928 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7929 ControlsExit, AllowPredicates); 7930 } 7931 7932 Optional<ScalarEvolution::ExitLimit> 7933 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7934 bool ExitIfTrue, bool ControlsExit, 7935 bool AllowPredicates) { 7936 (void)this->L; 7937 (void)this->ExitIfTrue; 7938 (void)this->AllowPredicates; 7939 7940 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7941 this->AllowPredicates == AllowPredicates && 7942 "Variance in assumed invariant key components!"); 7943 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7944 if (Itr == TripCountMap.end()) 7945 return None; 7946 return Itr->second; 7947 } 7948 7949 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7950 bool ExitIfTrue, 7951 bool ControlsExit, 7952 bool AllowPredicates, 7953 const ExitLimit &EL) { 7954 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7955 this->AllowPredicates == AllowPredicates && 7956 "Variance in assumed invariant key components!"); 7957 7958 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7959 assert(InsertResult.second && "Expected successful insertion!"); 7960 (void)InsertResult; 7961 (void)ExitIfTrue; 7962 } 7963 7964 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7965 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7966 bool ControlsExit, bool AllowPredicates) { 7967 7968 if (auto MaybeEL = 7969 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7970 return *MaybeEL; 7971 7972 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7973 ControlsExit, AllowPredicates); 7974 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7975 return EL; 7976 } 7977 7978 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7979 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7980 bool ControlsExit, bool AllowPredicates) { 7981 // Handle BinOp conditions (And, Or). 7982 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7983 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7984 return *LimitFromBinOp; 7985 7986 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7987 // Proceed to the next level to examine the icmp. 7988 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7989 ExitLimit EL = 7990 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7991 if (EL.hasFullInfo() || !AllowPredicates) 7992 return EL; 7993 7994 // Try again, but use SCEV predicates this time. 7995 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7996 /*AllowPredicates=*/true); 7997 } 7998 7999 // Check for a constant condition. These are normally stripped out by 8000 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8001 // preserve the CFG and is temporarily leaving constant conditions 8002 // in place. 8003 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8004 if (ExitIfTrue == !CI->getZExtValue()) 8005 // The backedge is always taken. 8006 return getCouldNotCompute(); 8007 else 8008 // The backedge is never taken. 8009 return getZero(CI->getType()); 8010 } 8011 8012 // If it's not an integer or pointer comparison then compute it the hard way. 8013 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8014 } 8015 8016 Optional<ScalarEvolution::ExitLimit> 8017 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8018 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8019 bool ControlsExit, bool AllowPredicates) { 8020 // Check if the controlling expression for this loop is an And or Or. 8021 Value *Op0, *Op1; 8022 bool IsAnd = false; 8023 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8024 IsAnd = true; 8025 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8026 IsAnd = false; 8027 else 8028 return None; 8029 8030 // EitherMayExit is true in these two cases: 8031 // br (and Op0 Op1), loop, exit 8032 // br (or Op0 Op1), exit, loop 8033 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8034 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8035 ControlsExit && !EitherMayExit, 8036 AllowPredicates); 8037 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8038 ControlsExit && !EitherMayExit, 8039 AllowPredicates); 8040 8041 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8042 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8043 if (isa<ConstantInt>(Op1)) 8044 return Op1 == NeutralElement ? EL0 : EL1; 8045 if (isa<ConstantInt>(Op0)) 8046 return Op0 == NeutralElement ? EL1 : EL0; 8047 8048 const SCEV *BECount = getCouldNotCompute(); 8049 const SCEV *MaxBECount = getCouldNotCompute(); 8050 if (EitherMayExit) { 8051 // Both conditions must be same for the loop to continue executing. 8052 // Choose the less conservative count. 8053 // If ExitCond is a short-circuit form (select), using 8054 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 8055 // To see the detailed examples, please see 8056 // test/Analysis/ScalarEvolution/exit-count-select.ll 8057 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 8058 if (!PoisonSafe) 8059 // Even if ExitCond is select, we can safely derive BECount using both 8060 // EL0 and EL1 in these cases: 8061 // (1) EL0.ExactNotTaken is non-zero 8062 // (2) EL1.ExactNotTaken is non-poison 8063 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 8064 // it cannot be umin(0, ..)) 8065 // The PoisonSafe assignment below is simplified and the assertion after 8066 // BECount calculation fully guarantees the condition (3). 8067 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 8068 isa<SCEVConstant>(EL1.ExactNotTaken); 8069 if (EL0.ExactNotTaken != getCouldNotCompute() && 8070 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 8071 BECount = 8072 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 8073 8074 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8075 // it should have been simplified to zero (see the condition (3) above) 8076 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8077 BECount->isZero()); 8078 } 8079 if (EL0.MaxNotTaken == getCouldNotCompute()) 8080 MaxBECount = EL1.MaxNotTaken; 8081 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8082 MaxBECount = EL0.MaxNotTaken; 8083 else 8084 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8085 } else { 8086 // Both conditions must be same at the same time for the loop to exit. 8087 // For now, be conservative. 8088 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8089 BECount = EL0.ExactNotTaken; 8090 } 8091 8092 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8093 // to be more aggressive when computing BECount than when computing 8094 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8095 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8096 // to not. 8097 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8098 !isa<SCEVCouldNotCompute>(BECount)) 8099 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8100 8101 return ExitLimit(BECount, MaxBECount, false, 8102 { &EL0.Predicates, &EL1.Predicates }); 8103 } 8104 8105 ScalarEvolution::ExitLimit 8106 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8107 ICmpInst *ExitCond, 8108 bool ExitIfTrue, 8109 bool ControlsExit, 8110 bool AllowPredicates) { 8111 // If the condition was exit on true, convert the condition to exit on false 8112 ICmpInst::Predicate Pred; 8113 if (!ExitIfTrue) 8114 Pred = ExitCond->getPredicate(); 8115 else 8116 Pred = ExitCond->getInversePredicate(); 8117 const ICmpInst::Predicate OriginalPred = Pred; 8118 8119 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8120 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8121 8122 // Try to evaluate any dependencies out of the loop. 8123 LHS = getSCEVAtScope(LHS, L); 8124 RHS = getSCEVAtScope(RHS, L); 8125 8126 // At this point, we would like to compute how many iterations of the 8127 // loop the predicate will return true for these inputs. 8128 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8129 // If there is a loop-invariant, force it into the RHS. 8130 std::swap(LHS, RHS); 8131 Pred = ICmpInst::getSwappedPredicate(Pred); 8132 } 8133 8134 // Simplify the operands before analyzing them. 8135 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8136 8137 // If we have a comparison of a chrec against a constant, try to use value 8138 // ranges to answer this query. 8139 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8140 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8141 if (AddRec->getLoop() == L) { 8142 // Form the constant range. 8143 ConstantRange CompRange = 8144 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8145 8146 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8147 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8148 } 8149 8150 switch (Pred) { 8151 case ICmpInst::ICMP_NE: { // while (X != Y) 8152 // Convert to: while (X-Y != 0) 8153 if (LHS->getType()->isPointerTy()) { 8154 LHS = getLosslessPtrToIntExpr(LHS); 8155 if (isa<SCEVCouldNotCompute>(LHS)) 8156 return LHS; 8157 } 8158 if (RHS->getType()->isPointerTy()) { 8159 RHS = getLosslessPtrToIntExpr(RHS); 8160 if (isa<SCEVCouldNotCompute>(RHS)) 8161 return RHS; 8162 } 8163 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8164 AllowPredicates); 8165 if (EL.hasAnyInfo()) return EL; 8166 break; 8167 } 8168 case ICmpInst::ICMP_EQ: { // while (X == Y) 8169 // Convert to: while (X-Y == 0) 8170 if (LHS->getType()->isPointerTy()) { 8171 LHS = getLosslessPtrToIntExpr(LHS); 8172 if (isa<SCEVCouldNotCompute>(LHS)) 8173 return LHS; 8174 } 8175 if (RHS->getType()->isPointerTy()) { 8176 RHS = getLosslessPtrToIntExpr(RHS); 8177 if (isa<SCEVCouldNotCompute>(RHS)) 8178 return RHS; 8179 } 8180 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8181 if (EL.hasAnyInfo()) return EL; 8182 break; 8183 } 8184 case ICmpInst::ICMP_SLT: 8185 case ICmpInst::ICMP_ULT: { // while (X < Y) 8186 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8187 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8188 AllowPredicates); 8189 if (EL.hasAnyInfo()) return EL; 8190 break; 8191 } 8192 case ICmpInst::ICMP_SGT: 8193 case ICmpInst::ICMP_UGT: { // while (X > Y) 8194 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8195 ExitLimit EL = 8196 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8197 AllowPredicates); 8198 if (EL.hasAnyInfo()) return EL; 8199 break; 8200 } 8201 default: 8202 break; 8203 } 8204 8205 auto *ExhaustiveCount = 8206 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8207 8208 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8209 return ExhaustiveCount; 8210 8211 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8212 ExitCond->getOperand(1), L, OriginalPred); 8213 } 8214 8215 ScalarEvolution::ExitLimit 8216 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8217 SwitchInst *Switch, 8218 BasicBlock *ExitingBlock, 8219 bool ControlsExit) { 8220 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8221 8222 // Give up if the exit is the default dest of a switch. 8223 if (Switch->getDefaultDest() == ExitingBlock) 8224 return getCouldNotCompute(); 8225 8226 assert(L->contains(Switch->getDefaultDest()) && 8227 "Default case must not exit the loop!"); 8228 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8229 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8230 8231 // while (X != Y) --> while (X-Y != 0) 8232 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8233 if (EL.hasAnyInfo()) 8234 return EL; 8235 8236 return getCouldNotCompute(); 8237 } 8238 8239 static ConstantInt * 8240 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8241 ScalarEvolution &SE) { 8242 const SCEV *InVal = SE.getConstant(C); 8243 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8244 assert(isa<SCEVConstant>(Val) && 8245 "Evaluation of SCEV at constant didn't fold correctly?"); 8246 return cast<SCEVConstant>(Val)->getValue(); 8247 } 8248 8249 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8250 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8251 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8252 if (!RHS) 8253 return getCouldNotCompute(); 8254 8255 const BasicBlock *Latch = L->getLoopLatch(); 8256 if (!Latch) 8257 return getCouldNotCompute(); 8258 8259 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8260 if (!Predecessor) 8261 return getCouldNotCompute(); 8262 8263 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8264 // Return LHS in OutLHS and shift_opt in OutOpCode. 8265 auto MatchPositiveShift = 8266 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8267 8268 using namespace PatternMatch; 8269 8270 ConstantInt *ShiftAmt; 8271 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8272 OutOpCode = Instruction::LShr; 8273 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8274 OutOpCode = Instruction::AShr; 8275 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8276 OutOpCode = Instruction::Shl; 8277 else 8278 return false; 8279 8280 return ShiftAmt->getValue().isStrictlyPositive(); 8281 }; 8282 8283 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8284 // 8285 // loop: 8286 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8287 // %iv.shifted = lshr i32 %iv, <positive constant> 8288 // 8289 // Return true on a successful match. Return the corresponding PHI node (%iv 8290 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8291 auto MatchShiftRecurrence = 8292 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8293 Optional<Instruction::BinaryOps> PostShiftOpCode; 8294 8295 { 8296 Instruction::BinaryOps OpC; 8297 Value *V; 8298 8299 // If we encounter a shift instruction, "peel off" the shift operation, 8300 // and remember that we did so. Later when we inspect %iv's backedge 8301 // value, we will make sure that the backedge value uses the same 8302 // operation. 8303 // 8304 // Note: the peeled shift operation does not have to be the same 8305 // instruction as the one feeding into the PHI's backedge value. We only 8306 // really care about it being the same *kind* of shift instruction -- 8307 // that's all that is required for our later inferences to hold. 8308 if (MatchPositiveShift(LHS, V, OpC)) { 8309 PostShiftOpCode = OpC; 8310 LHS = V; 8311 } 8312 } 8313 8314 PNOut = dyn_cast<PHINode>(LHS); 8315 if (!PNOut || PNOut->getParent() != L->getHeader()) 8316 return false; 8317 8318 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8319 Value *OpLHS; 8320 8321 return 8322 // The backedge value for the PHI node must be a shift by a positive 8323 // amount 8324 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8325 8326 // of the PHI node itself 8327 OpLHS == PNOut && 8328 8329 // and the kind of shift should be match the kind of shift we peeled 8330 // off, if any. 8331 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8332 }; 8333 8334 PHINode *PN; 8335 Instruction::BinaryOps OpCode; 8336 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8337 return getCouldNotCompute(); 8338 8339 const DataLayout &DL = getDataLayout(); 8340 8341 // The key rationale for this optimization is that for some kinds of shift 8342 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8343 // within a finite number of iterations. If the condition guarding the 8344 // backedge (in the sense that the backedge is taken if the condition is true) 8345 // is false for the value the shift recurrence stabilizes to, then we know 8346 // that the backedge is taken only a finite number of times. 8347 8348 ConstantInt *StableValue = nullptr; 8349 switch (OpCode) { 8350 default: 8351 llvm_unreachable("Impossible case!"); 8352 8353 case Instruction::AShr: { 8354 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8355 // bitwidth(K) iterations. 8356 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8357 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8358 Predecessor->getTerminator(), &DT); 8359 auto *Ty = cast<IntegerType>(RHS->getType()); 8360 if (Known.isNonNegative()) 8361 StableValue = ConstantInt::get(Ty, 0); 8362 else if (Known.isNegative()) 8363 StableValue = ConstantInt::get(Ty, -1, true); 8364 else 8365 return getCouldNotCompute(); 8366 8367 break; 8368 } 8369 case Instruction::LShr: 8370 case Instruction::Shl: 8371 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8372 // stabilize to 0 in at most bitwidth(K) iterations. 8373 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8374 break; 8375 } 8376 8377 auto *Result = 8378 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8379 assert(Result->getType()->isIntegerTy(1) && 8380 "Otherwise cannot be an operand to a branch instruction"); 8381 8382 if (Result->isZeroValue()) { 8383 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8384 const SCEV *UpperBound = 8385 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8386 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8387 } 8388 8389 return getCouldNotCompute(); 8390 } 8391 8392 /// Return true if we can constant fold an instruction of the specified type, 8393 /// assuming that all operands were constants. 8394 static bool CanConstantFold(const Instruction *I) { 8395 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8396 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8397 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8398 return true; 8399 8400 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8401 if (const Function *F = CI->getCalledFunction()) 8402 return canConstantFoldCallTo(CI, F); 8403 return false; 8404 } 8405 8406 /// Determine whether this instruction can constant evolve within this loop 8407 /// assuming its operands can all constant evolve. 8408 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8409 // An instruction outside of the loop can't be derived from a loop PHI. 8410 if (!L->contains(I)) return false; 8411 8412 if (isa<PHINode>(I)) { 8413 // We don't currently keep track of the control flow needed to evaluate 8414 // PHIs, so we cannot handle PHIs inside of loops. 8415 return L->getHeader() == I->getParent(); 8416 } 8417 8418 // If we won't be able to constant fold this expression even if the operands 8419 // are constants, bail early. 8420 return CanConstantFold(I); 8421 } 8422 8423 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8424 /// recursing through each instruction operand until reaching a loop header phi. 8425 static PHINode * 8426 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8427 DenseMap<Instruction *, PHINode *> &PHIMap, 8428 unsigned Depth) { 8429 if (Depth > MaxConstantEvolvingDepth) 8430 return nullptr; 8431 8432 // Otherwise, we can evaluate this instruction if all of its operands are 8433 // constant or derived from a PHI node themselves. 8434 PHINode *PHI = nullptr; 8435 for (Value *Op : UseInst->operands()) { 8436 if (isa<Constant>(Op)) continue; 8437 8438 Instruction *OpInst = dyn_cast<Instruction>(Op); 8439 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8440 8441 PHINode *P = dyn_cast<PHINode>(OpInst); 8442 if (!P) 8443 // If this operand is already visited, reuse the prior result. 8444 // We may have P != PHI if this is the deepest point at which the 8445 // inconsistent paths meet. 8446 P = PHIMap.lookup(OpInst); 8447 if (!P) { 8448 // Recurse and memoize the results, whether a phi is found or not. 8449 // This recursive call invalidates pointers into PHIMap. 8450 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8451 PHIMap[OpInst] = P; 8452 } 8453 if (!P) 8454 return nullptr; // Not evolving from PHI 8455 if (PHI && PHI != P) 8456 return nullptr; // Evolving from multiple different PHIs. 8457 PHI = P; 8458 } 8459 // This is a expression evolving from a constant PHI! 8460 return PHI; 8461 } 8462 8463 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8464 /// in the loop that V is derived from. We allow arbitrary operations along the 8465 /// way, but the operands of an operation must either be constants or a value 8466 /// derived from a constant PHI. If this expression does not fit with these 8467 /// constraints, return null. 8468 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8469 Instruction *I = dyn_cast<Instruction>(V); 8470 if (!I || !canConstantEvolve(I, L)) return nullptr; 8471 8472 if (PHINode *PN = dyn_cast<PHINode>(I)) 8473 return PN; 8474 8475 // Record non-constant instructions contained by the loop. 8476 DenseMap<Instruction *, PHINode *> PHIMap; 8477 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8478 } 8479 8480 /// EvaluateExpression - Given an expression that passes the 8481 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8482 /// in the loop has the value PHIVal. If we can't fold this expression for some 8483 /// reason, return null. 8484 static Constant *EvaluateExpression(Value *V, const Loop *L, 8485 DenseMap<Instruction *, Constant *> &Vals, 8486 const DataLayout &DL, 8487 const TargetLibraryInfo *TLI) { 8488 // Convenient constant check, but redundant for recursive calls. 8489 if (Constant *C = dyn_cast<Constant>(V)) return C; 8490 Instruction *I = dyn_cast<Instruction>(V); 8491 if (!I) return nullptr; 8492 8493 if (Constant *C = Vals.lookup(I)) return C; 8494 8495 // An instruction inside the loop depends on a value outside the loop that we 8496 // weren't given a mapping for, or a value such as a call inside the loop. 8497 if (!canConstantEvolve(I, L)) return nullptr; 8498 8499 // An unmapped PHI can be due to a branch or another loop inside this loop, 8500 // or due to this not being the initial iteration through a loop where we 8501 // couldn't compute the evolution of this particular PHI last time. 8502 if (isa<PHINode>(I)) return nullptr; 8503 8504 std::vector<Constant*> Operands(I->getNumOperands()); 8505 8506 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8507 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8508 if (!Operand) { 8509 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8510 if (!Operands[i]) return nullptr; 8511 continue; 8512 } 8513 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8514 Vals[Operand] = C; 8515 if (!C) return nullptr; 8516 Operands[i] = C; 8517 } 8518 8519 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8520 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8521 Operands[1], DL, TLI); 8522 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8523 if (!LI->isVolatile()) 8524 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8525 } 8526 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8527 } 8528 8529 8530 // If every incoming value to PN except the one for BB is a specific Constant, 8531 // return that, else return nullptr. 8532 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8533 Constant *IncomingVal = nullptr; 8534 8535 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8536 if (PN->getIncomingBlock(i) == BB) 8537 continue; 8538 8539 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8540 if (!CurrentVal) 8541 return nullptr; 8542 8543 if (IncomingVal != CurrentVal) { 8544 if (IncomingVal) 8545 return nullptr; 8546 IncomingVal = CurrentVal; 8547 } 8548 } 8549 8550 return IncomingVal; 8551 } 8552 8553 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8554 /// in the header of its containing loop, we know the loop executes a 8555 /// constant number of times, and the PHI node is just a recurrence 8556 /// involving constants, fold it. 8557 Constant * 8558 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8559 const APInt &BEs, 8560 const Loop *L) { 8561 auto I = ConstantEvolutionLoopExitValue.find(PN); 8562 if (I != ConstantEvolutionLoopExitValue.end()) 8563 return I->second; 8564 8565 if (BEs.ugt(MaxBruteForceIterations)) 8566 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8567 8568 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8569 8570 DenseMap<Instruction *, Constant *> CurrentIterVals; 8571 BasicBlock *Header = L->getHeader(); 8572 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8573 8574 BasicBlock *Latch = L->getLoopLatch(); 8575 if (!Latch) 8576 return nullptr; 8577 8578 for (PHINode &PHI : Header->phis()) { 8579 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8580 CurrentIterVals[&PHI] = StartCST; 8581 } 8582 if (!CurrentIterVals.count(PN)) 8583 return RetVal = nullptr; 8584 8585 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8586 8587 // Execute the loop symbolically to determine the exit value. 8588 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8589 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8590 8591 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8592 unsigned IterationNum = 0; 8593 const DataLayout &DL = getDataLayout(); 8594 for (; ; ++IterationNum) { 8595 if (IterationNum == NumIterations) 8596 return RetVal = CurrentIterVals[PN]; // Got exit value! 8597 8598 // Compute the value of the PHIs for the next iteration. 8599 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8600 DenseMap<Instruction *, Constant *> NextIterVals; 8601 Constant *NextPHI = 8602 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8603 if (!NextPHI) 8604 return nullptr; // Couldn't evaluate! 8605 NextIterVals[PN] = NextPHI; 8606 8607 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8608 8609 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8610 // cease to be able to evaluate one of them or if they stop evolving, 8611 // because that doesn't necessarily prevent us from computing PN. 8612 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8613 for (const auto &I : CurrentIterVals) { 8614 PHINode *PHI = dyn_cast<PHINode>(I.first); 8615 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8616 PHIsToCompute.emplace_back(PHI, I.second); 8617 } 8618 // We use two distinct loops because EvaluateExpression may invalidate any 8619 // iterators into CurrentIterVals. 8620 for (const auto &I : PHIsToCompute) { 8621 PHINode *PHI = I.first; 8622 Constant *&NextPHI = NextIterVals[PHI]; 8623 if (!NextPHI) { // Not already computed. 8624 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8625 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8626 } 8627 if (NextPHI != I.second) 8628 StoppedEvolving = false; 8629 } 8630 8631 // If all entries in CurrentIterVals == NextIterVals then we can stop 8632 // iterating, the loop can't continue to change. 8633 if (StoppedEvolving) 8634 return RetVal = CurrentIterVals[PN]; 8635 8636 CurrentIterVals.swap(NextIterVals); 8637 } 8638 } 8639 8640 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8641 Value *Cond, 8642 bool ExitWhen) { 8643 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8644 if (!PN) return getCouldNotCompute(); 8645 8646 // If the loop is canonicalized, the PHI will have exactly two entries. 8647 // That's the only form we support here. 8648 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8649 8650 DenseMap<Instruction *, Constant *> CurrentIterVals; 8651 BasicBlock *Header = L->getHeader(); 8652 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8653 8654 BasicBlock *Latch = L->getLoopLatch(); 8655 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8656 8657 for (PHINode &PHI : Header->phis()) { 8658 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8659 CurrentIterVals[&PHI] = StartCST; 8660 } 8661 if (!CurrentIterVals.count(PN)) 8662 return getCouldNotCompute(); 8663 8664 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8665 // the loop symbolically to determine when the condition gets a value of 8666 // "ExitWhen". 8667 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8668 const DataLayout &DL = getDataLayout(); 8669 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8670 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8671 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8672 8673 // Couldn't symbolically evaluate. 8674 if (!CondVal) return getCouldNotCompute(); 8675 8676 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8677 ++NumBruteForceTripCountsComputed; 8678 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8679 } 8680 8681 // Update all the PHI nodes for the next iteration. 8682 DenseMap<Instruction *, Constant *> NextIterVals; 8683 8684 // Create a list of which PHIs we need to compute. We want to do this before 8685 // calling EvaluateExpression on them because that may invalidate iterators 8686 // into CurrentIterVals. 8687 SmallVector<PHINode *, 8> PHIsToCompute; 8688 for (const auto &I : CurrentIterVals) { 8689 PHINode *PHI = dyn_cast<PHINode>(I.first); 8690 if (!PHI || PHI->getParent() != Header) continue; 8691 PHIsToCompute.push_back(PHI); 8692 } 8693 for (PHINode *PHI : PHIsToCompute) { 8694 Constant *&NextPHI = NextIterVals[PHI]; 8695 if (NextPHI) continue; // Already computed! 8696 8697 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8698 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8699 } 8700 CurrentIterVals.swap(NextIterVals); 8701 } 8702 8703 // Too many iterations were needed to evaluate. 8704 return getCouldNotCompute(); 8705 } 8706 8707 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8708 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8709 ValuesAtScopes[V]; 8710 // Check to see if we've folded this expression at this loop before. 8711 for (auto &LS : Values) 8712 if (LS.first == L) 8713 return LS.second ? LS.second : V; 8714 8715 Values.emplace_back(L, nullptr); 8716 8717 // Otherwise compute it. 8718 const SCEV *C = computeSCEVAtScope(V, L); 8719 for (auto &LS : reverse(ValuesAtScopes[V])) 8720 if (LS.first == L) { 8721 LS.second = C; 8722 break; 8723 } 8724 return C; 8725 } 8726 8727 /// This builds up a Constant using the ConstantExpr interface. That way, we 8728 /// will return Constants for objects which aren't represented by a 8729 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8730 /// Returns NULL if the SCEV isn't representable as a Constant. 8731 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8732 switch (V->getSCEVType()) { 8733 case scCouldNotCompute: 8734 case scAddRecExpr: 8735 return nullptr; 8736 case scConstant: 8737 return cast<SCEVConstant>(V)->getValue(); 8738 case scUnknown: 8739 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8740 case scSignExtend: { 8741 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8742 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8743 return ConstantExpr::getSExt(CastOp, SS->getType()); 8744 return nullptr; 8745 } 8746 case scZeroExtend: { 8747 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8748 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8749 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8750 return nullptr; 8751 } 8752 case scPtrToInt: { 8753 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8754 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8755 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8756 8757 return nullptr; 8758 } 8759 case scTruncate: { 8760 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8761 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8762 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8763 return nullptr; 8764 } 8765 case scAddExpr: { 8766 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8767 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8768 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8769 unsigned AS = PTy->getAddressSpace(); 8770 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8771 C = ConstantExpr::getBitCast(C, DestPtrTy); 8772 } 8773 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8774 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8775 if (!C2) 8776 return nullptr; 8777 8778 // First pointer! 8779 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8780 unsigned AS = C2->getType()->getPointerAddressSpace(); 8781 std::swap(C, C2); 8782 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8783 // The offsets have been converted to bytes. We can add bytes to an 8784 // i8* by GEP with the byte count in the first index. 8785 C = ConstantExpr::getBitCast(C, DestPtrTy); 8786 } 8787 8788 // Don't bother trying to sum two pointers. We probably can't 8789 // statically compute a load that results from it anyway. 8790 if (C2->getType()->isPointerTy()) 8791 return nullptr; 8792 8793 if (C->getType()->isPointerTy()) { 8794 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8795 C, C2); 8796 } else { 8797 C = ConstantExpr::getAdd(C, C2); 8798 } 8799 } 8800 return C; 8801 } 8802 return nullptr; 8803 } 8804 case scMulExpr: { 8805 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8806 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8807 // Don't bother with pointers at all. 8808 if (C->getType()->isPointerTy()) 8809 return nullptr; 8810 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8811 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8812 if (!C2 || C2->getType()->isPointerTy()) 8813 return nullptr; 8814 C = ConstantExpr::getMul(C, C2); 8815 } 8816 return C; 8817 } 8818 return nullptr; 8819 } 8820 case scUDivExpr: { 8821 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8822 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8823 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8824 if (LHS->getType() == RHS->getType()) 8825 return ConstantExpr::getUDiv(LHS, RHS); 8826 return nullptr; 8827 } 8828 case scSMaxExpr: 8829 case scUMaxExpr: 8830 case scSMinExpr: 8831 case scUMinExpr: 8832 return nullptr; // TODO: smax, umax, smin, umax. 8833 } 8834 llvm_unreachable("Unknown SCEV kind!"); 8835 } 8836 8837 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8838 if (isa<SCEVConstant>(V)) return V; 8839 8840 // If this instruction is evolved from a constant-evolving PHI, compute the 8841 // exit value from the loop without using SCEVs. 8842 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8843 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8844 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8845 const Loop *CurrLoop = this->LI[I->getParent()]; 8846 // Looking for loop exit value. 8847 if (CurrLoop && CurrLoop->getParentLoop() == L && 8848 PN->getParent() == CurrLoop->getHeader()) { 8849 // Okay, there is no closed form solution for the PHI node. Check 8850 // to see if the loop that contains it has a known backedge-taken 8851 // count. If so, we may be able to force computation of the exit 8852 // value. 8853 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8854 // This trivial case can show up in some degenerate cases where 8855 // the incoming IR has not yet been fully simplified. 8856 if (BackedgeTakenCount->isZero()) { 8857 Value *InitValue = nullptr; 8858 bool MultipleInitValues = false; 8859 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8860 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8861 if (!InitValue) 8862 InitValue = PN->getIncomingValue(i); 8863 else if (InitValue != PN->getIncomingValue(i)) { 8864 MultipleInitValues = true; 8865 break; 8866 } 8867 } 8868 } 8869 if (!MultipleInitValues && InitValue) 8870 return getSCEV(InitValue); 8871 } 8872 // Do we have a loop invariant value flowing around the backedge 8873 // for a loop which must execute the backedge? 8874 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8875 isKnownPositive(BackedgeTakenCount) && 8876 PN->getNumIncomingValues() == 2) { 8877 8878 unsigned InLoopPred = 8879 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8880 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8881 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8882 return getSCEV(BackedgeVal); 8883 } 8884 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8885 // Okay, we know how many times the containing loop executes. If 8886 // this is a constant evolving PHI node, get the final value at 8887 // the specified iteration number. 8888 Constant *RV = getConstantEvolutionLoopExitValue( 8889 PN, BTCC->getAPInt(), CurrLoop); 8890 if (RV) return getSCEV(RV); 8891 } 8892 } 8893 8894 // If there is a single-input Phi, evaluate it at our scope. If we can 8895 // prove that this replacement does not break LCSSA form, use new value. 8896 if (PN->getNumOperands() == 1) { 8897 const SCEV *Input = getSCEV(PN->getOperand(0)); 8898 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8899 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8900 // for the simplest case just support constants. 8901 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8902 } 8903 } 8904 8905 // Okay, this is an expression that we cannot symbolically evaluate 8906 // into a SCEV. Check to see if it's possible to symbolically evaluate 8907 // the arguments into constants, and if so, try to constant propagate the 8908 // result. This is particularly useful for computing loop exit values. 8909 if (CanConstantFold(I)) { 8910 SmallVector<Constant *, 4> Operands; 8911 bool MadeImprovement = false; 8912 for (Value *Op : I->operands()) { 8913 if (Constant *C = dyn_cast<Constant>(Op)) { 8914 Operands.push_back(C); 8915 continue; 8916 } 8917 8918 // If any of the operands is non-constant and if they are 8919 // non-integer and non-pointer, don't even try to analyze them 8920 // with scev techniques. 8921 if (!isSCEVable(Op->getType())) 8922 return V; 8923 8924 const SCEV *OrigV = getSCEV(Op); 8925 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8926 MadeImprovement |= OrigV != OpV; 8927 8928 Constant *C = BuildConstantFromSCEV(OpV); 8929 if (!C) return V; 8930 if (C->getType() != Op->getType()) 8931 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8932 Op->getType(), 8933 false), 8934 C, Op->getType()); 8935 Operands.push_back(C); 8936 } 8937 8938 // Check to see if getSCEVAtScope actually made an improvement. 8939 if (MadeImprovement) { 8940 Constant *C = nullptr; 8941 const DataLayout &DL = getDataLayout(); 8942 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8943 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8944 Operands[1], DL, &TLI); 8945 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8946 if (!Load->isVolatile()) 8947 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8948 DL); 8949 } else 8950 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8951 if (!C) return V; 8952 return getSCEV(C); 8953 } 8954 } 8955 } 8956 8957 // This is some other type of SCEVUnknown, just return it. 8958 return V; 8959 } 8960 8961 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8962 // Avoid performing the look-up in the common case where the specified 8963 // expression has no loop-variant portions. 8964 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8965 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8966 if (OpAtScope != Comm->getOperand(i)) { 8967 // Okay, at least one of these operands is loop variant but might be 8968 // foldable. Build a new instance of the folded commutative expression. 8969 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8970 Comm->op_begin()+i); 8971 NewOps.push_back(OpAtScope); 8972 8973 for (++i; i != e; ++i) { 8974 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8975 NewOps.push_back(OpAtScope); 8976 } 8977 if (isa<SCEVAddExpr>(Comm)) 8978 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8979 if (isa<SCEVMulExpr>(Comm)) 8980 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8981 if (isa<SCEVMinMaxExpr>(Comm)) 8982 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8983 llvm_unreachable("Unknown commutative SCEV type!"); 8984 } 8985 } 8986 // If we got here, all operands are loop invariant. 8987 return Comm; 8988 } 8989 8990 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8991 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8992 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8993 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8994 return Div; // must be loop invariant 8995 return getUDivExpr(LHS, RHS); 8996 } 8997 8998 // If this is a loop recurrence for a loop that does not contain L, then we 8999 // are dealing with the final value computed by the loop. 9000 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9001 // First, attempt to evaluate each operand. 9002 // Avoid performing the look-up in the common case where the specified 9003 // expression has no loop-variant portions. 9004 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9005 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9006 if (OpAtScope == AddRec->getOperand(i)) 9007 continue; 9008 9009 // Okay, at least one of these operands is loop variant but might be 9010 // foldable. Build a new instance of the folded commutative expression. 9011 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9012 AddRec->op_begin()+i); 9013 NewOps.push_back(OpAtScope); 9014 for (++i; i != e; ++i) 9015 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9016 9017 const SCEV *FoldedRec = 9018 getAddRecExpr(NewOps, AddRec->getLoop(), 9019 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9020 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9021 // The addrec may be folded to a nonrecurrence, for example, if the 9022 // induction variable is multiplied by zero after constant folding. Go 9023 // ahead and return the folded value. 9024 if (!AddRec) 9025 return FoldedRec; 9026 break; 9027 } 9028 9029 // If the scope is outside the addrec's loop, evaluate it by using the 9030 // loop exit value of the addrec. 9031 if (!AddRec->getLoop()->contains(L)) { 9032 // To evaluate this recurrence, we need to know how many times the AddRec 9033 // loop iterates. Compute this now. 9034 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9035 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9036 9037 // Then, evaluate the AddRec. 9038 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9039 } 9040 9041 return AddRec; 9042 } 9043 9044 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9045 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9046 if (Op == Cast->getOperand()) 9047 return Cast; // must be loop invariant 9048 return getZeroExtendExpr(Op, Cast->getType()); 9049 } 9050 9051 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9052 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9053 if (Op == Cast->getOperand()) 9054 return Cast; // must be loop invariant 9055 return getSignExtendExpr(Op, Cast->getType()); 9056 } 9057 9058 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9059 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9060 if (Op == Cast->getOperand()) 9061 return Cast; // must be loop invariant 9062 return getTruncateExpr(Op, Cast->getType()); 9063 } 9064 9065 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9066 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9067 if (Op == Cast->getOperand()) 9068 return Cast; // must be loop invariant 9069 return getPtrToIntExpr(Op, Cast->getType()); 9070 } 9071 9072 llvm_unreachable("Unknown SCEV type!"); 9073 } 9074 9075 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9076 return getSCEVAtScope(getSCEV(V), L); 9077 } 9078 9079 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9080 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9081 return stripInjectiveFunctions(ZExt->getOperand()); 9082 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9083 return stripInjectiveFunctions(SExt->getOperand()); 9084 return S; 9085 } 9086 9087 /// Finds the minimum unsigned root of the following equation: 9088 /// 9089 /// A * X = B (mod N) 9090 /// 9091 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9092 /// A and B isn't important. 9093 /// 9094 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9095 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9096 ScalarEvolution &SE) { 9097 uint32_t BW = A.getBitWidth(); 9098 assert(BW == SE.getTypeSizeInBits(B->getType())); 9099 assert(A != 0 && "A must be non-zero."); 9100 9101 // 1. D = gcd(A, N) 9102 // 9103 // The gcd of A and N may have only one prime factor: 2. The number of 9104 // trailing zeros in A is its multiplicity 9105 uint32_t Mult2 = A.countTrailingZeros(); 9106 // D = 2^Mult2 9107 9108 // 2. Check if B is divisible by D. 9109 // 9110 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9111 // is not less than multiplicity of this prime factor for D. 9112 if (SE.GetMinTrailingZeros(B) < Mult2) 9113 return SE.getCouldNotCompute(); 9114 9115 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9116 // modulo (N / D). 9117 // 9118 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9119 // (N / D) in general. The inverse itself always fits into BW bits, though, 9120 // so we immediately truncate it. 9121 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9122 APInt Mod(BW + 1, 0); 9123 Mod.setBit(BW - Mult2); // Mod = N / D 9124 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9125 9126 // 4. Compute the minimum unsigned root of the equation: 9127 // I * (B / D) mod (N / D) 9128 // To simplify the computation, we factor out the divide by D: 9129 // (I * B mod N) / D 9130 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9131 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9132 } 9133 9134 /// For a given quadratic addrec, generate coefficients of the corresponding 9135 /// quadratic equation, multiplied by a common value to ensure that they are 9136 /// integers. 9137 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9138 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9139 /// were multiplied by, and BitWidth is the bit width of the original addrec 9140 /// coefficients. 9141 /// This function returns None if the addrec coefficients are not compile- 9142 /// time constants. 9143 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9144 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9145 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9146 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9147 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9148 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9149 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9150 << *AddRec << '\n'); 9151 9152 // We currently can only solve this if the coefficients are constants. 9153 if (!LC || !MC || !NC) { 9154 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9155 return None; 9156 } 9157 9158 APInt L = LC->getAPInt(); 9159 APInt M = MC->getAPInt(); 9160 APInt N = NC->getAPInt(); 9161 assert(!N.isZero() && "This is not a quadratic addrec"); 9162 9163 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9164 unsigned NewWidth = BitWidth + 1; 9165 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9166 << BitWidth << '\n'); 9167 // The sign-extension (as opposed to a zero-extension) here matches the 9168 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9169 N = N.sext(NewWidth); 9170 M = M.sext(NewWidth); 9171 L = L.sext(NewWidth); 9172 9173 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9174 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9175 // L+M, L+2M+N, L+3M+3N, ... 9176 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9177 // 9178 // The equation Acc = 0 is then 9179 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9180 // In a quadratic form it becomes: 9181 // N n^2 + (2M-N) n + 2L = 0. 9182 9183 APInt A = N; 9184 APInt B = 2 * M - A; 9185 APInt C = 2 * L; 9186 APInt T = APInt(NewWidth, 2); 9187 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9188 << "x + " << C << ", coeff bw: " << NewWidth 9189 << ", multiplied by " << T << '\n'); 9190 return std::make_tuple(A, B, C, T, BitWidth); 9191 } 9192 9193 /// Helper function to compare optional APInts: 9194 /// (a) if X and Y both exist, return min(X, Y), 9195 /// (b) if neither X nor Y exist, return None, 9196 /// (c) if exactly one of X and Y exists, return that value. 9197 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9198 if (X.hasValue() && Y.hasValue()) { 9199 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9200 APInt XW = X->sextOrSelf(W); 9201 APInt YW = Y->sextOrSelf(W); 9202 return XW.slt(YW) ? *X : *Y; 9203 } 9204 if (!X.hasValue() && !Y.hasValue()) 9205 return None; 9206 return X.hasValue() ? *X : *Y; 9207 } 9208 9209 /// Helper function to truncate an optional APInt to a given BitWidth. 9210 /// When solving addrec-related equations, it is preferable to return a value 9211 /// that has the same bit width as the original addrec's coefficients. If the 9212 /// solution fits in the original bit width, truncate it (except for i1). 9213 /// Returning a value of a different bit width may inhibit some optimizations. 9214 /// 9215 /// In general, a solution to a quadratic equation generated from an addrec 9216 /// may require BW+1 bits, where BW is the bit width of the addrec's 9217 /// coefficients. The reason is that the coefficients of the quadratic 9218 /// equation are BW+1 bits wide (to avoid truncation when converting from 9219 /// the addrec to the equation). 9220 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9221 if (!X.hasValue()) 9222 return None; 9223 unsigned W = X->getBitWidth(); 9224 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9225 return X->trunc(BitWidth); 9226 return X; 9227 } 9228 9229 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9230 /// iterations. The values L, M, N are assumed to be signed, and they 9231 /// should all have the same bit widths. 9232 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9233 /// where BW is the bit width of the addrec's coefficients. 9234 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9235 /// returned as such, otherwise the bit width of the returned value may 9236 /// be greater than BW. 9237 /// 9238 /// This function returns None if 9239 /// (a) the addrec coefficients are not constant, or 9240 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9241 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9242 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9243 static Optional<APInt> 9244 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9245 APInt A, B, C, M; 9246 unsigned BitWidth; 9247 auto T = GetQuadraticEquation(AddRec); 9248 if (!T.hasValue()) 9249 return None; 9250 9251 std::tie(A, B, C, M, BitWidth) = *T; 9252 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9253 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9254 if (!X.hasValue()) 9255 return None; 9256 9257 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9258 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9259 if (!V->isZero()) 9260 return None; 9261 9262 return TruncIfPossible(X, BitWidth); 9263 } 9264 9265 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9266 /// iterations. The values M, N are assumed to be signed, and they 9267 /// should all have the same bit widths. 9268 /// Find the least n such that c(n) does not belong to the given range, 9269 /// while c(n-1) does. 9270 /// 9271 /// This function returns None if 9272 /// (a) the addrec coefficients are not constant, or 9273 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9274 /// bounds of the range. 9275 static Optional<APInt> 9276 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9277 const ConstantRange &Range, ScalarEvolution &SE) { 9278 assert(AddRec->getOperand(0)->isZero() && 9279 "Starting value of addrec should be 0"); 9280 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9281 << Range << ", addrec " << *AddRec << '\n'); 9282 // This case is handled in getNumIterationsInRange. Here we can assume that 9283 // we start in the range. 9284 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9285 "Addrec's initial value should be in range"); 9286 9287 APInt A, B, C, M; 9288 unsigned BitWidth; 9289 auto T = GetQuadraticEquation(AddRec); 9290 if (!T.hasValue()) 9291 return None; 9292 9293 // Be careful about the return value: there can be two reasons for not 9294 // returning an actual number. First, if no solutions to the equations 9295 // were found, and second, if the solutions don't leave the given range. 9296 // The first case means that the actual solution is "unknown", the second 9297 // means that it's known, but not valid. If the solution is unknown, we 9298 // cannot make any conclusions. 9299 // Return a pair: the optional solution and a flag indicating if the 9300 // solution was found. 9301 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9302 // Solve for signed overflow and unsigned overflow, pick the lower 9303 // solution. 9304 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9305 << Bound << " (before multiplying by " << M << ")\n"); 9306 Bound *= M; // The quadratic equation multiplier. 9307 9308 Optional<APInt> SO = None; 9309 if (BitWidth > 1) { 9310 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9311 "signed overflow\n"); 9312 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9313 } 9314 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9315 "unsigned overflow\n"); 9316 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9317 BitWidth+1); 9318 9319 auto LeavesRange = [&] (const APInt &X) { 9320 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9321 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9322 if (Range.contains(V0->getValue())) 9323 return false; 9324 // X should be at least 1, so X-1 is non-negative. 9325 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9326 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9327 if (Range.contains(V1->getValue())) 9328 return true; 9329 return false; 9330 }; 9331 9332 // If SolveQuadraticEquationWrap returns None, it means that there can 9333 // be a solution, but the function failed to find it. We cannot treat it 9334 // as "no solution". 9335 if (!SO.hasValue() || !UO.hasValue()) 9336 return { None, false }; 9337 9338 // Check the smaller value first to see if it leaves the range. 9339 // At this point, both SO and UO must have values. 9340 Optional<APInt> Min = MinOptional(SO, UO); 9341 if (LeavesRange(*Min)) 9342 return { Min, true }; 9343 Optional<APInt> Max = Min == SO ? UO : SO; 9344 if (LeavesRange(*Max)) 9345 return { Max, true }; 9346 9347 // Solutions were found, but were eliminated, hence the "true". 9348 return { None, true }; 9349 }; 9350 9351 std::tie(A, B, C, M, BitWidth) = *T; 9352 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9353 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9354 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9355 auto SL = SolveForBoundary(Lower); 9356 auto SU = SolveForBoundary(Upper); 9357 // If any of the solutions was unknown, no meaninigful conclusions can 9358 // be made. 9359 if (!SL.second || !SU.second) 9360 return None; 9361 9362 // Claim: The correct solution is not some value between Min and Max. 9363 // 9364 // Justification: Assuming that Min and Max are different values, one of 9365 // them is when the first signed overflow happens, the other is when the 9366 // first unsigned overflow happens. Crossing the range boundary is only 9367 // possible via an overflow (treating 0 as a special case of it, modeling 9368 // an overflow as crossing k*2^W for some k). 9369 // 9370 // The interesting case here is when Min was eliminated as an invalid 9371 // solution, but Max was not. The argument is that if there was another 9372 // overflow between Min and Max, it would also have been eliminated if 9373 // it was considered. 9374 // 9375 // For a given boundary, it is possible to have two overflows of the same 9376 // type (signed/unsigned) without having the other type in between: this 9377 // can happen when the vertex of the parabola is between the iterations 9378 // corresponding to the overflows. This is only possible when the two 9379 // overflows cross k*2^W for the same k. In such case, if the second one 9380 // left the range (and was the first one to do so), the first overflow 9381 // would have to enter the range, which would mean that either we had left 9382 // the range before or that we started outside of it. Both of these cases 9383 // are contradictions. 9384 // 9385 // Claim: In the case where SolveForBoundary returns None, the correct 9386 // solution is not some value between the Max for this boundary and the 9387 // Min of the other boundary. 9388 // 9389 // Justification: Assume that we had such Max_A and Min_B corresponding 9390 // to range boundaries A and B and such that Max_A < Min_B. If there was 9391 // a solution between Max_A and Min_B, it would have to be caused by an 9392 // overflow corresponding to either A or B. It cannot correspond to B, 9393 // since Min_B is the first occurrence of such an overflow. If it 9394 // corresponded to A, it would have to be either a signed or an unsigned 9395 // overflow that is larger than both eliminated overflows for A. But 9396 // between the eliminated overflows and this overflow, the values would 9397 // cover the entire value space, thus crossing the other boundary, which 9398 // is a contradiction. 9399 9400 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9401 } 9402 9403 ScalarEvolution::ExitLimit 9404 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9405 bool AllowPredicates) { 9406 9407 // This is only used for loops with a "x != y" exit test. The exit condition 9408 // is now expressed as a single expression, V = x-y. So the exit test is 9409 // effectively V != 0. We know and take advantage of the fact that this 9410 // expression only being used in a comparison by zero context. 9411 9412 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9413 // If the value is a constant 9414 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9415 // If the value is already zero, the branch will execute zero times. 9416 if (C->getValue()->isZero()) return C; 9417 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9418 } 9419 9420 const SCEVAddRecExpr *AddRec = 9421 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9422 9423 if (!AddRec && AllowPredicates) 9424 // Try to make this an AddRec using runtime tests, in the first X 9425 // iterations of this loop, where X is the SCEV expression found by the 9426 // algorithm below. 9427 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9428 9429 if (!AddRec || AddRec->getLoop() != L) 9430 return getCouldNotCompute(); 9431 9432 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9433 // the quadratic equation to solve it. 9434 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9435 // We can only use this value if the chrec ends up with an exact zero 9436 // value at this index. When solving for "X*X != 5", for example, we 9437 // should not accept a root of 2. 9438 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9439 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9440 return ExitLimit(R, R, false, Predicates); 9441 } 9442 return getCouldNotCompute(); 9443 } 9444 9445 // Otherwise we can only handle this if it is affine. 9446 if (!AddRec->isAffine()) 9447 return getCouldNotCompute(); 9448 9449 // If this is an affine expression, the execution count of this branch is 9450 // the minimum unsigned root of the following equation: 9451 // 9452 // Start + Step*N = 0 (mod 2^BW) 9453 // 9454 // equivalent to: 9455 // 9456 // Step*N = -Start (mod 2^BW) 9457 // 9458 // where BW is the common bit width of Start and Step. 9459 9460 // Get the initial value for the loop. 9461 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9462 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9463 9464 // For now we handle only constant steps. 9465 // 9466 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9467 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9468 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9469 // We have not yet seen any such cases. 9470 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9471 if (!StepC || StepC->getValue()->isZero()) 9472 return getCouldNotCompute(); 9473 9474 // For positive steps (counting up until unsigned overflow): 9475 // N = -Start/Step (as unsigned) 9476 // For negative steps (counting down to zero): 9477 // N = Start/-Step 9478 // First compute the unsigned distance from zero in the direction of Step. 9479 bool CountDown = StepC->getAPInt().isNegative(); 9480 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9481 9482 // Handle unitary steps, which cannot wraparound. 9483 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9484 // N = Distance (as unsigned) 9485 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9486 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9487 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9488 if (MaxBECountBase.ult(MaxBECount)) 9489 MaxBECount = MaxBECountBase; 9490 9491 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9492 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9493 // case, and see if we can improve the bound. 9494 // 9495 // Explicitly handling this here is necessary because getUnsignedRange 9496 // isn't context-sensitive; it doesn't know that we only care about the 9497 // range inside the loop. 9498 const SCEV *Zero = getZero(Distance->getType()); 9499 const SCEV *One = getOne(Distance->getType()); 9500 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9501 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9502 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9503 // as "unsigned_max(Distance + 1) - 1". 9504 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9505 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9506 } 9507 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9508 } 9509 9510 // If the condition controls loop exit (the loop exits only if the expression 9511 // is true) and the addition is no-wrap we can use unsigned divide to 9512 // compute the backedge count. In this case, the step may not divide the 9513 // distance, but we don't care because if the condition is "missed" the loop 9514 // will have undefined behavior due to wrapping. 9515 if (ControlsExit && AddRec->hasNoSelfWrap() && 9516 loopHasNoAbnormalExits(AddRec->getLoop())) { 9517 const SCEV *Exact = 9518 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9519 const SCEV *Max = getCouldNotCompute(); 9520 if (Exact != getCouldNotCompute()) { 9521 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9522 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9523 if (BaseMaxInt.ult(MaxInt)) 9524 Max = getConstant(BaseMaxInt); 9525 else 9526 Max = getConstant(MaxInt); 9527 } 9528 return ExitLimit(Exact, Max, false, Predicates); 9529 } 9530 9531 // Solve the general equation. 9532 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9533 getNegativeSCEV(Start), *this); 9534 const SCEV *M = E == getCouldNotCompute() 9535 ? E 9536 : getConstant(getUnsignedRangeMax(E)); 9537 return ExitLimit(E, M, false, Predicates); 9538 } 9539 9540 ScalarEvolution::ExitLimit 9541 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9542 // Loops that look like: while (X == 0) are very strange indeed. We don't 9543 // handle them yet except for the trivial case. This could be expanded in the 9544 // future as needed. 9545 9546 // If the value is a constant, check to see if it is known to be non-zero 9547 // already. If so, the backedge will execute zero times. 9548 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9549 if (!C->getValue()->isZero()) 9550 return getZero(C->getType()); 9551 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9552 } 9553 9554 // We could implement others, but I really doubt anyone writes loops like 9555 // this, and if they did, they would already be constant folded. 9556 return getCouldNotCompute(); 9557 } 9558 9559 std::pair<const BasicBlock *, const BasicBlock *> 9560 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9561 const { 9562 // If the block has a unique predecessor, then there is no path from the 9563 // predecessor to the block that does not go through the direct edge 9564 // from the predecessor to the block. 9565 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9566 return {Pred, BB}; 9567 9568 // A loop's header is defined to be a block that dominates the loop. 9569 // If the header has a unique predecessor outside the loop, it must be 9570 // a block that has exactly one successor that can reach the loop. 9571 if (const Loop *L = LI.getLoopFor(BB)) 9572 return {L->getLoopPredecessor(), L->getHeader()}; 9573 9574 return {nullptr, nullptr}; 9575 } 9576 9577 /// SCEV structural equivalence is usually sufficient for testing whether two 9578 /// expressions are equal, however for the purposes of looking for a condition 9579 /// guarding a loop, it can be useful to be a little more general, since a 9580 /// front-end may have replicated the controlling expression. 9581 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9582 // Quick check to see if they are the same SCEV. 9583 if (A == B) return true; 9584 9585 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9586 // Not all instructions that are "identical" compute the same value. For 9587 // instance, two distinct alloca instructions allocating the same type are 9588 // identical and do not read memory; but compute distinct values. 9589 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9590 }; 9591 9592 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9593 // two different instructions with the same value. Check for this case. 9594 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9595 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9596 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9597 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9598 if (ComputesEqualValues(AI, BI)) 9599 return true; 9600 9601 // Otherwise assume they may have a different value. 9602 return false; 9603 } 9604 9605 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9606 const SCEV *&LHS, const SCEV *&RHS, 9607 unsigned Depth) { 9608 bool Changed = false; 9609 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9610 // '0 != 0'. 9611 auto TrivialCase = [&](bool TriviallyTrue) { 9612 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9613 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9614 return true; 9615 }; 9616 // If we hit the max recursion limit bail out. 9617 if (Depth >= 3) 9618 return false; 9619 9620 // Canonicalize a constant to the right side. 9621 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9622 // Check for both operands constant. 9623 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9624 if (ConstantExpr::getICmp(Pred, 9625 LHSC->getValue(), 9626 RHSC->getValue())->isNullValue()) 9627 return TrivialCase(false); 9628 else 9629 return TrivialCase(true); 9630 } 9631 // Otherwise swap the operands to put the constant on the right. 9632 std::swap(LHS, RHS); 9633 Pred = ICmpInst::getSwappedPredicate(Pred); 9634 Changed = true; 9635 } 9636 9637 // If we're comparing an addrec with a value which is loop-invariant in the 9638 // addrec's loop, put the addrec on the left. Also make a dominance check, 9639 // as both operands could be addrecs loop-invariant in each other's loop. 9640 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9641 const Loop *L = AR->getLoop(); 9642 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9643 std::swap(LHS, RHS); 9644 Pred = ICmpInst::getSwappedPredicate(Pred); 9645 Changed = true; 9646 } 9647 } 9648 9649 // If there's a constant operand, canonicalize comparisons with boundary 9650 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9651 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9652 const APInt &RA = RC->getAPInt(); 9653 9654 bool SimplifiedByConstantRange = false; 9655 9656 if (!ICmpInst::isEquality(Pred)) { 9657 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9658 if (ExactCR.isFullSet()) 9659 return TrivialCase(true); 9660 else if (ExactCR.isEmptySet()) 9661 return TrivialCase(false); 9662 9663 APInt NewRHS; 9664 CmpInst::Predicate NewPred; 9665 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9666 ICmpInst::isEquality(NewPred)) { 9667 // We were able to convert an inequality to an equality. 9668 Pred = NewPred; 9669 RHS = getConstant(NewRHS); 9670 Changed = SimplifiedByConstantRange = true; 9671 } 9672 } 9673 9674 if (!SimplifiedByConstantRange) { 9675 switch (Pred) { 9676 default: 9677 break; 9678 case ICmpInst::ICMP_EQ: 9679 case ICmpInst::ICMP_NE: 9680 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9681 if (!RA) 9682 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9683 if (const SCEVMulExpr *ME = 9684 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9685 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9686 ME->getOperand(0)->isAllOnesValue()) { 9687 RHS = AE->getOperand(1); 9688 LHS = ME->getOperand(1); 9689 Changed = true; 9690 } 9691 break; 9692 9693 9694 // The "Should have been caught earlier!" messages refer to the fact 9695 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9696 // should have fired on the corresponding cases, and canonicalized the 9697 // check to trivial case. 9698 9699 case ICmpInst::ICMP_UGE: 9700 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9701 Pred = ICmpInst::ICMP_UGT; 9702 RHS = getConstant(RA - 1); 9703 Changed = true; 9704 break; 9705 case ICmpInst::ICMP_ULE: 9706 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9707 Pred = ICmpInst::ICMP_ULT; 9708 RHS = getConstant(RA + 1); 9709 Changed = true; 9710 break; 9711 case ICmpInst::ICMP_SGE: 9712 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9713 Pred = ICmpInst::ICMP_SGT; 9714 RHS = getConstant(RA - 1); 9715 Changed = true; 9716 break; 9717 case ICmpInst::ICMP_SLE: 9718 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9719 Pred = ICmpInst::ICMP_SLT; 9720 RHS = getConstant(RA + 1); 9721 Changed = true; 9722 break; 9723 } 9724 } 9725 } 9726 9727 // Check for obvious equality. 9728 if (HasSameValue(LHS, RHS)) { 9729 if (ICmpInst::isTrueWhenEqual(Pred)) 9730 return TrivialCase(true); 9731 if (ICmpInst::isFalseWhenEqual(Pred)) 9732 return TrivialCase(false); 9733 } 9734 9735 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9736 // adding or subtracting 1 from one of the operands. 9737 switch (Pred) { 9738 case ICmpInst::ICMP_SLE: 9739 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9740 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9741 SCEV::FlagNSW); 9742 Pred = ICmpInst::ICMP_SLT; 9743 Changed = true; 9744 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9745 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9746 SCEV::FlagNSW); 9747 Pred = ICmpInst::ICMP_SLT; 9748 Changed = true; 9749 } 9750 break; 9751 case ICmpInst::ICMP_SGE: 9752 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9753 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9754 SCEV::FlagNSW); 9755 Pred = ICmpInst::ICMP_SGT; 9756 Changed = true; 9757 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9758 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9759 SCEV::FlagNSW); 9760 Pred = ICmpInst::ICMP_SGT; 9761 Changed = true; 9762 } 9763 break; 9764 case ICmpInst::ICMP_ULE: 9765 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9766 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9767 SCEV::FlagNUW); 9768 Pred = ICmpInst::ICMP_ULT; 9769 Changed = true; 9770 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9771 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9772 Pred = ICmpInst::ICMP_ULT; 9773 Changed = true; 9774 } 9775 break; 9776 case ICmpInst::ICMP_UGE: 9777 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9778 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9779 Pred = ICmpInst::ICMP_UGT; 9780 Changed = true; 9781 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9782 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9783 SCEV::FlagNUW); 9784 Pred = ICmpInst::ICMP_UGT; 9785 Changed = true; 9786 } 9787 break; 9788 default: 9789 break; 9790 } 9791 9792 // TODO: More simplifications are possible here. 9793 9794 // Recursively simplify until we either hit a recursion limit or nothing 9795 // changes. 9796 if (Changed) 9797 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9798 9799 return Changed; 9800 } 9801 9802 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9803 return getSignedRangeMax(S).isNegative(); 9804 } 9805 9806 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9807 return getSignedRangeMin(S).isStrictlyPositive(); 9808 } 9809 9810 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9811 return !getSignedRangeMin(S).isNegative(); 9812 } 9813 9814 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9815 return !getSignedRangeMax(S).isStrictlyPositive(); 9816 } 9817 9818 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9819 return getUnsignedRangeMin(S) != 0; 9820 } 9821 9822 std::pair<const SCEV *, const SCEV *> 9823 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9824 // Compute SCEV on entry of loop L. 9825 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9826 if (Start == getCouldNotCompute()) 9827 return { Start, Start }; 9828 // Compute post increment SCEV for loop L. 9829 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9830 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9831 return { Start, PostInc }; 9832 } 9833 9834 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9835 const SCEV *LHS, const SCEV *RHS) { 9836 // First collect all loops. 9837 SmallPtrSet<const Loop *, 8> LoopsUsed; 9838 getUsedLoops(LHS, LoopsUsed); 9839 getUsedLoops(RHS, LoopsUsed); 9840 9841 if (LoopsUsed.empty()) 9842 return false; 9843 9844 // Domination relationship must be a linear order on collected loops. 9845 #ifndef NDEBUG 9846 for (auto *L1 : LoopsUsed) 9847 for (auto *L2 : LoopsUsed) 9848 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9849 DT.dominates(L2->getHeader(), L1->getHeader())) && 9850 "Domination relationship is not a linear order"); 9851 #endif 9852 9853 const Loop *MDL = 9854 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9855 [&](const Loop *L1, const Loop *L2) { 9856 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9857 }); 9858 9859 // Get init and post increment value for LHS. 9860 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9861 // if LHS contains unknown non-invariant SCEV then bail out. 9862 if (SplitLHS.first == getCouldNotCompute()) 9863 return false; 9864 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9865 // Get init and post increment value for RHS. 9866 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9867 // if RHS contains unknown non-invariant SCEV then bail out. 9868 if (SplitRHS.first == getCouldNotCompute()) 9869 return false; 9870 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9871 // It is possible that init SCEV contains an invariant load but it does 9872 // not dominate MDL and is not available at MDL loop entry, so we should 9873 // check it here. 9874 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9875 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9876 return false; 9877 9878 // It seems backedge guard check is faster than entry one so in some cases 9879 // it can speed up whole estimation by short circuit 9880 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9881 SplitRHS.second) && 9882 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9883 } 9884 9885 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9886 const SCEV *LHS, const SCEV *RHS) { 9887 // Canonicalize the inputs first. 9888 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9889 9890 if (isKnownViaInduction(Pred, LHS, RHS)) 9891 return true; 9892 9893 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9894 return true; 9895 9896 // Otherwise see what can be done with some simple reasoning. 9897 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9898 } 9899 9900 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9901 const SCEV *LHS, 9902 const SCEV *RHS) { 9903 if (isKnownPredicate(Pred, LHS, RHS)) 9904 return true; 9905 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9906 return false; 9907 return None; 9908 } 9909 9910 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9911 const SCEV *LHS, const SCEV *RHS, 9912 const Instruction *CtxI) { 9913 // TODO: Analyze guards and assumes from Context's block. 9914 return isKnownPredicate(Pred, LHS, RHS) || 9915 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 9916 } 9917 9918 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 9919 const SCEV *LHS, 9920 const SCEV *RHS, 9921 const Instruction *CtxI) { 9922 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9923 if (KnownWithoutContext) 9924 return KnownWithoutContext; 9925 9926 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 9927 return true; 9928 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 9929 ICmpInst::getInversePredicate(Pred), 9930 LHS, RHS)) 9931 return false; 9932 return None; 9933 } 9934 9935 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9936 const SCEVAddRecExpr *LHS, 9937 const SCEV *RHS) { 9938 const Loop *L = LHS->getLoop(); 9939 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9940 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9941 } 9942 9943 Optional<ScalarEvolution::MonotonicPredicateType> 9944 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9945 ICmpInst::Predicate Pred) { 9946 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9947 9948 #ifndef NDEBUG 9949 // Verify an invariant: inverting the predicate should turn a monotonically 9950 // increasing change to a monotonically decreasing one, and vice versa. 9951 if (Result) { 9952 auto ResultSwapped = 9953 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9954 9955 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9956 assert(ResultSwapped.getValue() != Result.getValue() && 9957 "monotonicity should flip as we flip the predicate"); 9958 } 9959 #endif 9960 9961 return Result; 9962 } 9963 9964 Optional<ScalarEvolution::MonotonicPredicateType> 9965 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9966 ICmpInst::Predicate Pred) { 9967 // A zero step value for LHS means the induction variable is essentially a 9968 // loop invariant value. We don't really depend on the predicate actually 9969 // flipping from false to true (for increasing predicates, and the other way 9970 // around for decreasing predicates), all we care about is that *if* the 9971 // predicate changes then it only changes from false to true. 9972 // 9973 // A zero step value in itself is not very useful, but there may be places 9974 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9975 // as general as possible. 9976 9977 // Only handle LE/LT/GE/GT predicates. 9978 if (!ICmpInst::isRelational(Pred)) 9979 return None; 9980 9981 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9982 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9983 "Should be greater or less!"); 9984 9985 // Check that AR does not wrap. 9986 if (ICmpInst::isUnsigned(Pred)) { 9987 if (!LHS->hasNoUnsignedWrap()) 9988 return None; 9989 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9990 } else { 9991 assert(ICmpInst::isSigned(Pred) && 9992 "Relational predicate is either signed or unsigned!"); 9993 if (!LHS->hasNoSignedWrap()) 9994 return None; 9995 9996 const SCEV *Step = LHS->getStepRecurrence(*this); 9997 9998 if (isKnownNonNegative(Step)) 9999 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10000 10001 if (isKnownNonPositive(Step)) 10002 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10003 10004 return None; 10005 } 10006 } 10007 10008 Optional<ScalarEvolution::LoopInvariantPredicate> 10009 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10010 const SCEV *LHS, const SCEV *RHS, 10011 const Loop *L) { 10012 10013 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10014 if (!isLoopInvariant(RHS, L)) { 10015 if (!isLoopInvariant(LHS, L)) 10016 return None; 10017 10018 std::swap(LHS, RHS); 10019 Pred = ICmpInst::getSwappedPredicate(Pred); 10020 } 10021 10022 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10023 if (!ArLHS || ArLHS->getLoop() != L) 10024 return None; 10025 10026 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10027 if (!MonotonicType) 10028 return None; 10029 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10030 // true as the loop iterates, and the backedge is control dependent on 10031 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10032 // 10033 // * if the predicate was false in the first iteration then the predicate 10034 // is never evaluated again, since the loop exits without taking the 10035 // backedge. 10036 // * if the predicate was true in the first iteration then it will 10037 // continue to be true for all future iterations since it is 10038 // monotonically increasing. 10039 // 10040 // For both the above possibilities, we can replace the loop varying 10041 // predicate with its value on the first iteration of the loop (which is 10042 // loop invariant). 10043 // 10044 // A similar reasoning applies for a monotonically decreasing predicate, by 10045 // replacing true with false and false with true in the above two bullets. 10046 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10047 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10048 10049 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10050 return None; 10051 10052 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10053 } 10054 10055 Optional<ScalarEvolution::LoopInvariantPredicate> 10056 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10057 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10058 const Instruction *CtxI, const SCEV *MaxIter) { 10059 // Try to prove the following set of facts: 10060 // - The predicate is monotonic in the iteration space. 10061 // - If the check does not fail on the 1st iteration: 10062 // - No overflow will happen during first MaxIter iterations; 10063 // - It will not fail on the MaxIter'th iteration. 10064 // If the check does fail on the 1st iteration, we leave the loop and no 10065 // other checks matter. 10066 10067 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10068 if (!isLoopInvariant(RHS, L)) { 10069 if (!isLoopInvariant(LHS, L)) 10070 return None; 10071 10072 std::swap(LHS, RHS); 10073 Pred = ICmpInst::getSwappedPredicate(Pred); 10074 } 10075 10076 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10077 if (!AR || AR->getLoop() != L) 10078 return None; 10079 10080 // The predicate must be relational (i.e. <, <=, >=, >). 10081 if (!ICmpInst::isRelational(Pred)) 10082 return None; 10083 10084 // TODO: Support steps other than +/- 1. 10085 const SCEV *Step = AR->getStepRecurrence(*this); 10086 auto *One = getOne(Step->getType()); 10087 auto *MinusOne = getNegativeSCEV(One); 10088 if (Step != One && Step != MinusOne) 10089 return None; 10090 10091 // Type mismatch here means that MaxIter is potentially larger than max 10092 // unsigned value in start type, which mean we cannot prove no wrap for the 10093 // indvar. 10094 if (AR->getType() != MaxIter->getType()) 10095 return None; 10096 10097 // Value of IV on suggested last iteration. 10098 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10099 // Does it still meet the requirement? 10100 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10101 return None; 10102 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10103 // not exceed max unsigned value of this type), this effectively proves 10104 // that there is no wrap during the iteration. To prove that there is no 10105 // signed/unsigned wrap, we need to check that 10106 // Start <= Last for step = 1 or Start >= Last for step = -1. 10107 ICmpInst::Predicate NoOverflowPred = 10108 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10109 if (Step == MinusOne) 10110 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10111 const SCEV *Start = AR->getStart(); 10112 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10113 return None; 10114 10115 // Everything is fine. 10116 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10117 } 10118 10119 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10120 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10121 if (HasSameValue(LHS, RHS)) 10122 return ICmpInst::isTrueWhenEqual(Pred); 10123 10124 // This code is split out from isKnownPredicate because it is called from 10125 // within isLoopEntryGuardedByCond. 10126 10127 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10128 const ConstantRange &RangeRHS) { 10129 return RangeLHS.icmp(Pred, RangeRHS); 10130 }; 10131 10132 // The check at the top of the function catches the case where the values are 10133 // known to be equal. 10134 if (Pred == CmpInst::ICMP_EQ) 10135 return false; 10136 10137 if (Pred == CmpInst::ICMP_NE) { 10138 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10139 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10140 return true; 10141 auto *Diff = getMinusSCEV(LHS, RHS); 10142 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10143 } 10144 10145 if (CmpInst::isSigned(Pred)) 10146 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10147 10148 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10149 } 10150 10151 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10152 const SCEV *LHS, 10153 const SCEV *RHS) { 10154 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10155 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10156 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10157 // OutC1 and OutC2. 10158 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10159 APInt &OutC1, APInt &OutC2, 10160 SCEV::NoWrapFlags ExpectedFlags) { 10161 const SCEV *XNonConstOp, *XConstOp; 10162 const SCEV *YNonConstOp, *YConstOp; 10163 SCEV::NoWrapFlags XFlagsPresent; 10164 SCEV::NoWrapFlags YFlagsPresent; 10165 10166 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10167 XConstOp = getZero(X->getType()); 10168 XNonConstOp = X; 10169 XFlagsPresent = ExpectedFlags; 10170 } 10171 if (!isa<SCEVConstant>(XConstOp) || 10172 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10173 return false; 10174 10175 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10176 YConstOp = getZero(Y->getType()); 10177 YNonConstOp = Y; 10178 YFlagsPresent = ExpectedFlags; 10179 } 10180 10181 if (!isa<SCEVConstant>(YConstOp) || 10182 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10183 return false; 10184 10185 if (YNonConstOp != XNonConstOp) 10186 return false; 10187 10188 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10189 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10190 10191 return true; 10192 }; 10193 10194 APInt C1; 10195 APInt C2; 10196 10197 switch (Pred) { 10198 default: 10199 break; 10200 10201 case ICmpInst::ICMP_SGE: 10202 std::swap(LHS, RHS); 10203 LLVM_FALLTHROUGH; 10204 case ICmpInst::ICMP_SLE: 10205 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10206 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10207 return true; 10208 10209 break; 10210 10211 case ICmpInst::ICMP_SGT: 10212 std::swap(LHS, RHS); 10213 LLVM_FALLTHROUGH; 10214 case ICmpInst::ICMP_SLT: 10215 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10216 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10217 return true; 10218 10219 break; 10220 10221 case ICmpInst::ICMP_UGE: 10222 std::swap(LHS, RHS); 10223 LLVM_FALLTHROUGH; 10224 case ICmpInst::ICMP_ULE: 10225 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10226 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10227 return true; 10228 10229 break; 10230 10231 case ICmpInst::ICMP_UGT: 10232 std::swap(LHS, RHS); 10233 LLVM_FALLTHROUGH; 10234 case ICmpInst::ICMP_ULT: 10235 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10236 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10237 return true; 10238 break; 10239 } 10240 10241 return false; 10242 } 10243 10244 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10245 const SCEV *LHS, 10246 const SCEV *RHS) { 10247 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10248 return false; 10249 10250 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10251 // the stack can result in exponential time complexity. 10252 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10253 10254 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10255 // 10256 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10257 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10258 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10259 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10260 // use isKnownPredicate later if needed. 10261 return isKnownNonNegative(RHS) && 10262 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10263 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10264 } 10265 10266 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10267 ICmpInst::Predicate Pred, 10268 const SCEV *LHS, const SCEV *RHS) { 10269 // No need to even try if we know the module has no guards. 10270 if (!HasGuards) 10271 return false; 10272 10273 return any_of(*BB, [&](const Instruction &I) { 10274 using namespace llvm::PatternMatch; 10275 10276 Value *Condition; 10277 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10278 m_Value(Condition))) && 10279 isImpliedCond(Pred, LHS, RHS, Condition, false); 10280 }); 10281 } 10282 10283 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10284 /// protected by a conditional between LHS and RHS. This is used to 10285 /// to eliminate casts. 10286 bool 10287 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10288 ICmpInst::Predicate Pred, 10289 const SCEV *LHS, const SCEV *RHS) { 10290 // Interpret a null as meaning no loop, where there is obviously no guard 10291 // (interprocedural conditions notwithstanding). 10292 if (!L) return true; 10293 10294 if (VerifyIR) 10295 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10296 "This cannot be done on broken IR!"); 10297 10298 10299 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10300 return true; 10301 10302 BasicBlock *Latch = L->getLoopLatch(); 10303 if (!Latch) 10304 return false; 10305 10306 BranchInst *LoopContinuePredicate = 10307 dyn_cast<BranchInst>(Latch->getTerminator()); 10308 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10309 isImpliedCond(Pred, LHS, RHS, 10310 LoopContinuePredicate->getCondition(), 10311 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10312 return true; 10313 10314 // We don't want more than one activation of the following loops on the stack 10315 // -- that can lead to O(n!) time complexity. 10316 if (WalkingBEDominatingConds) 10317 return false; 10318 10319 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10320 10321 // See if we can exploit a trip count to prove the predicate. 10322 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10323 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10324 if (LatchBECount != getCouldNotCompute()) { 10325 // We know that Latch branches back to the loop header exactly 10326 // LatchBECount times. This means the backdege condition at Latch is 10327 // equivalent to "{0,+,1} u< LatchBECount". 10328 Type *Ty = LatchBECount->getType(); 10329 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10330 const SCEV *LoopCounter = 10331 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10332 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10333 LatchBECount)) 10334 return true; 10335 } 10336 10337 // Check conditions due to any @llvm.assume intrinsics. 10338 for (auto &AssumeVH : AC.assumptions()) { 10339 if (!AssumeVH) 10340 continue; 10341 auto *CI = cast<CallInst>(AssumeVH); 10342 if (!DT.dominates(CI, Latch->getTerminator())) 10343 continue; 10344 10345 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10346 return true; 10347 } 10348 10349 // If the loop is not reachable from the entry block, we risk running into an 10350 // infinite loop as we walk up into the dom tree. These loops do not matter 10351 // anyway, so we just return a conservative answer when we see them. 10352 if (!DT.isReachableFromEntry(L->getHeader())) 10353 return false; 10354 10355 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10356 return true; 10357 10358 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10359 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10360 assert(DTN && "should reach the loop header before reaching the root!"); 10361 10362 BasicBlock *BB = DTN->getBlock(); 10363 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10364 return true; 10365 10366 BasicBlock *PBB = BB->getSinglePredecessor(); 10367 if (!PBB) 10368 continue; 10369 10370 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10371 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10372 continue; 10373 10374 Value *Condition = ContinuePredicate->getCondition(); 10375 10376 // If we have an edge `E` within the loop body that dominates the only 10377 // latch, the condition guarding `E` also guards the backedge. This 10378 // reasoning works only for loops with a single latch. 10379 10380 BasicBlockEdge DominatingEdge(PBB, BB); 10381 if (DominatingEdge.isSingleEdge()) { 10382 // We're constructively (and conservatively) enumerating edges within the 10383 // loop body that dominate the latch. The dominator tree better agree 10384 // with us on this: 10385 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10386 10387 if (isImpliedCond(Pred, LHS, RHS, Condition, 10388 BB != ContinuePredicate->getSuccessor(0))) 10389 return true; 10390 } 10391 } 10392 10393 return false; 10394 } 10395 10396 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10397 ICmpInst::Predicate Pred, 10398 const SCEV *LHS, 10399 const SCEV *RHS) { 10400 if (VerifyIR) 10401 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10402 "This cannot be done on broken IR!"); 10403 10404 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10405 // the facts (a >= b && a != b) separately. A typical situation is when the 10406 // non-strict comparison is known from ranges and non-equality is known from 10407 // dominating predicates. If we are proving strict comparison, we always try 10408 // to prove non-equality and non-strict comparison separately. 10409 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10410 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10411 bool ProvedNonStrictComparison = false; 10412 bool ProvedNonEquality = false; 10413 10414 auto SplitAndProve = 10415 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10416 if (!ProvedNonStrictComparison) 10417 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10418 if (!ProvedNonEquality) 10419 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10420 if (ProvedNonStrictComparison && ProvedNonEquality) 10421 return true; 10422 return false; 10423 }; 10424 10425 if (ProvingStrictComparison) { 10426 auto ProofFn = [&](ICmpInst::Predicate P) { 10427 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10428 }; 10429 if (SplitAndProve(ProofFn)) 10430 return true; 10431 } 10432 10433 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10434 auto ProveViaGuard = [&](const BasicBlock *Block) { 10435 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10436 return true; 10437 if (ProvingStrictComparison) { 10438 auto ProofFn = [&](ICmpInst::Predicate P) { 10439 return isImpliedViaGuard(Block, P, LHS, RHS); 10440 }; 10441 if (SplitAndProve(ProofFn)) 10442 return true; 10443 } 10444 return false; 10445 }; 10446 10447 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10448 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10449 const Instruction *CtxI = &BB->front(); 10450 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10451 return true; 10452 if (ProvingStrictComparison) { 10453 auto ProofFn = [&](ICmpInst::Predicate P) { 10454 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10455 }; 10456 if (SplitAndProve(ProofFn)) 10457 return true; 10458 } 10459 return false; 10460 }; 10461 10462 // Starting at the block's predecessor, climb up the predecessor chain, as long 10463 // as there are predecessors that can be found that have unique successors 10464 // leading to the original block. 10465 const Loop *ContainingLoop = LI.getLoopFor(BB); 10466 const BasicBlock *PredBB; 10467 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10468 PredBB = ContainingLoop->getLoopPredecessor(); 10469 else 10470 PredBB = BB->getSinglePredecessor(); 10471 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10472 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10473 if (ProveViaGuard(Pair.first)) 10474 return true; 10475 10476 const BranchInst *LoopEntryPredicate = 10477 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10478 if (!LoopEntryPredicate || 10479 LoopEntryPredicate->isUnconditional()) 10480 continue; 10481 10482 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10483 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10484 return true; 10485 } 10486 10487 // Check conditions due to any @llvm.assume intrinsics. 10488 for (auto &AssumeVH : AC.assumptions()) { 10489 if (!AssumeVH) 10490 continue; 10491 auto *CI = cast<CallInst>(AssumeVH); 10492 if (!DT.dominates(CI, BB)) 10493 continue; 10494 10495 if (ProveViaCond(CI->getArgOperand(0), false)) 10496 return true; 10497 } 10498 10499 return false; 10500 } 10501 10502 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10503 ICmpInst::Predicate Pred, 10504 const SCEV *LHS, 10505 const SCEV *RHS) { 10506 // Interpret a null as meaning no loop, where there is obviously no guard 10507 // (interprocedural conditions notwithstanding). 10508 if (!L) 10509 return false; 10510 10511 // Both LHS and RHS must be available at loop entry. 10512 assert(isAvailableAtLoopEntry(LHS, L) && 10513 "LHS is not available at Loop Entry"); 10514 assert(isAvailableAtLoopEntry(RHS, L) && 10515 "RHS is not available at Loop Entry"); 10516 10517 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10518 return true; 10519 10520 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10521 } 10522 10523 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10524 const SCEV *RHS, 10525 const Value *FoundCondValue, bool Inverse, 10526 const Instruction *CtxI) { 10527 // False conditions implies anything. Do not bother analyzing it further. 10528 if (FoundCondValue == 10529 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10530 return true; 10531 10532 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10533 return false; 10534 10535 auto ClearOnExit = 10536 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10537 10538 // Recursively handle And and Or conditions. 10539 const Value *Op0, *Op1; 10540 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10541 if (!Inverse) 10542 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10543 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10544 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10545 if (Inverse) 10546 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10547 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10548 } 10549 10550 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10551 if (!ICI) return false; 10552 10553 // Now that we found a conditional branch that dominates the loop or controls 10554 // the loop latch. Check to see if it is the comparison we are looking for. 10555 ICmpInst::Predicate FoundPred; 10556 if (Inverse) 10557 FoundPred = ICI->getInversePredicate(); 10558 else 10559 FoundPred = ICI->getPredicate(); 10560 10561 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10562 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10563 10564 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10565 } 10566 10567 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10568 const SCEV *RHS, 10569 ICmpInst::Predicate FoundPred, 10570 const SCEV *FoundLHS, const SCEV *FoundRHS, 10571 const Instruction *CtxI) { 10572 // Balance the types. 10573 if (getTypeSizeInBits(LHS->getType()) < 10574 getTypeSizeInBits(FoundLHS->getType())) { 10575 // For unsigned and equality predicates, try to prove that both found 10576 // operands fit into narrow unsigned range. If so, try to prove facts in 10577 // narrow types. 10578 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10579 auto *NarrowType = LHS->getType(); 10580 auto *WideType = FoundLHS->getType(); 10581 auto BitWidth = getTypeSizeInBits(NarrowType); 10582 const SCEV *MaxValue = getZeroExtendExpr( 10583 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10584 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10585 MaxValue) && 10586 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10587 MaxValue)) { 10588 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10589 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10590 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10591 TruncFoundRHS, CtxI)) 10592 return true; 10593 } 10594 } 10595 10596 if (LHS->getType()->isPointerTy()) 10597 return false; 10598 if (CmpInst::isSigned(Pred)) { 10599 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10600 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10601 } else { 10602 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10603 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10604 } 10605 } else if (getTypeSizeInBits(LHS->getType()) > 10606 getTypeSizeInBits(FoundLHS->getType())) { 10607 if (FoundLHS->getType()->isPointerTy()) 10608 return false; 10609 if (CmpInst::isSigned(FoundPred)) { 10610 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10611 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10612 } else { 10613 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10614 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10615 } 10616 } 10617 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10618 FoundRHS, CtxI); 10619 } 10620 10621 bool ScalarEvolution::isImpliedCondBalancedTypes( 10622 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10623 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10624 const Instruction *CtxI) { 10625 assert(getTypeSizeInBits(LHS->getType()) == 10626 getTypeSizeInBits(FoundLHS->getType()) && 10627 "Types should be balanced!"); 10628 // Canonicalize the query to match the way instcombine will have 10629 // canonicalized the comparison. 10630 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10631 if (LHS == RHS) 10632 return CmpInst::isTrueWhenEqual(Pred); 10633 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10634 if (FoundLHS == FoundRHS) 10635 return CmpInst::isFalseWhenEqual(FoundPred); 10636 10637 // Check to see if we can make the LHS or RHS match. 10638 if (LHS == FoundRHS || RHS == FoundLHS) { 10639 if (isa<SCEVConstant>(RHS)) { 10640 std::swap(FoundLHS, FoundRHS); 10641 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10642 } else { 10643 std::swap(LHS, RHS); 10644 Pred = ICmpInst::getSwappedPredicate(Pred); 10645 } 10646 } 10647 10648 // Check whether the found predicate is the same as the desired predicate. 10649 if (FoundPred == Pred) 10650 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10651 10652 // Check whether swapping the found predicate makes it the same as the 10653 // desired predicate. 10654 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10655 // We can write the implication 10656 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10657 // using one of the following ways: 10658 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10659 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10660 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10661 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10662 // Forms 1. and 2. require swapping the operands of one condition. Don't 10663 // do this if it would break canonical constant/addrec ordering. 10664 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10665 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10666 CtxI); 10667 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10668 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 10669 10670 // There's no clear preference between forms 3. and 4., try both. Avoid 10671 // forming getNotSCEV of pointer values as the resulting subtract is 10672 // not legal. 10673 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 10674 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10675 FoundLHS, FoundRHS, CtxI)) 10676 return true; 10677 10678 if (!FoundLHS->getType()->isPointerTy() && 10679 !FoundRHS->getType()->isPointerTy() && 10680 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10681 getNotSCEV(FoundRHS), CtxI)) 10682 return true; 10683 10684 return false; 10685 } 10686 10687 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 10688 CmpInst::Predicate P2) { 10689 assert(P1 != P2 && "Handled earlier!"); 10690 return CmpInst::isRelational(P2) && 10691 P1 == CmpInst::getFlippedSignednessPredicate(P2); 10692 }; 10693 if (IsSignFlippedPredicate(Pred, FoundPred)) { 10694 // Unsigned comparison is the same as signed comparison when both the 10695 // operands are non-negative or negative. 10696 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 10697 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 10698 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10699 // Create local copies that we can freely swap and canonicalize our 10700 // conditions to "le/lt". 10701 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 10702 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 10703 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 10704 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 10705 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 10706 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 10707 std::swap(CanonicalLHS, CanonicalRHS); 10708 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 10709 } 10710 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 10711 "Must be!"); 10712 assert((ICmpInst::isLT(CanonicalFoundPred) || 10713 ICmpInst::isLE(CanonicalFoundPred)) && 10714 "Must be!"); 10715 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 10716 // Use implication: 10717 // x <u y && y >=s 0 --> x <s y. 10718 // If we can prove the left part, the right part is also proven. 10719 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10720 CanonicalRHS, CanonicalFoundLHS, 10721 CanonicalFoundRHS); 10722 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 10723 // Use implication: 10724 // x <s y && y <s 0 --> x <u y. 10725 // If we can prove the left part, the right part is also proven. 10726 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10727 CanonicalRHS, CanonicalFoundLHS, 10728 CanonicalFoundRHS); 10729 } 10730 10731 // Check if we can make progress by sharpening ranges. 10732 if (FoundPred == ICmpInst::ICMP_NE && 10733 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10734 10735 const SCEVConstant *C = nullptr; 10736 const SCEV *V = nullptr; 10737 10738 if (isa<SCEVConstant>(FoundLHS)) { 10739 C = cast<SCEVConstant>(FoundLHS); 10740 V = FoundRHS; 10741 } else { 10742 C = cast<SCEVConstant>(FoundRHS); 10743 V = FoundLHS; 10744 } 10745 10746 // The guarding predicate tells us that C != V. If the known range 10747 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10748 // range we consider has to correspond to same signedness as the 10749 // predicate we're interested in folding. 10750 10751 APInt Min = ICmpInst::isSigned(Pred) ? 10752 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10753 10754 if (Min == C->getAPInt()) { 10755 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10756 // This is true even if (Min + 1) wraps around -- in case of 10757 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10758 10759 APInt SharperMin = Min + 1; 10760 10761 switch (Pred) { 10762 case ICmpInst::ICMP_SGE: 10763 case ICmpInst::ICMP_UGE: 10764 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10765 // RHS, we're done. 10766 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10767 CtxI)) 10768 return true; 10769 LLVM_FALLTHROUGH; 10770 10771 case ICmpInst::ICMP_SGT: 10772 case ICmpInst::ICMP_UGT: 10773 // We know from the range information that (V `Pred` Min || 10774 // V == Min). We know from the guarding condition that !(V 10775 // == Min). This gives us 10776 // 10777 // V `Pred` Min || V == Min && !(V == Min) 10778 // => V `Pred` Min 10779 // 10780 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10781 10782 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 10783 return true; 10784 break; 10785 10786 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10787 case ICmpInst::ICMP_SLE: 10788 case ICmpInst::ICMP_ULE: 10789 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10790 LHS, V, getConstant(SharperMin), CtxI)) 10791 return true; 10792 LLVM_FALLTHROUGH; 10793 10794 case ICmpInst::ICMP_SLT: 10795 case ICmpInst::ICMP_ULT: 10796 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10797 LHS, V, getConstant(Min), CtxI)) 10798 return true; 10799 break; 10800 10801 default: 10802 // No change 10803 break; 10804 } 10805 } 10806 } 10807 10808 // Check whether the actual condition is beyond sufficient. 10809 if (FoundPred == ICmpInst::ICMP_EQ) 10810 if (ICmpInst::isTrueWhenEqual(Pred)) 10811 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10812 return true; 10813 if (Pred == ICmpInst::ICMP_NE) 10814 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10815 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10816 return true; 10817 10818 // Otherwise assume the worst. 10819 return false; 10820 } 10821 10822 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10823 const SCEV *&L, const SCEV *&R, 10824 SCEV::NoWrapFlags &Flags) { 10825 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10826 if (!AE || AE->getNumOperands() != 2) 10827 return false; 10828 10829 L = AE->getOperand(0); 10830 R = AE->getOperand(1); 10831 Flags = AE->getNoWrapFlags(); 10832 return true; 10833 } 10834 10835 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10836 const SCEV *Less) { 10837 // We avoid subtracting expressions here because this function is usually 10838 // fairly deep in the call stack (i.e. is called many times). 10839 10840 // X - X = 0. 10841 if (More == Less) 10842 return APInt(getTypeSizeInBits(More->getType()), 0); 10843 10844 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10845 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10846 const auto *MAR = cast<SCEVAddRecExpr>(More); 10847 10848 if (LAR->getLoop() != MAR->getLoop()) 10849 return None; 10850 10851 // We look at affine expressions only; not for correctness but to keep 10852 // getStepRecurrence cheap. 10853 if (!LAR->isAffine() || !MAR->isAffine()) 10854 return None; 10855 10856 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10857 return None; 10858 10859 Less = LAR->getStart(); 10860 More = MAR->getStart(); 10861 10862 // fall through 10863 } 10864 10865 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10866 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10867 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10868 return M - L; 10869 } 10870 10871 SCEV::NoWrapFlags Flags; 10872 const SCEV *LLess = nullptr, *RLess = nullptr; 10873 const SCEV *LMore = nullptr, *RMore = nullptr; 10874 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10875 // Compare (X + C1) vs X. 10876 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10877 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10878 if (RLess == More) 10879 return -(C1->getAPInt()); 10880 10881 // Compare X vs (X + C2). 10882 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10883 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10884 if (RMore == Less) 10885 return C2->getAPInt(); 10886 10887 // Compare (X + C1) vs (X + C2). 10888 if (C1 && C2 && RLess == RMore) 10889 return C2->getAPInt() - C1->getAPInt(); 10890 10891 return None; 10892 } 10893 10894 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10895 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10896 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 10897 // Try to recognize the following pattern: 10898 // 10899 // FoundRHS = ... 10900 // ... 10901 // loop: 10902 // FoundLHS = {Start,+,W} 10903 // context_bb: // Basic block from the same loop 10904 // known(Pred, FoundLHS, FoundRHS) 10905 // 10906 // If some predicate is known in the context of a loop, it is also known on 10907 // each iteration of this loop, including the first iteration. Therefore, in 10908 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10909 // prove the original pred using this fact. 10910 if (!CtxI) 10911 return false; 10912 const BasicBlock *ContextBB = CtxI->getParent(); 10913 // Make sure AR varies in the context block. 10914 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10915 const Loop *L = AR->getLoop(); 10916 // Make sure that context belongs to the loop and executes on 1st iteration 10917 // (if it ever executes at all). 10918 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10919 return false; 10920 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10921 return false; 10922 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10923 } 10924 10925 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10926 const Loop *L = AR->getLoop(); 10927 // Make sure that context belongs to the loop and executes on 1st iteration 10928 // (if it ever executes at all). 10929 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10930 return false; 10931 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10932 return false; 10933 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10934 } 10935 10936 return false; 10937 } 10938 10939 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10940 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10941 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10942 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10943 return false; 10944 10945 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10946 if (!AddRecLHS) 10947 return false; 10948 10949 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10950 if (!AddRecFoundLHS) 10951 return false; 10952 10953 // We'd like to let SCEV reason about control dependencies, so we constrain 10954 // both the inequalities to be about add recurrences on the same loop. This 10955 // way we can use isLoopEntryGuardedByCond later. 10956 10957 const Loop *L = AddRecFoundLHS->getLoop(); 10958 if (L != AddRecLHS->getLoop()) 10959 return false; 10960 10961 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10962 // 10963 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10964 // ... (2) 10965 // 10966 // Informal proof for (2), assuming (1) [*]: 10967 // 10968 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10969 // 10970 // Then 10971 // 10972 // FoundLHS s< FoundRHS s< INT_MIN - C 10973 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10974 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10975 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10976 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10977 // <=> FoundLHS + C s< FoundRHS + C 10978 // 10979 // [*]: (1) can be proved by ruling out overflow. 10980 // 10981 // [**]: This can be proved by analyzing all the four possibilities: 10982 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10983 // (A s>= 0, B s>= 0). 10984 // 10985 // Note: 10986 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10987 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10988 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10989 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10990 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10991 // C)". 10992 10993 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10994 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10995 if (!LDiff || !RDiff || *LDiff != *RDiff) 10996 return false; 10997 10998 if (LDiff->isMinValue()) 10999 return true; 11000 11001 APInt FoundRHSLimit; 11002 11003 if (Pred == CmpInst::ICMP_ULT) { 11004 FoundRHSLimit = -(*RDiff); 11005 } else { 11006 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11007 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11008 } 11009 11010 // Try to prove (1) or (2), as needed. 11011 return isAvailableAtLoopEntry(FoundRHS, L) && 11012 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11013 getConstant(FoundRHSLimit)); 11014 } 11015 11016 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11017 const SCEV *LHS, const SCEV *RHS, 11018 const SCEV *FoundLHS, 11019 const SCEV *FoundRHS, unsigned Depth) { 11020 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11021 11022 auto ClearOnExit = make_scope_exit([&]() { 11023 if (LPhi) { 11024 bool Erased = PendingMerges.erase(LPhi); 11025 assert(Erased && "Failed to erase LPhi!"); 11026 (void)Erased; 11027 } 11028 if (RPhi) { 11029 bool Erased = PendingMerges.erase(RPhi); 11030 assert(Erased && "Failed to erase RPhi!"); 11031 (void)Erased; 11032 } 11033 }); 11034 11035 // Find respective Phis and check that they are not being pending. 11036 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11037 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11038 if (!PendingMerges.insert(Phi).second) 11039 return false; 11040 LPhi = Phi; 11041 } 11042 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11043 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11044 // If we detect a loop of Phi nodes being processed by this method, for 11045 // example: 11046 // 11047 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11048 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11049 // 11050 // we don't want to deal with a case that complex, so return conservative 11051 // answer false. 11052 if (!PendingMerges.insert(Phi).second) 11053 return false; 11054 RPhi = Phi; 11055 } 11056 11057 // If none of LHS, RHS is a Phi, nothing to do here. 11058 if (!LPhi && !RPhi) 11059 return false; 11060 11061 // If there is a SCEVUnknown Phi we are interested in, make it left. 11062 if (!LPhi) { 11063 std::swap(LHS, RHS); 11064 std::swap(FoundLHS, FoundRHS); 11065 std::swap(LPhi, RPhi); 11066 Pred = ICmpInst::getSwappedPredicate(Pred); 11067 } 11068 11069 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11070 const BasicBlock *LBB = LPhi->getParent(); 11071 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11072 11073 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11074 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11075 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11076 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11077 }; 11078 11079 if (RPhi && RPhi->getParent() == LBB) { 11080 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11081 // If we compare two Phis from the same block, and for each entry block 11082 // the predicate is true for incoming values from this block, then the 11083 // predicate is also true for the Phis. 11084 for (const BasicBlock *IncBB : predecessors(LBB)) { 11085 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11086 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11087 if (!ProvedEasily(L, R)) 11088 return false; 11089 } 11090 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11091 // Case two: RHS is also a Phi from the same basic block, and it is an 11092 // AddRec. It means that there is a loop which has both AddRec and Unknown 11093 // PHIs, for it we can compare incoming values of AddRec from above the loop 11094 // and latch with their respective incoming values of LPhi. 11095 // TODO: Generalize to handle loops with many inputs in a header. 11096 if (LPhi->getNumIncomingValues() != 2) return false; 11097 11098 auto *RLoop = RAR->getLoop(); 11099 auto *Predecessor = RLoop->getLoopPredecessor(); 11100 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11101 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11102 if (!ProvedEasily(L1, RAR->getStart())) 11103 return false; 11104 auto *Latch = RLoop->getLoopLatch(); 11105 assert(Latch && "Loop with AddRec with no latch?"); 11106 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11107 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11108 return false; 11109 } else { 11110 // In all other cases go over inputs of LHS and compare each of them to RHS, 11111 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11112 // At this point RHS is either a non-Phi, or it is a Phi from some block 11113 // different from LBB. 11114 for (const BasicBlock *IncBB : predecessors(LBB)) { 11115 // Check that RHS is available in this block. 11116 if (!dominates(RHS, IncBB)) 11117 return false; 11118 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11119 // Make sure L does not refer to a value from a potentially previous 11120 // iteration of a loop. 11121 if (!properlyDominates(L, IncBB)) 11122 return false; 11123 if (!ProvedEasily(L, RHS)) 11124 return false; 11125 } 11126 } 11127 return true; 11128 } 11129 11130 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11131 const SCEV *LHS, const SCEV *RHS, 11132 const SCEV *FoundLHS, 11133 const SCEV *FoundRHS, 11134 const Instruction *CtxI) { 11135 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11136 return true; 11137 11138 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11139 return true; 11140 11141 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11142 CtxI)) 11143 return true; 11144 11145 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11146 FoundLHS, FoundRHS); 11147 } 11148 11149 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11150 template <typename MinMaxExprType> 11151 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11152 const SCEV *Candidate) { 11153 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11154 if (!MinMaxExpr) 11155 return false; 11156 11157 return is_contained(MinMaxExpr->operands(), Candidate); 11158 } 11159 11160 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11161 ICmpInst::Predicate Pred, 11162 const SCEV *LHS, const SCEV *RHS) { 11163 // If both sides are affine addrecs for the same loop, with equal 11164 // steps, and we know the recurrences don't wrap, then we only 11165 // need to check the predicate on the starting values. 11166 11167 if (!ICmpInst::isRelational(Pred)) 11168 return false; 11169 11170 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11171 if (!LAR) 11172 return false; 11173 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11174 if (!RAR) 11175 return false; 11176 if (LAR->getLoop() != RAR->getLoop()) 11177 return false; 11178 if (!LAR->isAffine() || !RAR->isAffine()) 11179 return false; 11180 11181 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11182 return false; 11183 11184 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11185 SCEV::FlagNSW : SCEV::FlagNUW; 11186 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11187 return false; 11188 11189 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11190 } 11191 11192 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11193 /// expression? 11194 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11195 ICmpInst::Predicate Pred, 11196 const SCEV *LHS, const SCEV *RHS) { 11197 switch (Pred) { 11198 default: 11199 return false; 11200 11201 case ICmpInst::ICMP_SGE: 11202 std::swap(LHS, RHS); 11203 LLVM_FALLTHROUGH; 11204 case ICmpInst::ICMP_SLE: 11205 return 11206 // min(A, ...) <= A 11207 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11208 // A <= max(A, ...) 11209 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11210 11211 case ICmpInst::ICMP_UGE: 11212 std::swap(LHS, RHS); 11213 LLVM_FALLTHROUGH; 11214 case ICmpInst::ICMP_ULE: 11215 return 11216 // min(A, ...) <= A 11217 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11218 // A <= max(A, ...) 11219 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11220 } 11221 11222 llvm_unreachable("covered switch fell through?!"); 11223 } 11224 11225 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11226 const SCEV *LHS, const SCEV *RHS, 11227 const SCEV *FoundLHS, 11228 const SCEV *FoundRHS, 11229 unsigned Depth) { 11230 assert(getTypeSizeInBits(LHS->getType()) == 11231 getTypeSizeInBits(RHS->getType()) && 11232 "LHS and RHS have different sizes?"); 11233 assert(getTypeSizeInBits(FoundLHS->getType()) == 11234 getTypeSizeInBits(FoundRHS->getType()) && 11235 "FoundLHS and FoundRHS have different sizes?"); 11236 // We want to avoid hurting the compile time with analysis of too big trees. 11237 if (Depth > MaxSCEVOperationsImplicationDepth) 11238 return false; 11239 11240 // We only want to work with GT comparison so far. 11241 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11242 Pred = CmpInst::getSwappedPredicate(Pred); 11243 std::swap(LHS, RHS); 11244 std::swap(FoundLHS, FoundRHS); 11245 } 11246 11247 // For unsigned, try to reduce it to corresponding signed comparison. 11248 if (Pred == ICmpInst::ICMP_UGT) 11249 // We can replace unsigned predicate with its signed counterpart if all 11250 // involved values are non-negative. 11251 // TODO: We could have better support for unsigned. 11252 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11253 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11254 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11255 // use this fact to prove that LHS and RHS are non-negative. 11256 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11257 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11258 FoundRHS) && 11259 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11260 FoundRHS)) 11261 Pred = ICmpInst::ICMP_SGT; 11262 } 11263 11264 if (Pred != ICmpInst::ICMP_SGT) 11265 return false; 11266 11267 auto GetOpFromSExt = [&](const SCEV *S) { 11268 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11269 return Ext->getOperand(); 11270 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11271 // the constant in some cases. 11272 return S; 11273 }; 11274 11275 // Acquire values from extensions. 11276 auto *OrigLHS = LHS; 11277 auto *OrigFoundLHS = FoundLHS; 11278 LHS = GetOpFromSExt(LHS); 11279 FoundLHS = GetOpFromSExt(FoundLHS); 11280 11281 // Is the SGT predicate can be proved trivially or using the found context. 11282 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11283 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11284 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11285 FoundRHS, Depth + 1); 11286 }; 11287 11288 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11289 // We want to avoid creation of any new non-constant SCEV. Since we are 11290 // going to compare the operands to RHS, we should be certain that we don't 11291 // need any size extensions for this. So let's decline all cases when the 11292 // sizes of types of LHS and RHS do not match. 11293 // TODO: Maybe try to get RHS from sext to catch more cases? 11294 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11295 return false; 11296 11297 // Should not overflow. 11298 if (!LHSAddExpr->hasNoSignedWrap()) 11299 return false; 11300 11301 auto *LL = LHSAddExpr->getOperand(0); 11302 auto *LR = LHSAddExpr->getOperand(1); 11303 auto *MinusOne = getMinusOne(RHS->getType()); 11304 11305 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11306 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11307 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11308 }; 11309 // Try to prove the following rule: 11310 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11311 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11312 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11313 return true; 11314 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11315 Value *LL, *LR; 11316 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11317 11318 using namespace llvm::PatternMatch; 11319 11320 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11321 // Rules for division. 11322 // We are going to perform some comparisons with Denominator and its 11323 // derivative expressions. In general case, creating a SCEV for it may 11324 // lead to a complex analysis of the entire graph, and in particular it 11325 // can request trip count recalculation for the same loop. This would 11326 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11327 // this, we only want to create SCEVs that are constants in this section. 11328 // So we bail if Denominator is not a constant. 11329 if (!isa<ConstantInt>(LR)) 11330 return false; 11331 11332 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11333 11334 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11335 // then a SCEV for the numerator already exists and matches with FoundLHS. 11336 auto *Numerator = getExistingSCEV(LL); 11337 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11338 return false; 11339 11340 // Make sure that the numerator matches with FoundLHS and the denominator 11341 // is positive. 11342 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11343 return false; 11344 11345 auto *DTy = Denominator->getType(); 11346 auto *FRHSTy = FoundRHS->getType(); 11347 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11348 // One of types is a pointer and another one is not. We cannot extend 11349 // them properly to a wider type, so let us just reject this case. 11350 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11351 // to avoid this check. 11352 return false; 11353 11354 // Given that: 11355 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11356 auto *WTy = getWiderType(DTy, FRHSTy); 11357 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11358 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11359 11360 // Try to prove the following rule: 11361 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11362 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11363 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11364 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11365 if (isKnownNonPositive(RHS) && 11366 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11367 return true; 11368 11369 // Try to prove the following rule: 11370 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11371 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11372 // If we divide it by Denominator > 2, then: 11373 // 1. If FoundLHS is negative, then the result is 0. 11374 // 2. If FoundLHS is non-negative, then the result is non-negative. 11375 // Anyways, the result is non-negative. 11376 auto *MinusOne = getMinusOne(WTy); 11377 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11378 if (isKnownNegative(RHS) && 11379 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11380 return true; 11381 } 11382 } 11383 11384 // If our expression contained SCEVUnknown Phis, and we split it down and now 11385 // need to prove something for them, try to prove the predicate for every 11386 // possible incoming values of those Phis. 11387 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11388 return true; 11389 11390 return false; 11391 } 11392 11393 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11394 const SCEV *LHS, const SCEV *RHS) { 11395 // zext x u<= sext x, sext x s<= zext x 11396 switch (Pred) { 11397 case ICmpInst::ICMP_SGE: 11398 std::swap(LHS, RHS); 11399 LLVM_FALLTHROUGH; 11400 case ICmpInst::ICMP_SLE: { 11401 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11402 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11403 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11404 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11405 return true; 11406 break; 11407 } 11408 case ICmpInst::ICMP_UGE: 11409 std::swap(LHS, RHS); 11410 LLVM_FALLTHROUGH; 11411 case ICmpInst::ICMP_ULE: { 11412 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11413 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11414 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11415 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11416 return true; 11417 break; 11418 } 11419 default: 11420 break; 11421 }; 11422 return false; 11423 } 11424 11425 bool 11426 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11427 const SCEV *LHS, const SCEV *RHS) { 11428 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11429 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11430 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11431 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11432 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11433 } 11434 11435 bool 11436 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11437 const SCEV *LHS, const SCEV *RHS, 11438 const SCEV *FoundLHS, 11439 const SCEV *FoundRHS) { 11440 switch (Pred) { 11441 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11442 case ICmpInst::ICMP_EQ: 11443 case ICmpInst::ICMP_NE: 11444 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11445 return true; 11446 break; 11447 case ICmpInst::ICMP_SLT: 11448 case ICmpInst::ICMP_SLE: 11449 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11450 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11451 return true; 11452 break; 11453 case ICmpInst::ICMP_SGT: 11454 case ICmpInst::ICMP_SGE: 11455 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11456 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11457 return true; 11458 break; 11459 case ICmpInst::ICMP_ULT: 11460 case ICmpInst::ICMP_ULE: 11461 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11462 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11463 return true; 11464 break; 11465 case ICmpInst::ICMP_UGT: 11466 case ICmpInst::ICMP_UGE: 11467 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11468 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11469 return true; 11470 break; 11471 } 11472 11473 // Maybe it can be proved via operations? 11474 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11475 return true; 11476 11477 return false; 11478 } 11479 11480 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11481 const SCEV *LHS, 11482 const SCEV *RHS, 11483 const SCEV *FoundLHS, 11484 const SCEV *FoundRHS) { 11485 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11486 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11487 // reduce the compile time impact of this optimization. 11488 return false; 11489 11490 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11491 if (!Addend) 11492 return false; 11493 11494 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11495 11496 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11497 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11498 ConstantRange FoundLHSRange = 11499 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11500 11501 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11502 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11503 11504 // We can also compute the range of values for `LHS` that satisfy the 11505 // consequent, "`LHS` `Pred` `RHS`": 11506 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11507 // The antecedent implies the consequent if every value of `LHS` that 11508 // satisfies the antecedent also satisfies the consequent. 11509 return LHSRange.icmp(Pred, ConstRHS); 11510 } 11511 11512 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11513 bool IsSigned) { 11514 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11515 11516 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11517 const SCEV *One = getOne(Stride->getType()); 11518 11519 if (IsSigned) { 11520 APInt MaxRHS = getSignedRangeMax(RHS); 11521 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11522 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11523 11524 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11525 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11526 } 11527 11528 APInt MaxRHS = getUnsignedRangeMax(RHS); 11529 APInt MaxValue = APInt::getMaxValue(BitWidth); 11530 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11531 11532 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11533 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11534 } 11535 11536 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11537 bool IsSigned) { 11538 11539 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11540 const SCEV *One = getOne(Stride->getType()); 11541 11542 if (IsSigned) { 11543 APInt MinRHS = getSignedRangeMin(RHS); 11544 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11545 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11546 11547 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11548 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11549 } 11550 11551 APInt MinRHS = getUnsignedRangeMin(RHS); 11552 APInt MinValue = APInt::getMinValue(BitWidth); 11553 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11554 11555 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11556 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11557 } 11558 11559 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11560 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11561 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11562 // expression fixes the case of N=0. 11563 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11564 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11565 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11566 } 11567 11568 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11569 const SCEV *Stride, 11570 const SCEV *End, 11571 unsigned BitWidth, 11572 bool IsSigned) { 11573 // The logic in this function assumes we can represent a positive stride. 11574 // If we can't, the backedge-taken count must be zero. 11575 if (IsSigned && BitWidth == 1) 11576 return getZero(Stride->getType()); 11577 11578 // This code has only been closely audited for negative strides in the 11579 // unsigned comparison case, it may be correct for signed comparison, but 11580 // that needs to be established. 11581 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11582 "Stride is expected strictly positive for signed case!"); 11583 11584 // Calculate the maximum backedge count based on the range of values 11585 // permitted by Start, End, and Stride. 11586 APInt MinStart = 11587 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11588 11589 APInt MinStride = 11590 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11591 11592 // We assume either the stride is positive, or the backedge-taken count 11593 // is zero. So force StrideForMaxBECount to be at least one. 11594 APInt One(BitWidth, 1); 11595 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11596 : APIntOps::umax(One, MinStride); 11597 11598 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11599 : APInt::getMaxValue(BitWidth); 11600 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11601 11602 // Although End can be a MAX expression we estimate MaxEnd considering only 11603 // the case End = RHS of the loop termination condition. This is safe because 11604 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11605 // taken count. 11606 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11607 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11608 11609 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11610 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11611 : APIntOps::umax(MaxEnd, MinStart); 11612 11613 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11614 getConstant(StrideForMaxBECount) /* Step */); 11615 } 11616 11617 ScalarEvolution::ExitLimit 11618 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11619 const Loop *L, bool IsSigned, 11620 bool ControlsExit, bool AllowPredicates) { 11621 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11622 11623 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11624 bool PredicatedIV = false; 11625 11626 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11627 // Can we prove this loop *must* be UB if overflow of IV occurs? 11628 // Reasoning goes as follows: 11629 // * Suppose the IV did self wrap. 11630 // * If Stride evenly divides the iteration space, then once wrap 11631 // occurs, the loop must revisit the same values. 11632 // * We know that RHS is invariant, and that none of those values 11633 // caused this exit to be taken previously. Thus, this exit is 11634 // dynamically dead. 11635 // * If this is the sole exit, then a dead exit implies the loop 11636 // must be infinite if there are no abnormal exits. 11637 // * If the loop were infinite, then it must either not be mustprogress 11638 // or have side effects. Otherwise, it must be UB. 11639 // * It can't (by assumption), be UB so we have contradicted our 11640 // premise and can conclude the IV did not in fact self-wrap. 11641 if (!isLoopInvariant(RHS, L)) 11642 return false; 11643 11644 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11645 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11646 return false; 11647 11648 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11649 return false; 11650 11651 return loopIsFiniteByAssumption(L); 11652 }; 11653 11654 if (!IV) { 11655 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11656 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11657 if (AR && AR->getLoop() == L && AR->isAffine()) { 11658 auto Flags = AR->getNoWrapFlags(); 11659 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11660 Flags = setFlags(Flags, SCEV::FlagNW); 11661 11662 SmallVector<const SCEV*> Operands{AR->operands()}; 11663 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11664 11665 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11666 } 11667 if (AR->hasNoUnsignedWrap()) { 11668 // Emulate what getZeroExtendExpr would have done during construction 11669 // if we'd been able to infer the fact just above at that time. 11670 const SCEV *Step = AR->getStepRecurrence(*this); 11671 Type *Ty = ZExt->getType(); 11672 auto *S = getAddRecExpr( 11673 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11674 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11675 IV = dyn_cast<SCEVAddRecExpr>(S); 11676 } 11677 } 11678 } 11679 } 11680 11681 11682 if (!IV && AllowPredicates) { 11683 // Try to make this an AddRec using runtime tests, in the first X 11684 // iterations of this loop, where X is the SCEV expression found by the 11685 // algorithm below. 11686 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11687 PredicatedIV = true; 11688 } 11689 11690 // Avoid weird loops 11691 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11692 return getCouldNotCompute(); 11693 11694 // A precondition of this method is that the condition being analyzed 11695 // reaches an exiting branch which dominates the latch. Given that, we can 11696 // assume that an increment which violates the nowrap specification and 11697 // produces poison must cause undefined behavior when the resulting poison 11698 // value is branched upon and thus we can conclude that the backedge is 11699 // taken no more often than would be required to produce that poison value. 11700 // Note that a well defined loop can exit on the iteration which violates 11701 // the nowrap specification if there is another exit (either explicit or 11702 // implicit/exceptional) which causes the loop to execute before the 11703 // exiting instruction we're analyzing would trigger UB. 11704 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11705 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11706 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11707 11708 const SCEV *Stride = IV->getStepRecurrence(*this); 11709 11710 bool PositiveStride = isKnownPositive(Stride); 11711 11712 // Avoid negative or zero stride values. 11713 if (!PositiveStride) { 11714 // We can compute the correct backedge taken count for loops with unknown 11715 // strides if we can prove that the loop is not an infinite loop with side 11716 // effects. Here's the loop structure we are trying to handle - 11717 // 11718 // i = start 11719 // do { 11720 // A[i] = i; 11721 // i += s; 11722 // } while (i < end); 11723 // 11724 // The backedge taken count for such loops is evaluated as - 11725 // (max(end, start + stride) - start - 1) /u stride 11726 // 11727 // The additional preconditions that we need to check to prove correctness 11728 // of the above formula is as follows - 11729 // 11730 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11731 // NoWrap flag). 11732 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11733 // no side effects within the loop) 11734 // c) loop has a single static exit (with no abnormal exits) 11735 // 11736 // Precondition a) implies that if the stride is negative, this is a single 11737 // trip loop. The backedge taken count formula reduces to zero in this case. 11738 // 11739 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11740 // then a zero stride means the backedge can't be taken without executing 11741 // undefined behavior. 11742 // 11743 // The positive stride case is the same as isKnownPositive(Stride) returning 11744 // true (original behavior of the function). 11745 // 11746 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 11747 !loopHasNoAbnormalExits(L)) 11748 return getCouldNotCompute(); 11749 11750 // This bailout is protecting the logic in computeMaxBECountForLT which 11751 // has not yet been sufficiently auditted or tested with negative strides. 11752 // We used to filter out all known-non-positive cases here, we're in the 11753 // process of being less restrictive bit by bit. 11754 if (IsSigned && isKnownNonPositive(Stride)) 11755 return getCouldNotCompute(); 11756 11757 if (!isKnownNonZero(Stride)) { 11758 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11759 // if it might eventually be greater than start and if so, on which 11760 // iteration. We can't even produce a useful upper bound. 11761 if (!isLoopInvariant(RHS, L)) 11762 return getCouldNotCompute(); 11763 11764 // We allow a potentially zero stride, but we need to divide by stride 11765 // below. Since the loop can't be infinite and this check must control 11766 // the sole exit, we can infer the exit must be taken on the first 11767 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11768 // we know the numerator in the divides below must be zero, so we can 11769 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11770 // and produce the right result. 11771 // FIXME: Handle the case where Stride is poison? 11772 auto wouldZeroStrideBeUB = [&]() { 11773 // Proof by contradiction. Suppose the stride were zero. If we can 11774 // prove that the backedge *is* taken on the first iteration, then since 11775 // we know this condition controls the sole exit, we must have an 11776 // infinite loop. We can't have a (well defined) infinite loop per 11777 // check just above. 11778 // Note: The (Start - Stride) term is used to get the start' term from 11779 // (start' + stride,+,stride). Remember that we only care about the 11780 // result of this expression when stride == 0 at runtime. 11781 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11782 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11783 }; 11784 if (!wouldZeroStrideBeUB()) { 11785 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11786 } 11787 } 11788 } else if (!Stride->isOne() && !NoWrap) { 11789 auto isUBOnWrap = [&]() { 11790 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11791 // follows trivially from the fact that every (un)signed-wrapped, but 11792 // not self-wrapped value must be LT than the last value before 11793 // (un)signed wrap. Since we know that last value didn't exit, nor 11794 // will any smaller one. 11795 return canAssumeNoSelfWrap(IV); 11796 }; 11797 11798 // Avoid proven overflow cases: this will ensure that the backedge taken 11799 // count will not generate any unsigned overflow. Relaxed no-overflow 11800 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11801 // undefined behaviors like the case of C language. 11802 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11803 return getCouldNotCompute(); 11804 } 11805 11806 // On all paths just preceeding, we established the following invariant: 11807 // IV can be assumed not to overflow up to and including the exiting 11808 // iteration. We proved this in one of two ways: 11809 // 1) We can show overflow doesn't occur before the exiting iteration 11810 // 1a) canIVOverflowOnLT, and b) step of one 11811 // 2) We can show that if overflow occurs, the loop must execute UB 11812 // before any possible exit. 11813 // Note that we have not yet proved RHS invariant (in general). 11814 11815 const SCEV *Start = IV->getStart(); 11816 11817 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11818 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 11819 // Use integer-typed versions for actual computation; we can't subtract 11820 // pointers in general. 11821 const SCEV *OrigStart = Start; 11822 const SCEV *OrigRHS = RHS; 11823 if (Start->getType()->isPointerTy()) { 11824 Start = getLosslessPtrToIntExpr(Start); 11825 if (isa<SCEVCouldNotCompute>(Start)) 11826 return Start; 11827 } 11828 if (RHS->getType()->isPointerTy()) { 11829 RHS = getLosslessPtrToIntExpr(RHS); 11830 if (isa<SCEVCouldNotCompute>(RHS)) 11831 return RHS; 11832 } 11833 11834 // When the RHS is not invariant, we do not know the end bound of the loop and 11835 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11836 // calculate the MaxBECount, given the start, stride and max value for the end 11837 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11838 // checked above). 11839 if (!isLoopInvariant(RHS, L)) { 11840 const SCEV *MaxBECount = computeMaxBECountForLT( 11841 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11842 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11843 false /*MaxOrZero*/, Predicates); 11844 } 11845 11846 // We use the expression (max(End,Start)-Start)/Stride to describe the 11847 // backedge count, as if the backedge is taken at least once max(End,Start) 11848 // is End and so the result is as above, and if not max(End,Start) is Start 11849 // so we get a backedge count of zero. 11850 const SCEV *BECount = nullptr; 11851 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 11852 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 11853 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 11854 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 11855 // Can we prove (max(RHS,Start) > Start - Stride? 11856 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 11857 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 11858 // In this case, we can use a refined formula for computing backedge taken 11859 // count. The general formula remains: 11860 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11861 // We want to use the alternate formula: 11862 // "((End - 1) - (Start - Stride)) /u Stride" 11863 // Let's do a quick case analysis to show these are equivalent under 11864 // our precondition that max(RHS,Start) > Start - Stride. 11865 // * For RHS <= Start, the backedge-taken count must be zero. 11866 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11867 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11868 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11869 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11870 // this to the stride of 1 case. 11871 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11872 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11873 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11874 // "((RHS - (Start - Stride) - 1) /u Stride". 11875 // Our preconditions trivially imply no overflow in that form. 11876 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11877 const SCEV *Numerator = 11878 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 11879 BECount = getUDivExpr(Numerator, Stride); 11880 } 11881 11882 const SCEV *BECountIfBackedgeTaken = nullptr; 11883 if (!BECount) { 11884 auto canProveRHSGreaterThanEqualStart = [&]() { 11885 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11886 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11887 return true; 11888 11889 // (RHS > Start - 1) implies RHS >= Start. 11890 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11891 // "Start - 1" doesn't overflow. 11892 // * For signed comparison, if Start - 1 does overflow, it's equal 11893 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11894 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11895 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11896 // 11897 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11898 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11899 auto *StartMinusOne = getAddExpr(OrigStart, 11900 getMinusOne(OrigStart->getType())); 11901 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11902 }; 11903 11904 // If we know that RHS >= Start in the context of loop, then we know that 11905 // max(RHS, Start) = RHS at this point. 11906 const SCEV *End; 11907 if (canProveRHSGreaterThanEqualStart()) { 11908 End = RHS; 11909 } else { 11910 // If RHS < Start, the backedge will be taken zero times. So in 11911 // general, we can write the backedge-taken count as: 11912 // 11913 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11914 // 11915 // We convert it to the following to make it more convenient for SCEV: 11916 // 11917 // ceil(max(RHS, Start) - Start) / Stride 11918 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11919 11920 // See what would happen if we assume the backedge is taken. This is 11921 // used to compute MaxBECount. 11922 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11923 } 11924 11925 // At this point, we know: 11926 // 11927 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11928 // 2. The index variable doesn't overflow. 11929 // 11930 // Therefore, we know N exists such that 11931 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11932 // doesn't overflow. 11933 // 11934 // Using this information, try to prove whether the addition in 11935 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11936 const SCEV *One = getOne(Stride->getType()); 11937 bool MayAddOverflow = [&] { 11938 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11939 if (StrideC->getAPInt().isPowerOf2()) { 11940 // Suppose Stride is a power of two, and Start/End are unsigned 11941 // integers. Let UMAX be the largest representable unsigned 11942 // integer. 11943 // 11944 // By the preconditions of this function, we know 11945 // "(Start + Stride * N) >= End", and this doesn't overflow. 11946 // As a formula: 11947 // 11948 // End <= (Start + Stride * N) <= UMAX 11949 // 11950 // Subtracting Start from all the terms: 11951 // 11952 // End - Start <= Stride * N <= UMAX - Start 11953 // 11954 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11955 // 11956 // End - Start <= Stride * N <= UMAX 11957 // 11958 // Stride * N is a multiple of Stride. Therefore, 11959 // 11960 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11961 // 11962 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11963 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11964 // 11965 // End - Start <= Stride * N <= UMAX - Stride - 1 11966 // 11967 // Dropping the middle term: 11968 // 11969 // End - Start <= UMAX - Stride - 1 11970 // 11971 // Adding Stride - 1 to both sides: 11972 // 11973 // (End - Start) + (Stride - 1) <= UMAX 11974 // 11975 // In other words, the addition doesn't have unsigned overflow. 11976 // 11977 // A similar proof works if we treat Start/End as signed values. 11978 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11979 // use signed max instead of unsigned max. Note that we're trying 11980 // to prove a lack of unsigned overflow in either case. 11981 return false; 11982 } 11983 } 11984 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 11985 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 11986 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 11987 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 11988 // 11989 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 11990 return false; 11991 } 11992 return true; 11993 }(); 11994 11995 const SCEV *Delta = getMinusSCEV(End, Start); 11996 if (!MayAddOverflow) { 11997 // floor((D + (S - 1)) / S) 11998 // We prefer this formulation if it's legal because it's fewer operations. 11999 BECount = 12000 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12001 } else { 12002 BECount = getUDivCeilSCEV(Delta, Stride); 12003 } 12004 } 12005 12006 const SCEV *MaxBECount; 12007 bool MaxOrZero = false; 12008 if (isa<SCEVConstant>(BECount)) { 12009 MaxBECount = BECount; 12010 } else if (BECountIfBackedgeTaken && 12011 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12012 // If we know exactly how many times the backedge will be taken if it's 12013 // taken at least once, then the backedge count will either be that or 12014 // zero. 12015 MaxBECount = BECountIfBackedgeTaken; 12016 MaxOrZero = true; 12017 } else { 12018 MaxBECount = computeMaxBECountForLT( 12019 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12020 } 12021 12022 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12023 !isa<SCEVCouldNotCompute>(BECount)) 12024 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12025 12026 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12027 } 12028 12029 ScalarEvolution::ExitLimit 12030 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12031 const Loop *L, bool IsSigned, 12032 bool ControlsExit, bool AllowPredicates) { 12033 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12034 // We handle only IV > Invariant 12035 if (!isLoopInvariant(RHS, L)) 12036 return getCouldNotCompute(); 12037 12038 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12039 if (!IV && AllowPredicates) 12040 // Try to make this an AddRec using runtime tests, in the first X 12041 // iterations of this loop, where X is the SCEV expression found by the 12042 // algorithm below. 12043 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12044 12045 // Avoid weird loops 12046 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12047 return getCouldNotCompute(); 12048 12049 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12050 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12051 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12052 12053 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12054 12055 // Avoid negative or zero stride values 12056 if (!isKnownPositive(Stride)) 12057 return getCouldNotCompute(); 12058 12059 // Avoid proven overflow cases: this will ensure that the backedge taken count 12060 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12061 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12062 // behaviors like the case of C language. 12063 if (!Stride->isOne() && !NoWrap) 12064 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12065 return getCouldNotCompute(); 12066 12067 const SCEV *Start = IV->getStart(); 12068 const SCEV *End = RHS; 12069 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12070 // If we know that Start >= RHS in the context of loop, then we know that 12071 // min(RHS, Start) = RHS at this point. 12072 if (isLoopEntryGuardedByCond( 12073 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12074 End = RHS; 12075 else 12076 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12077 } 12078 12079 if (Start->getType()->isPointerTy()) { 12080 Start = getLosslessPtrToIntExpr(Start); 12081 if (isa<SCEVCouldNotCompute>(Start)) 12082 return Start; 12083 } 12084 if (End->getType()->isPointerTy()) { 12085 End = getLosslessPtrToIntExpr(End); 12086 if (isa<SCEVCouldNotCompute>(End)) 12087 return End; 12088 } 12089 12090 // Compute ((Start - End) + (Stride - 1)) / Stride. 12091 // FIXME: This can overflow. Holding off on fixing this for now; 12092 // howManyGreaterThans will hopefully be gone soon. 12093 const SCEV *One = getOne(Stride->getType()); 12094 const SCEV *BECount = getUDivExpr( 12095 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12096 12097 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12098 : getUnsignedRangeMax(Start); 12099 12100 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12101 : getUnsignedRangeMin(Stride); 12102 12103 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12104 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12105 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12106 12107 // Although End can be a MIN expression we estimate MinEnd considering only 12108 // the case End = RHS. This is safe because in the other case (Start - End) 12109 // is zero, leading to a zero maximum backedge taken count. 12110 APInt MinEnd = 12111 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12112 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12113 12114 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12115 ? BECount 12116 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12117 getConstant(MinStride)); 12118 12119 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12120 MaxBECount = BECount; 12121 12122 return ExitLimit(BECount, MaxBECount, false, Predicates); 12123 } 12124 12125 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12126 ScalarEvolution &SE) const { 12127 if (Range.isFullSet()) // Infinite loop. 12128 return SE.getCouldNotCompute(); 12129 12130 // If the start is a non-zero constant, shift the range to simplify things. 12131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12132 if (!SC->getValue()->isZero()) { 12133 SmallVector<const SCEV *, 4> Operands(operands()); 12134 Operands[0] = SE.getZero(SC->getType()); 12135 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12136 getNoWrapFlags(FlagNW)); 12137 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12138 return ShiftedAddRec->getNumIterationsInRange( 12139 Range.subtract(SC->getAPInt()), SE); 12140 // This is strange and shouldn't happen. 12141 return SE.getCouldNotCompute(); 12142 } 12143 12144 // The only time we can solve this is when we have all constant indices. 12145 // Otherwise, we cannot determine the overflow conditions. 12146 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12147 return SE.getCouldNotCompute(); 12148 12149 // Okay at this point we know that all elements of the chrec are constants and 12150 // that the start element is zero. 12151 12152 // First check to see if the range contains zero. If not, the first 12153 // iteration exits. 12154 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12155 if (!Range.contains(APInt(BitWidth, 0))) 12156 return SE.getZero(getType()); 12157 12158 if (isAffine()) { 12159 // If this is an affine expression then we have this situation: 12160 // Solve {0,+,A} in Range === Ax in Range 12161 12162 // We know that zero is in the range. If A is positive then we know that 12163 // the upper value of the range must be the first possible exit value. 12164 // If A is negative then the lower of the range is the last possible loop 12165 // value. Also note that we already checked for a full range. 12166 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12167 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12168 12169 // The exit value should be (End+A)/A. 12170 APInt ExitVal = (End + A).udiv(A); 12171 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12172 12173 // Evaluate at the exit value. If we really did fall out of the valid 12174 // range, then we computed our trip count, otherwise wrap around or other 12175 // things must have happened. 12176 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12177 if (Range.contains(Val->getValue())) 12178 return SE.getCouldNotCompute(); // Something strange happened 12179 12180 // Ensure that the previous value is in the range. This is a sanity check. 12181 assert(Range.contains( 12182 EvaluateConstantChrecAtConstant(this, 12183 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12184 "Linear scev computation is off in a bad way!"); 12185 return SE.getConstant(ExitValue); 12186 } 12187 12188 if (isQuadratic()) { 12189 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12190 return SE.getConstant(S.getValue()); 12191 } 12192 12193 return SE.getCouldNotCompute(); 12194 } 12195 12196 const SCEVAddRecExpr * 12197 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12198 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12199 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12200 // but in this case we cannot guarantee that the value returned will be an 12201 // AddRec because SCEV does not have a fixed point where it stops 12202 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12203 // may happen if we reach arithmetic depth limit while simplifying. So we 12204 // construct the returned value explicitly. 12205 SmallVector<const SCEV *, 3> Ops; 12206 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12207 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12208 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12209 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12210 // We know that the last operand is not a constant zero (otherwise it would 12211 // have been popped out earlier). This guarantees us that if the result has 12212 // the same last operand, then it will also not be popped out, meaning that 12213 // the returned value will be an AddRec. 12214 const SCEV *Last = getOperand(getNumOperands() - 1); 12215 assert(!Last->isZero() && "Recurrency with zero step?"); 12216 Ops.push_back(Last); 12217 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12218 SCEV::FlagAnyWrap)); 12219 } 12220 12221 // Return true when S contains at least an undef value. 12222 static inline bool containsUndefs(const SCEV *S) { 12223 return SCEVExprContains(S, [](const SCEV *S) { 12224 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12225 return isa<UndefValue>(SU->getValue()); 12226 return false; 12227 }); 12228 } 12229 12230 /// Return the size of an element read or written by Inst. 12231 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12232 Type *Ty; 12233 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12234 Ty = Store->getValueOperand()->getType(); 12235 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12236 Ty = Load->getType(); 12237 else 12238 return nullptr; 12239 12240 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12241 return getSizeOfExpr(ETy, Ty); 12242 } 12243 12244 //===----------------------------------------------------------------------===// 12245 // SCEVCallbackVH Class Implementation 12246 //===----------------------------------------------------------------------===// 12247 12248 void ScalarEvolution::SCEVCallbackVH::deleted() { 12249 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12250 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12251 SE->ConstantEvolutionLoopExitValue.erase(PN); 12252 SE->eraseValueFromMap(getValPtr()); 12253 // this now dangles! 12254 } 12255 12256 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12257 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12258 12259 // Forget all the expressions associated with users of the old value, 12260 // so that future queries will recompute the expressions using the new 12261 // value. 12262 Value *Old = getValPtr(); 12263 SmallVector<User *, 16> Worklist(Old->users()); 12264 SmallPtrSet<User *, 8> Visited; 12265 while (!Worklist.empty()) { 12266 User *U = Worklist.pop_back_val(); 12267 // Deleting the Old value will cause this to dangle. Postpone 12268 // that until everything else is done. 12269 if (U == Old) 12270 continue; 12271 if (!Visited.insert(U).second) 12272 continue; 12273 if (PHINode *PN = dyn_cast<PHINode>(U)) 12274 SE->ConstantEvolutionLoopExitValue.erase(PN); 12275 SE->eraseValueFromMap(U); 12276 llvm::append_range(Worklist, U->users()); 12277 } 12278 // Delete the Old value. 12279 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12280 SE->ConstantEvolutionLoopExitValue.erase(PN); 12281 SE->eraseValueFromMap(Old); 12282 // this now dangles! 12283 } 12284 12285 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12286 : CallbackVH(V), SE(se) {} 12287 12288 //===----------------------------------------------------------------------===// 12289 // ScalarEvolution Class Implementation 12290 //===----------------------------------------------------------------------===// 12291 12292 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12293 AssumptionCache &AC, DominatorTree &DT, 12294 LoopInfo &LI) 12295 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12296 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12297 LoopDispositions(64), BlockDispositions(64) { 12298 // To use guards for proving predicates, we need to scan every instruction in 12299 // relevant basic blocks, and not just terminators. Doing this is a waste of 12300 // time if the IR does not actually contain any calls to 12301 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12302 // 12303 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12304 // to _add_ guards to the module when there weren't any before, and wants 12305 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12306 // efficient in lieu of being smart in that rather obscure case. 12307 12308 auto *GuardDecl = F.getParent()->getFunction( 12309 Intrinsic::getName(Intrinsic::experimental_guard)); 12310 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12311 } 12312 12313 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12314 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12315 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12316 ValueExprMap(std::move(Arg.ValueExprMap)), 12317 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12318 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12319 PendingMerges(std::move(Arg.PendingMerges)), 12320 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12321 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12322 PredicatedBackedgeTakenCounts( 12323 std::move(Arg.PredicatedBackedgeTakenCounts)), 12324 ConstantEvolutionLoopExitValue( 12325 std::move(Arg.ConstantEvolutionLoopExitValue)), 12326 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12327 LoopDispositions(std::move(Arg.LoopDispositions)), 12328 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12329 BlockDispositions(std::move(Arg.BlockDispositions)), 12330 SCEVUsers(std::move(Arg.SCEVUsers)), 12331 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12332 SignedRanges(std::move(Arg.SignedRanges)), 12333 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12334 UniquePreds(std::move(Arg.UniquePreds)), 12335 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12336 LoopUsers(std::move(Arg.LoopUsers)), 12337 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12338 FirstUnknown(Arg.FirstUnknown) { 12339 Arg.FirstUnknown = nullptr; 12340 } 12341 12342 ScalarEvolution::~ScalarEvolution() { 12343 // Iterate through all the SCEVUnknown instances and call their 12344 // destructors, so that they release their references to their values. 12345 for (SCEVUnknown *U = FirstUnknown; U;) { 12346 SCEVUnknown *Tmp = U; 12347 U = U->Next; 12348 Tmp->~SCEVUnknown(); 12349 } 12350 FirstUnknown = nullptr; 12351 12352 ExprValueMap.clear(); 12353 ValueExprMap.clear(); 12354 HasRecMap.clear(); 12355 BackedgeTakenCounts.clear(); 12356 PredicatedBackedgeTakenCounts.clear(); 12357 12358 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12359 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12360 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12361 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12362 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12363 } 12364 12365 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12366 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12367 } 12368 12369 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12370 const Loop *L) { 12371 // Print all inner loops first 12372 for (Loop *I : *L) 12373 PrintLoopInfo(OS, SE, I); 12374 12375 OS << "Loop "; 12376 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12377 OS << ": "; 12378 12379 SmallVector<BasicBlock *, 8> ExitingBlocks; 12380 L->getExitingBlocks(ExitingBlocks); 12381 if (ExitingBlocks.size() != 1) 12382 OS << "<multiple exits> "; 12383 12384 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12385 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12386 else 12387 OS << "Unpredictable backedge-taken count.\n"; 12388 12389 if (ExitingBlocks.size() > 1) 12390 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12391 OS << " exit count for " << ExitingBlock->getName() << ": " 12392 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12393 } 12394 12395 OS << "Loop "; 12396 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12397 OS << ": "; 12398 12399 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12400 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12401 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12402 OS << ", actual taken count either this or zero."; 12403 } else { 12404 OS << "Unpredictable max backedge-taken count. "; 12405 } 12406 12407 OS << "\n" 12408 "Loop "; 12409 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12410 OS << ": "; 12411 12412 SCEVUnionPredicate Pred; 12413 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12414 if (!isa<SCEVCouldNotCompute>(PBT)) { 12415 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12416 OS << " Predicates:\n"; 12417 Pred.print(OS, 4); 12418 } else { 12419 OS << "Unpredictable predicated backedge-taken count. "; 12420 } 12421 OS << "\n"; 12422 12423 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12424 OS << "Loop "; 12425 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12426 OS << ": "; 12427 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12428 } 12429 } 12430 12431 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12432 switch (LD) { 12433 case ScalarEvolution::LoopVariant: 12434 return "Variant"; 12435 case ScalarEvolution::LoopInvariant: 12436 return "Invariant"; 12437 case ScalarEvolution::LoopComputable: 12438 return "Computable"; 12439 } 12440 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12441 } 12442 12443 void ScalarEvolution::print(raw_ostream &OS) const { 12444 // ScalarEvolution's implementation of the print method is to print 12445 // out SCEV values of all instructions that are interesting. Doing 12446 // this potentially causes it to create new SCEV objects though, 12447 // which technically conflicts with the const qualifier. This isn't 12448 // observable from outside the class though, so casting away the 12449 // const isn't dangerous. 12450 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12451 12452 if (ClassifyExpressions) { 12453 OS << "Classifying expressions for: "; 12454 F.printAsOperand(OS, /*PrintType=*/false); 12455 OS << "\n"; 12456 for (Instruction &I : instructions(F)) 12457 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12458 OS << I << '\n'; 12459 OS << " --> "; 12460 const SCEV *SV = SE.getSCEV(&I); 12461 SV->print(OS); 12462 if (!isa<SCEVCouldNotCompute>(SV)) { 12463 OS << " U: "; 12464 SE.getUnsignedRange(SV).print(OS); 12465 OS << " S: "; 12466 SE.getSignedRange(SV).print(OS); 12467 } 12468 12469 const Loop *L = LI.getLoopFor(I.getParent()); 12470 12471 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12472 if (AtUse != SV) { 12473 OS << " --> "; 12474 AtUse->print(OS); 12475 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12476 OS << " U: "; 12477 SE.getUnsignedRange(AtUse).print(OS); 12478 OS << " S: "; 12479 SE.getSignedRange(AtUse).print(OS); 12480 } 12481 } 12482 12483 if (L) { 12484 OS << "\t\t" "Exits: "; 12485 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12486 if (!SE.isLoopInvariant(ExitValue, L)) { 12487 OS << "<<Unknown>>"; 12488 } else { 12489 OS << *ExitValue; 12490 } 12491 12492 bool First = true; 12493 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12494 if (First) { 12495 OS << "\t\t" "LoopDispositions: { "; 12496 First = false; 12497 } else { 12498 OS << ", "; 12499 } 12500 12501 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12502 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12503 } 12504 12505 for (auto *InnerL : depth_first(L)) { 12506 if (InnerL == L) 12507 continue; 12508 if (First) { 12509 OS << "\t\t" "LoopDispositions: { "; 12510 First = false; 12511 } else { 12512 OS << ", "; 12513 } 12514 12515 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12516 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12517 } 12518 12519 OS << " }"; 12520 } 12521 12522 OS << "\n"; 12523 } 12524 } 12525 12526 OS << "Determining loop execution counts for: "; 12527 F.printAsOperand(OS, /*PrintType=*/false); 12528 OS << "\n"; 12529 for (Loop *I : LI) 12530 PrintLoopInfo(OS, &SE, I); 12531 } 12532 12533 ScalarEvolution::LoopDisposition 12534 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12535 auto &Values = LoopDispositions[S]; 12536 for (auto &V : Values) { 12537 if (V.getPointer() == L) 12538 return V.getInt(); 12539 } 12540 Values.emplace_back(L, LoopVariant); 12541 LoopDisposition D = computeLoopDisposition(S, L); 12542 auto &Values2 = LoopDispositions[S]; 12543 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12544 if (V.getPointer() == L) { 12545 V.setInt(D); 12546 break; 12547 } 12548 } 12549 return D; 12550 } 12551 12552 ScalarEvolution::LoopDisposition 12553 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12554 switch (S->getSCEVType()) { 12555 case scConstant: 12556 return LoopInvariant; 12557 case scPtrToInt: 12558 case scTruncate: 12559 case scZeroExtend: 12560 case scSignExtend: 12561 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12562 case scAddRecExpr: { 12563 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12564 12565 // If L is the addrec's loop, it's computable. 12566 if (AR->getLoop() == L) 12567 return LoopComputable; 12568 12569 // Add recurrences are never invariant in the function-body (null loop). 12570 if (!L) 12571 return LoopVariant; 12572 12573 // Everything that is not defined at loop entry is variant. 12574 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12575 return LoopVariant; 12576 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12577 " dominate the contained loop's header?"); 12578 12579 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12580 if (AR->getLoop()->contains(L)) 12581 return LoopInvariant; 12582 12583 // This recurrence is variant w.r.t. L if any of its operands 12584 // are variant. 12585 for (auto *Op : AR->operands()) 12586 if (!isLoopInvariant(Op, L)) 12587 return LoopVariant; 12588 12589 // Otherwise it's loop-invariant. 12590 return LoopInvariant; 12591 } 12592 case scAddExpr: 12593 case scMulExpr: 12594 case scUMaxExpr: 12595 case scSMaxExpr: 12596 case scUMinExpr: 12597 case scSMinExpr: { 12598 bool HasVarying = false; 12599 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12600 LoopDisposition D = getLoopDisposition(Op, L); 12601 if (D == LoopVariant) 12602 return LoopVariant; 12603 if (D == LoopComputable) 12604 HasVarying = true; 12605 } 12606 return HasVarying ? LoopComputable : LoopInvariant; 12607 } 12608 case scUDivExpr: { 12609 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12610 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12611 if (LD == LoopVariant) 12612 return LoopVariant; 12613 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12614 if (RD == LoopVariant) 12615 return LoopVariant; 12616 return (LD == LoopInvariant && RD == LoopInvariant) ? 12617 LoopInvariant : LoopComputable; 12618 } 12619 case scUnknown: 12620 // All non-instruction values are loop invariant. All instructions are loop 12621 // invariant if they are not contained in the specified loop. 12622 // Instructions are never considered invariant in the function body 12623 // (null loop) because they are defined within the "loop". 12624 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12625 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12626 return LoopInvariant; 12627 case scCouldNotCompute: 12628 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12629 } 12630 llvm_unreachable("Unknown SCEV kind!"); 12631 } 12632 12633 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12634 return getLoopDisposition(S, L) == LoopInvariant; 12635 } 12636 12637 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12638 return getLoopDisposition(S, L) == LoopComputable; 12639 } 12640 12641 ScalarEvolution::BlockDisposition 12642 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12643 auto &Values = BlockDispositions[S]; 12644 for (auto &V : Values) { 12645 if (V.getPointer() == BB) 12646 return V.getInt(); 12647 } 12648 Values.emplace_back(BB, DoesNotDominateBlock); 12649 BlockDisposition D = computeBlockDisposition(S, BB); 12650 auto &Values2 = BlockDispositions[S]; 12651 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12652 if (V.getPointer() == BB) { 12653 V.setInt(D); 12654 break; 12655 } 12656 } 12657 return D; 12658 } 12659 12660 ScalarEvolution::BlockDisposition 12661 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12662 switch (S->getSCEVType()) { 12663 case scConstant: 12664 return ProperlyDominatesBlock; 12665 case scPtrToInt: 12666 case scTruncate: 12667 case scZeroExtend: 12668 case scSignExtend: 12669 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12670 case scAddRecExpr: { 12671 // This uses a "dominates" query instead of "properly dominates" query 12672 // to test for proper dominance too, because the instruction which 12673 // produces the addrec's value is a PHI, and a PHI effectively properly 12674 // dominates its entire containing block. 12675 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12676 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12677 return DoesNotDominateBlock; 12678 12679 // Fall through into SCEVNAryExpr handling. 12680 LLVM_FALLTHROUGH; 12681 } 12682 case scAddExpr: 12683 case scMulExpr: 12684 case scUMaxExpr: 12685 case scSMaxExpr: 12686 case scUMinExpr: 12687 case scSMinExpr: { 12688 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12689 bool Proper = true; 12690 for (const SCEV *NAryOp : NAry->operands()) { 12691 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12692 if (D == DoesNotDominateBlock) 12693 return DoesNotDominateBlock; 12694 if (D == DominatesBlock) 12695 Proper = false; 12696 } 12697 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12698 } 12699 case scUDivExpr: { 12700 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12701 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12702 BlockDisposition LD = getBlockDisposition(LHS, BB); 12703 if (LD == DoesNotDominateBlock) 12704 return DoesNotDominateBlock; 12705 BlockDisposition RD = getBlockDisposition(RHS, BB); 12706 if (RD == DoesNotDominateBlock) 12707 return DoesNotDominateBlock; 12708 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12709 ProperlyDominatesBlock : DominatesBlock; 12710 } 12711 case scUnknown: 12712 if (Instruction *I = 12713 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12714 if (I->getParent() == BB) 12715 return DominatesBlock; 12716 if (DT.properlyDominates(I->getParent(), BB)) 12717 return ProperlyDominatesBlock; 12718 return DoesNotDominateBlock; 12719 } 12720 return ProperlyDominatesBlock; 12721 case scCouldNotCompute: 12722 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12723 } 12724 llvm_unreachable("Unknown SCEV kind!"); 12725 } 12726 12727 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12728 return getBlockDisposition(S, BB) >= DominatesBlock; 12729 } 12730 12731 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12732 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12733 } 12734 12735 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12736 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12737 } 12738 12739 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 12740 for (auto *S : SCEVs) 12741 forgetMemoizedResultsImpl(S); 12742 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 12743 for (auto I = PredicatedSCEVRewrites.begin(); 12744 I != PredicatedSCEVRewrites.end();) { 12745 std::pair<const SCEV *, const Loop *> Entry = I->first; 12746 if (ToForget.count(Entry.first)) 12747 PredicatedSCEVRewrites.erase(I++); 12748 else 12749 ++I; 12750 } 12751 12752 auto RemoveSCEVFromBackedgeMap = [&ToForget]( 12753 DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12754 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12755 BackedgeTakenInfo &BEInfo = I->second; 12756 if (any_of(ToForget, 12757 [&BEInfo](const SCEV *S) { return BEInfo.hasOperand(S); })) 12758 Map.erase(I++); 12759 else 12760 ++I; 12761 } 12762 }; 12763 12764 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12765 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12766 } 12767 12768 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 12769 ValuesAtScopes.erase(S); 12770 LoopDispositions.erase(S); 12771 BlockDispositions.erase(S); 12772 UnsignedRanges.erase(S); 12773 SignedRanges.erase(S); 12774 ExprValueMap.erase(S); 12775 HasRecMap.erase(S); 12776 MinTrailingZerosCache.erase(S); 12777 } 12778 12779 void 12780 ScalarEvolution::getUsedLoops(const SCEV *S, 12781 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12782 struct FindUsedLoops { 12783 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12784 : LoopsUsed(LoopsUsed) {} 12785 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12786 bool follow(const SCEV *S) { 12787 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12788 LoopsUsed.insert(AR->getLoop()); 12789 return true; 12790 } 12791 12792 bool isDone() const { return false; } 12793 }; 12794 12795 FindUsedLoops F(LoopsUsed); 12796 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12797 } 12798 12799 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12800 SmallPtrSet<const Loop *, 8> LoopsUsed; 12801 getUsedLoops(S, LoopsUsed); 12802 for (auto *L : LoopsUsed) 12803 LoopUsers[L].push_back(S); 12804 } 12805 12806 void ScalarEvolution::verify() const { 12807 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12808 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12809 12810 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12811 12812 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12813 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12814 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12815 12816 const SCEV *visitConstant(const SCEVConstant *Constant) { 12817 return SE.getConstant(Constant->getAPInt()); 12818 } 12819 12820 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12821 return SE.getUnknown(Expr->getValue()); 12822 } 12823 12824 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12825 return SE.getCouldNotCompute(); 12826 } 12827 }; 12828 12829 SCEVMapper SCM(SE2); 12830 12831 while (!LoopStack.empty()) { 12832 auto *L = LoopStack.pop_back_val(); 12833 llvm::append_range(LoopStack, *L); 12834 12835 auto *CurBECount = SCM.visit( 12836 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12837 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12838 12839 if (CurBECount == SE2.getCouldNotCompute() || 12840 NewBECount == SE2.getCouldNotCompute()) { 12841 // NB! This situation is legal, but is very suspicious -- whatever pass 12842 // change the loop to make a trip count go from could not compute to 12843 // computable or vice-versa *should have* invalidated SCEV. However, we 12844 // choose not to assert here (for now) since we don't want false 12845 // positives. 12846 continue; 12847 } 12848 12849 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12850 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12851 // not propagate undef aggressively). This means we can (and do) fail 12852 // verification in cases where a transform makes the trip count of a loop 12853 // go from "undef" to "undef+1" (say). The transform is fine, since in 12854 // both cases the loop iterates "undef" times, but SCEV thinks we 12855 // increased the trip count of the loop by 1 incorrectly. 12856 continue; 12857 } 12858 12859 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12860 SE.getTypeSizeInBits(NewBECount->getType())) 12861 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12862 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12863 SE.getTypeSizeInBits(NewBECount->getType())) 12864 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12865 12866 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12867 12868 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12869 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12870 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12871 dbgs() << "Old: " << *CurBECount << "\n"; 12872 dbgs() << "New: " << *NewBECount << "\n"; 12873 dbgs() << "Delta: " << *Delta << "\n"; 12874 std::abort(); 12875 } 12876 } 12877 12878 // Collect all valid loops currently in LoopInfo. 12879 SmallPtrSet<Loop *, 32> ValidLoops; 12880 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12881 while (!Worklist.empty()) { 12882 Loop *L = Worklist.pop_back_val(); 12883 if (ValidLoops.contains(L)) 12884 continue; 12885 ValidLoops.insert(L); 12886 Worklist.append(L->begin(), L->end()); 12887 } 12888 // Check for SCEV expressions referencing invalid/deleted loops. 12889 for (auto &KV : ValueExprMap) { 12890 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12891 if (!AR) 12892 continue; 12893 assert(ValidLoops.contains(AR->getLoop()) && 12894 "AddRec references invalid loop"); 12895 } 12896 } 12897 12898 bool ScalarEvolution::invalidate( 12899 Function &F, const PreservedAnalyses &PA, 12900 FunctionAnalysisManager::Invalidator &Inv) { 12901 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12902 // of its dependencies is invalidated. 12903 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12904 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12905 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12906 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12907 Inv.invalidate<LoopAnalysis>(F, PA); 12908 } 12909 12910 AnalysisKey ScalarEvolutionAnalysis::Key; 12911 12912 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12913 FunctionAnalysisManager &AM) { 12914 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12915 AM.getResult<AssumptionAnalysis>(F), 12916 AM.getResult<DominatorTreeAnalysis>(F), 12917 AM.getResult<LoopAnalysis>(F)); 12918 } 12919 12920 PreservedAnalyses 12921 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12922 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12923 return PreservedAnalyses::all(); 12924 } 12925 12926 PreservedAnalyses 12927 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12928 // For compatibility with opt's -analyze feature under legacy pass manager 12929 // which was not ported to NPM. This keeps tests using 12930 // update_analyze_test_checks.py working. 12931 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12932 << F.getName() << "':\n"; 12933 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12934 return PreservedAnalyses::all(); 12935 } 12936 12937 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12938 "Scalar Evolution Analysis", false, true) 12939 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12940 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12941 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12942 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12943 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12944 "Scalar Evolution Analysis", false, true) 12945 12946 char ScalarEvolutionWrapperPass::ID = 0; 12947 12948 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12949 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12950 } 12951 12952 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12953 SE.reset(new ScalarEvolution( 12954 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12955 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12956 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12957 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12958 return false; 12959 } 12960 12961 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12962 12963 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12964 SE->print(OS); 12965 } 12966 12967 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12968 if (!VerifySCEV) 12969 return; 12970 12971 SE->verify(); 12972 } 12973 12974 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12975 AU.setPreservesAll(); 12976 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12977 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12978 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12979 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12980 } 12981 12982 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12983 const SCEV *RHS) { 12984 FoldingSetNodeID ID; 12985 assert(LHS->getType() == RHS->getType() && 12986 "Type mismatch between LHS and RHS"); 12987 // Unique this node based on the arguments 12988 ID.AddInteger(SCEVPredicate::P_Equal); 12989 ID.AddPointer(LHS); 12990 ID.AddPointer(RHS); 12991 void *IP = nullptr; 12992 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12993 return S; 12994 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12995 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12996 UniquePreds.InsertNode(Eq, IP); 12997 return Eq; 12998 } 12999 13000 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13001 const SCEVAddRecExpr *AR, 13002 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13003 FoldingSetNodeID ID; 13004 // Unique this node based on the arguments 13005 ID.AddInteger(SCEVPredicate::P_Wrap); 13006 ID.AddPointer(AR); 13007 ID.AddInteger(AddedFlags); 13008 void *IP = nullptr; 13009 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13010 return S; 13011 auto *OF = new (SCEVAllocator) 13012 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13013 UniquePreds.InsertNode(OF, IP); 13014 return OF; 13015 } 13016 13017 namespace { 13018 13019 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13020 public: 13021 13022 /// Rewrites \p S in the context of a loop L and the SCEV predication 13023 /// infrastructure. 13024 /// 13025 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13026 /// equivalences present in \p Pred. 13027 /// 13028 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13029 /// \p NewPreds such that the result will be an AddRecExpr. 13030 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13031 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13032 SCEVUnionPredicate *Pred) { 13033 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13034 return Rewriter.visit(S); 13035 } 13036 13037 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13038 if (Pred) { 13039 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13040 for (auto *Pred : ExprPreds) 13041 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13042 if (IPred->getLHS() == Expr) 13043 return IPred->getRHS(); 13044 } 13045 return convertToAddRecWithPreds(Expr); 13046 } 13047 13048 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13049 const SCEV *Operand = visit(Expr->getOperand()); 13050 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13051 if (AR && AR->getLoop() == L && AR->isAffine()) { 13052 // This couldn't be folded because the operand didn't have the nuw 13053 // flag. Add the nusw flag as an assumption that we could make. 13054 const SCEV *Step = AR->getStepRecurrence(SE); 13055 Type *Ty = Expr->getType(); 13056 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13057 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13058 SE.getSignExtendExpr(Step, Ty), L, 13059 AR->getNoWrapFlags()); 13060 } 13061 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13062 } 13063 13064 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13065 const SCEV *Operand = visit(Expr->getOperand()); 13066 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13067 if (AR && AR->getLoop() == L && AR->isAffine()) { 13068 // This couldn't be folded because the operand didn't have the nsw 13069 // flag. Add the nssw flag as an assumption that we could make. 13070 const SCEV *Step = AR->getStepRecurrence(SE); 13071 Type *Ty = Expr->getType(); 13072 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13073 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13074 SE.getSignExtendExpr(Step, Ty), L, 13075 AR->getNoWrapFlags()); 13076 } 13077 return SE.getSignExtendExpr(Operand, Expr->getType()); 13078 } 13079 13080 private: 13081 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13082 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13083 SCEVUnionPredicate *Pred) 13084 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13085 13086 bool addOverflowAssumption(const SCEVPredicate *P) { 13087 if (!NewPreds) { 13088 // Check if we've already made this assumption. 13089 return Pred && Pred->implies(P); 13090 } 13091 NewPreds->insert(P); 13092 return true; 13093 } 13094 13095 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13096 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13097 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13098 return addOverflowAssumption(A); 13099 } 13100 13101 // If \p Expr represents a PHINode, we try to see if it can be represented 13102 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13103 // to add this predicate as a runtime overflow check, we return the AddRec. 13104 // If \p Expr does not meet these conditions (is not a PHI node, or we 13105 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13106 // return \p Expr. 13107 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13108 if (!isa<PHINode>(Expr->getValue())) 13109 return Expr; 13110 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13111 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13112 if (!PredicatedRewrite) 13113 return Expr; 13114 for (auto *P : PredicatedRewrite->second){ 13115 // Wrap predicates from outer loops are not supported. 13116 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13117 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13118 if (L != AR->getLoop()) 13119 return Expr; 13120 } 13121 if (!addOverflowAssumption(P)) 13122 return Expr; 13123 } 13124 return PredicatedRewrite->first; 13125 } 13126 13127 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13128 SCEVUnionPredicate *Pred; 13129 const Loop *L; 13130 }; 13131 13132 } // end anonymous namespace 13133 13134 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13135 SCEVUnionPredicate &Preds) { 13136 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13137 } 13138 13139 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13140 const SCEV *S, const Loop *L, 13141 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13142 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13143 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13144 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13145 13146 if (!AddRec) 13147 return nullptr; 13148 13149 // Since the transformation was successful, we can now transfer the SCEV 13150 // predicates. 13151 for (auto *P : TransformPreds) 13152 Preds.insert(P); 13153 13154 return AddRec; 13155 } 13156 13157 /// SCEV predicates 13158 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13159 SCEVPredicateKind Kind) 13160 : FastID(ID), Kind(Kind) {} 13161 13162 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13163 const SCEV *LHS, const SCEV *RHS) 13164 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13165 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13166 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13167 } 13168 13169 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13170 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13171 13172 if (!Op) 13173 return false; 13174 13175 return Op->LHS == LHS && Op->RHS == RHS; 13176 } 13177 13178 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13179 13180 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13181 13182 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13183 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13184 } 13185 13186 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13187 const SCEVAddRecExpr *AR, 13188 IncrementWrapFlags Flags) 13189 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13190 13191 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13192 13193 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13194 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13195 13196 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13197 } 13198 13199 bool SCEVWrapPredicate::isAlwaysTrue() const { 13200 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13201 IncrementWrapFlags IFlags = Flags; 13202 13203 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13204 IFlags = clearFlags(IFlags, IncrementNSSW); 13205 13206 return IFlags == IncrementAnyWrap; 13207 } 13208 13209 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13210 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13211 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13212 OS << "<nusw>"; 13213 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13214 OS << "<nssw>"; 13215 OS << "\n"; 13216 } 13217 13218 SCEVWrapPredicate::IncrementWrapFlags 13219 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13220 ScalarEvolution &SE) { 13221 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13222 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13223 13224 // We can safely transfer the NSW flag as NSSW. 13225 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13226 ImpliedFlags = IncrementNSSW; 13227 13228 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13229 // If the increment is positive, the SCEV NUW flag will also imply the 13230 // WrapPredicate NUSW flag. 13231 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13232 if (Step->getValue()->getValue().isNonNegative()) 13233 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13234 } 13235 13236 return ImpliedFlags; 13237 } 13238 13239 /// Union predicates don't get cached so create a dummy set ID for it. 13240 SCEVUnionPredicate::SCEVUnionPredicate() 13241 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13242 13243 bool SCEVUnionPredicate::isAlwaysTrue() const { 13244 return all_of(Preds, 13245 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13246 } 13247 13248 ArrayRef<const SCEVPredicate *> 13249 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13250 auto I = SCEVToPreds.find(Expr); 13251 if (I == SCEVToPreds.end()) 13252 return ArrayRef<const SCEVPredicate *>(); 13253 return I->second; 13254 } 13255 13256 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13257 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13258 return all_of(Set->Preds, 13259 [this](const SCEVPredicate *I) { return this->implies(I); }); 13260 13261 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13262 if (ScevPredsIt == SCEVToPreds.end()) 13263 return false; 13264 auto &SCEVPreds = ScevPredsIt->second; 13265 13266 return any_of(SCEVPreds, 13267 [N](const SCEVPredicate *I) { return I->implies(N); }); 13268 } 13269 13270 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13271 13272 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13273 for (auto Pred : Preds) 13274 Pred->print(OS, Depth); 13275 } 13276 13277 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13278 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13279 for (auto Pred : Set->Preds) 13280 add(Pred); 13281 return; 13282 } 13283 13284 if (implies(N)) 13285 return; 13286 13287 const SCEV *Key = N->getExpr(); 13288 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13289 " associated expression!"); 13290 13291 SCEVToPreds[Key].push_back(N); 13292 Preds.push_back(N); 13293 } 13294 13295 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13296 Loop &L) 13297 : SE(SE), L(L) {} 13298 13299 void ScalarEvolution::registerUser(const SCEV *User, 13300 ArrayRef<const SCEV *> Ops) { 13301 for (auto *Op : Ops) 13302 // We do not expect that forgetting cached data for SCEVConstants will ever 13303 // open any prospects for sharpening or introduce any correctness issues, 13304 // so we don't bother storing their dependencies. 13305 if (!isa<SCEVConstant>(Op)) 13306 SCEVUsers[Op].insert(User); 13307 } 13308 13309 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13310 const SCEV *Expr = SE.getSCEV(V); 13311 RewriteEntry &Entry = RewriteMap[Expr]; 13312 13313 // If we already have an entry and the version matches, return it. 13314 if (Entry.second && Generation == Entry.first) 13315 return Entry.second; 13316 13317 // We found an entry but it's stale. Rewrite the stale entry 13318 // according to the current predicate. 13319 if (Entry.second) 13320 Expr = Entry.second; 13321 13322 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13323 Entry = {Generation, NewSCEV}; 13324 13325 return NewSCEV; 13326 } 13327 13328 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13329 if (!BackedgeCount) { 13330 SCEVUnionPredicate BackedgePred; 13331 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13332 addPredicate(BackedgePred); 13333 } 13334 return BackedgeCount; 13335 } 13336 13337 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13338 if (Preds.implies(&Pred)) 13339 return; 13340 Preds.add(&Pred); 13341 updateGeneration(); 13342 } 13343 13344 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13345 return Preds; 13346 } 13347 13348 void PredicatedScalarEvolution::updateGeneration() { 13349 // If the generation number wrapped recompute everything. 13350 if (++Generation == 0) { 13351 for (auto &II : RewriteMap) { 13352 const SCEV *Rewritten = II.second.second; 13353 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13354 } 13355 } 13356 } 13357 13358 void PredicatedScalarEvolution::setNoOverflow( 13359 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13360 const SCEV *Expr = getSCEV(V); 13361 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13362 13363 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13364 13365 // Clear the statically implied flags. 13366 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13367 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13368 13369 auto II = FlagsMap.insert({V, Flags}); 13370 if (!II.second) 13371 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13372 } 13373 13374 bool PredicatedScalarEvolution::hasNoOverflow( 13375 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13376 const SCEV *Expr = getSCEV(V); 13377 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13378 13379 Flags = SCEVWrapPredicate::clearFlags( 13380 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13381 13382 auto II = FlagsMap.find(V); 13383 13384 if (II != FlagsMap.end()) 13385 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13386 13387 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13388 } 13389 13390 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13391 const SCEV *Expr = this->getSCEV(V); 13392 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13393 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13394 13395 if (!New) 13396 return nullptr; 13397 13398 for (auto *P : NewPreds) 13399 Preds.add(P); 13400 13401 updateGeneration(); 13402 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13403 return New; 13404 } 13405 13406 PredicatedScalarEvolution::PredicatedScalarEvolution( 13407 const PredicatedScalarEvolution &Init) 13408 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13409 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13410 for (auto I : Init.FlagsMap) 13411 FlagsMap.insert(I); 13412 } 13413 13414 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13415 // For each block. 13416 for (auto *BB : L.getBlocks()) 13417 for (auto &I : *BB) { 13418 if (!SE.isSCEVable(I.getType())) 13419 continue; 13420 13421 auto *Expr = SE.getSCEV(&I); 13422 auto II = RewriteMap.find(Expr); 13423 13424 if (II == RewriteMap.end()) 13425 continue; 13426 13427 // Don't print things that are not interesting. 13428 if (II->second.second == Expr) 13429 continue; 13430 13431 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13432 OS.indent(Depth + 2) << *Expr << "\n"; 13433 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13434 } 13435 } 13436 13437 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13438 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13439 // for URem with constant power-of-2 second operands. 13440 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13441 // 4, A / B becomes X / 8). 13442 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13443 const SCEV *&RHS) { 13444 // Try to match 'zext (trunc A to iB) to iY', which is used 13445 // for URem with constant power-of-2 second operands. Make sure the size of 13446 // the operand A matches the size of the whole expressions. 13447 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13448 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13449 LHS = Trunc->getOperand(); 13450 // Bail out if the type of the LHS is larger than the type of the 13451 // expression for now. 13452 if (getTypeSizeInBits(LHS->getType()) > 13453 getTypeSizeInBits(Expr->getType())) 13454 return false; 13455 if (LHS->getType() != Expr->getType()) 13456 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13457 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13458 << getTypeSizeInBits(Trunc->getType())); 13459 return true; 13460 } 13461 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13462 if (Add == nullptr || Add->getNumOperands() != 2) 13463 return false; 13464 13465 const SCEV *A = Add->getOperand(1); 13466 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13467 13468 if (Mul == nullptr) 13469 return false; 13470 13471 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13472 // (SomeExpr + (-(SomeExpr / B) * B)). 13473 if (Expr == getURemExpr(A, B)) { 13474 LHS = A; 13475 RHS = B; 13476 return true; 13477 } 13478 return false; 13479 }; 13480 13481 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13482 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13483 return MatchURemWithDivisor(Mul->getOperand(1)) || 13484 MatchURemWithDivisor(Mul->getOperand(2)); 13485 13486 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13487 if (Mul->getNumOperands() == 2) 13488 return MatchURemWithDivisor(Mul->getOperand(1)) || 13489 MatchURemWithDivisor(Mul->getOperand(0)) || 13490 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13491 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13492 return false; 13493 } 13494 13495 const SCEV * 13496 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13497 SmallVector<BasicBlock*, 16> ExitingBlocks; 13498 L->getExitingBlocks(ExitingBlocks); 13499 13500 // Form an expression for the maximum exit count possible for this loop. We 13501 // merge the max and exact information to approximate a version of 13502 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13503 SmallVector<const SCEV*, 4> ExitCounts; 13504 for (BasicBlock *ExitingBB : ExitingBlocks) { 13505 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13506 if (isa<SCEVCouldNotCompute>(ExitCount)) 13507 ExitCount = getExitCount(L, ExitingBB, 13508 ScalarEvolution::ConstantMaximum); 13509 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13510 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13511 "We should only have known counts for exiting blocks that " 13512 "dominate latch!"); 13513 ExitCounts.push_back(ExitCount); 13514 } 13515 } 13516 if (ExitCounts.empty()) 13517 return getCouldNotCompute(); 13518 return getUMinFromMismatchedTypes(ExitCounts); 13519 } 13520 13521 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13522 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13523 /// we cannot guarantee that the replacement is loop invariant in the loop of 13524 /// the AddRec. 13525 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13526 ValueToSCEVMapTy ⤅ 13527 13528 public: 13529 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13530 : SCEVRewriteVisitor(SE), Map(M) {} 13531 13532 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13533 13534 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13535 auto I = Map.find(Expr->getValue()); 13536 if (I == Map.end()) 13537 return Expr; 13538 return I->second; 13539 } 13540 }; 13541 13542 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13543 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13544 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13545 // WARNING: It is generally unsound to apply any wrap flags to the proposed 13546 // replacement SCEV which isn't directly implied by the structure of that 13547 // SCEV. In particular, using contextual facts to imply flags is *NOT* 13548 // legal. See the scoping rules for flags in the header to understand why. 13549 13550 // If we have LHS == 0, check if LHS is computing a property of some unknown 13551 // SCEV %v which we can rewrite %v to express explicitly. 13552 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13553 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13554 RHSC->getValue()->isNullValue()) { 13555 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13556 // explicitly express that. 13557 const SCEV *URemLHS = nullptr; 13558 const SCEV *URemRHS = nullptr; 13559 if (matchURem(LHS, URemLHS, URemRHS)) { 13560 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13561 Value *V = LHSUnknown->getValue(); 13562 RewriteMap[V] = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 13563 return; 13564 } 13565 } 13566 } 13567 13568 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13569 std::swap(LHS, RHS); 13570 Predicate = CmpInst::getSwappedPredicate(Predicate); 13571 } 13572 13573 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13574 // create this form when combining two checks of the form (X u< C2 + C1) and 13575 // (X >=u C1). 13576 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13577 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13578 if (!AddExpr || AddExpr->getNumOperands() != 2) 13579 return false; 13580 13581 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13582 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13583 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13584 if (!C1 || !C2 || !LHSUnknown) 13585 return false; 13586 13587 auto ExactRegion = 13588 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13589 .sub(C1->getAPInt()); 13590 13591 // Bail out, unless we have a non-wrapping, monotonic range. 13592 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13593 return false; 13594 auto I = RewriteMap.find(LHSUnknown->getValue()); 13595 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13596 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13597 getConstant(ExactRegion.getUnsignedMin()), 13598 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13599 return true; 13600 }; 13601 if (MatchRangeCheckIdiom()) 13602 return; 13603 13604 // For now, limit to conditions that provide information about unknown 13605 // expressions. RHS also cannot contain add recurrences. 13606 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13607 if (!LHSUnknown || containsAddRecurrence(RHS)) 13608 return; 13609 13610 // Check whether LHS has already been rewritten. In that case we want to 13611 // chain further rewrites onto the already rewritten value. 13612 auto I = RewriteMap.find(LHSUnknown->getValue()); 13613 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13614 const SCEV *RewrittenRHS = nullptr; 13615 switch (Predicate) { 13616 case CmpInst::ICMP_ULT: 13617 RewrittenRHS = 13618 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13619 break; 13620 case CmpInst::ICMP_SLT: 13621 RewrittenRHS = 13622 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13623 break; 13624 case CmpInst::ICMP_ULE: 13625 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13626 break; 13627 case CmpInst::ICMP_SLE: 13628 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13629 break; 13630 case CmpInst::ICMP_UGT: 13631 RewrittenRHS = 13632 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13633 break; 13634 case CmpInst::ICMP_SGT: 13635 RewrittenRHS = 13636 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13637 break; 13638 case CmpInst::ICMP_UGE: 13639 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13640 break; 13641 case CmpInst::ICMP_SGE: 13642 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13643 break; 13644 case CmpInst::ICMP_EQ: 13645 if (isa<SCEVConstant>(RHS)) 13646 RewrittenRHS = RHS; 13647 break; 13648 case CmpInst::ICMP_NE: 13649 if (isa<SCEVConstant>(RHS) && 13650 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13651 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13652 break; 13653 default: 13654 break; 13655 } 13656 13657 if (RewrittenRHS) 13658 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13659 }; 13660 // Starting at the loop predecessor, climb up the predecessor chain, as long 13661 // as there are predecessors that can be found that have unique successors 13662 // leading to the original header. 13663 // TODO: share this logic with isLoopEntryGuardedByCond. 13664 ValueToSCEVMapTy RewriteMap; 13665 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13666 L->getLoopPredecessor(), L->getHeader()); 13667 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13668 13669 const BranchInst *LoopEntryPredicate = 13670 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13671 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13672 continue; 13673 13674 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13675 SmallVector<Value *, 8> Worklist; 13676 SmallPtrSet<Value *, 8> Visited; 13677 Worklist.push_back(LoopEntryPredicate->getCondition()); 13678 while (!Worklist.empty()) { 13679 Value *Cond = Worklist.pop_back_val(); 13680 if (!Visited.insert(Cond).second) 13681 continue; 13682 13683 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13684 auto Predicate = 13685 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13686 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13687 getSCEV(Cmp->getOperand(1)), RewriteMap); 13688 continue; 13689 } 13690 13691 Value *L, *R; 13692 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13693 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13694 Worklist.push_back(L); 13695 Worklist.push_back(R); 13696 } 13697 } 13698 } 13699 13700 // Also collect information from assumptions dominating the loop. 13701 for (auto &AssumeVH : AC.assumptions()) { 13702 if (!AssumeVH) 13703 continue; 13704 auto *AssumeI = cast<CallInst>(AssumeVH); 13705 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13706 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13707 continue; 13708 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13709 getSCEV(Cmp->getOperand(1)), RewriteMap); 13710 } 13711 13712 if (RewriteMap.empty()) 13713 return Expr; 13714 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13715 return Rewriter.visit(Expr); 13716 } 13717