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 /// Check whether value has nuw/nsw/exact set but SCEV does not. 4081 /// TODO: In reality it is better to check the poison recursively 4082 /// but this is better than nothing. 4083 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 4084 if (auto *I = dyn_cast<Instruction>(V)) { 4085 if (isa<OverflowingBinaryOperator>(I)) { 4086 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 4087 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 4088 return true; 4089 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 4090 return true; 4091 } 4092 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 4093 return true; 4094 } 4095 return false; 4096 } 4097 4098 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4099 /// create a new one. 4100 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4101 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4102 4103 const SCEV *S = getExistingSCEV(V); 4104 if (S == nullptr) { 4105 S = createSCEV(V); 4106 // During PHI resolution, it is possible to create two SCEVs for the same 4107 // V, so it is needed to double check whether V->S is inserted into 4108 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4109 std::pair<ValueExprMapType::iterator, bool> Pair = 4110 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4111 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 4112 ExprValueMap[S].insert({V, nullptr}); 4113 4114 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4115 // ExprValueMap. 4116 const SCEV *Stripped = S; 4117 ConstantInt *Offset = nullptr; 4118 std::tie(Stripped, Offset) = splitAddExpr(S); 4119 // If stripped is SCEVUnknown, don't bother to save 4120 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4121 // increase the complexity of the expansion code. 4122 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4123 // because it may generate add/sub instead of GEP in SCEV expansion. 4124 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4125 !isa<GetElementPtrInst>(V)) 4126 ExprValueMap[Stripped].insert({V, Offset}); 4127 } 4128 } 4129 return S; 4130 } 4131 4132 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4133 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4134 4135 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4136 if (I != ValueExprMap.end()) { 4137 const SCEV *S = I->second; 4138 if (checkValidity(S)) 4139 return S; 4140 eraseValueFromMap(V); 4141 forgetMemoizedResults(S); 4142 } 4143 return nullptr; 4144 } 4145 4146 /// Return a SCEV corresponding to -V = -1*V 4147 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4148 SCEV::NoWrapFlags Flags) { 4149 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4150 return getConstant( 4151 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4152 4153 Type *Ty = V->getType(); 4154 Ty = getEffectiveSCEVType(Ty); 4155 return getMulExpr(V, getMinusOne(Ty), Flags); 4156 } 4157 4158 /// If Expr computes ~A, return A else return nullptr 4159 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4160 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4161 if (!Add || Add->getNumOperands() != 2 || 4162 !Add->getOperand(0)->isAllOnesValue()) 4163 return nullptr; 4164 4165 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4166 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4167 !AddRHS->getOperand(0)->isAllOnesValue()) 4168 return nullptr; 4169 4170 return AddRHS->getOperand(1); 4171 } 4172 4173 /// Return a SCEV corresponding to ~V = -1-V 4174 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4175 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4176 4177 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4178 return getConstant( 4179 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4180 4181 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4182 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4183 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4184 SmallVector<const SCEV *, 2> MatchedOperands; 4185 for (const SCEV *Operand : MME->operands()) { 4186 const SCEV *Matched = MatchNotExpr(Operand); 4187 if (!Matched) 4188 return (const SCEV *)nullptr; 4189 MatchedOperands.push_back(Matched); 4190 } 4191 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4192 MatchedOperands); 4193 }; 4194 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4195 return Replaced; 4196 } 4197 4198 Type *Ty = V->getType(); 4199 Ty = getEffectiveSCEVType(Ty); 4200 return getMinusSCEV(getMinusOne(Ty), V); 4201 } 4202 4203 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4204 assert(P->getType()->isPointerTy()); 4205 4206 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4207 // The base of an AddRec is the first operand. 4208 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4209 Ops[0] = removePointerBase(Ops[0]); 4210 // Don't try to transfer nowrap flags for now. We could in some cases 4211 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4212 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4213 } 4214 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4215 // The base of an Add is the pointer operand. 4216 SmallVector<const SCEV *> Ops{Add->operands()}; 4217 const SCEV **PtrOp = nullptr; 4218 for (const SCEV *&AddOp : Ops) { 4219 if (AddOp->getType()->isPointerTy()) { 4220 assert(!PtrOp && "Cannot have multiple pointer ops"); 4221 PtrOp = &AddOp; 4222 } 4223 } 4224 *PtrOp = removePointerBase(*PtrOp); 4225 // Don't try to transfer nowrap flags for now. We could in some cases 4226 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4227 return getAddExpr(Ops); 4228 } 4229 // Any other expression must be a pointer base. 4230 return getZero(P->getType()); 4231 } 4232 4233 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4234 SCEV::NoWrapFlags Flags, 4235 unsigned Depth) { 4236 // Fast path: X - X --> 0. 4237 if (LHS == RHS) 4238 return getZero(LHS->getType()); 4239 4240 // If we subtract two pointers with different pointer bases, bail. 4241 // Eventually, we're going to add an assertion to getMulExpr that we 4242 // can't multiply by a pointer. 4243 if (RHS->getType()->isPointerTy()) { 4244 if (!LHS->getType()->isPointerTy() || 4245 getPointerBase(LHS) != getPointerBase(RHS)) 4246 return getCouldNotCompute(); 4247 LHS = removePointerBase(LHS); 4248 RHS = removePointerBase(RHS); 4249 } 4250 4251 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4252 // makes it so that we cannot make much use of NUW. 4253 auto AddFlags = SCEV::FlagAnyWrap; 4254 const bool RHSIsNotMinSigned = 4255 !getSignedRangeMin(RHS).isMinSignedValue(); 4256 if (hasFlags(Flags, SCEV::FlagNSW)) { 4257 // Let M be the minimum representable signed value. Then (-1)*RHS 4258 // signed-wraps if and only if RHS is M. That can happen even for 4259 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4260 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4261 // (-1)*RHS, we need to prove that RHS != M. 4262 // 4263 // If LHS is non-negative and we know that LHS - RHS does not 4264 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4265 // either by proving that RHS > M or that LHS >= 0. 4266 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4267 AddFlags = SCEV::FlagNSW; 4268 } 4269 } 4270 4271 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4272 // RHS is NSW and LHS >= 0. 4273 // 4274 // The difficulty here is that the NSW flag may have been proven 4275 // relative to a loop that is to be found in a recurrence in LHS and 4276 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4277 // larger scope than intended. 4278 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4279 4280 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4281 } 4282 4283 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4284 unsigned Depth) { 4285 Type *SrcTy = V->getType(); 4286 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4287 "Cannot truncate or zero extend with non-integer arguments!"); 4288 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4289 return V; // No conversion 4290 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4291 return getTruncateExpr(V, Ty, Depth); 4292 return getZeroExtendExpr(V, Ty, Depth); 4293 } 4294 4295 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4296 unsigned Depth) { 4297 Type *SrcTy = V->getType(); 4298 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4299 "Cannot truncate or zero extend with non-integer arguments!"); 4300 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4301 return V; // No conversion 4302 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4303 return getTruncateExpr(V, Ty, Depth); 4304 return getSignExtendExpr(V, Ty, Depth); 4305 } 4306 4307 const SCEV * 4308 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4309 Type *SrcTy = V->getType(); 4310 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4311 "Cannot noop or zero extend with non-integer arguments!"); 4312 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4313 "getNoopOrZeroExtend cannot truncate!"); 4314 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4315 return V; // No conversion 4316 return getZeroExtendExpr(V, Ty); 4317 } 4318 4319 const SCEV * 4320 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4321 Type *SrcTy = V->getType(); 4322 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4323 "Cannot noop or sign extend with non-integer arguments!"); 4324 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4325 "getNoopOrSignExtend cannot truncate!"); 4326 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4327 return V; // No conversion 4328 return getSignExtendExpr(V, Ty); 4329 } 4330 4331 const SCEV * 4332 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4333 Type *SrcTy = V->getType(); 4334 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4335 "Cannot noop or any extend with non-integer arguments!"); 4336 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4337 "getNoopOrAnyExtend cannot truncate!"); 4338 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4339 return V; // No conversion 4340 return getAnyExtendExpr(V, Ty); 4341 } 4342 4343 const SCEV * 4344 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4345 Type *SrcTy = V->getType(); 4346 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4347 "Cannot truncate or noop with non-integer arguments!"); 4348 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4349 "getTruncateOrNoop cannot extend!"); 4350 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4351 return V; // No conversion 4352 return getTruncateExpr(V, Ty); 4353 } 4354 4355 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4356 const SCEV *RHS) { 4357 const SCEV *PromotedLHS = LHS; 4358 const SCEV *PromotedRHS = RHS; 4359 4360 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4361 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4362 else 4363 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4364 4365 return getUMaxExpr(PromotedLHS, PromotedRHS); 4366 } 4367 4368 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4369 const SCEV *RHS) { 4370 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4371 return getUMinFromMismatchedTypes(Ops); 4372 } 4373 4374 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4375 SmallVectorImpl<const SCEV *> &Ops) { 4376 assert(!Ops.empty() && "At least one operand must be!"); 4377 // Trivial case. 4378 if (Ops.size() == 1) 4379 return Ops[0]; 4380 4381 // Find the max type first. 4382 Type *MaxType = nullptr; 4383 for (auto *S : Ops) 4384 if (MaxType) 4385 MaxType = getWiderType(MaxType, S->getType()); 4386 else 4387 MaxType = S->getType(); 4388 assert(MaxType && "Failed to find maximum type!"); 4389 4390 // Extend all ops to max type. 4391 SmallVector<const SCEV *, 2> PromotedOps; 4392 for (auto *S : Ops) 4393 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4394 4395 // Generate umin. 4396 return getUMinExpr(PromotedOps); 4397 } 4398 4399 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4400 // A pointer operand may evaluate to a nonpointer expression, such as null. 4401 if (!V->getType()->isPointerTy()) 4402 return V; 4403 4404 while (true) { 4405 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4406 V = AddRec->getStart(); 4407 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4408 const SCEV *PtrOp = nullptr; 4409 for (const SCEV *AddOp : Add->operands()) { 4410 if (AddOp->getType()->isPointerTy()) { 4411 assert(!PtrOp && "Cannot have multiple pointer ops"); 4412 PtrOp = AddOp; 4413 } 4414 } 4415 assert(PtrOp && "Must have pointer op"); 4416 V = PtrOp; 4417 } else // Not something we can look further into. 4418 return V; 4419 } 4420 } 4421 4422 /// Push users of the given Instruction onto the given Worklist. 4423 static void PushDefUseChildren(Instruction *I, 4424 SmallVectorImpl<Instruction *> &Worklist, 4425 SmallPtrSetImpl<Instruction *> &Visited) { 4426 // Push the def-use children onto the Worklist stack. 4427 for (User *U : I->users()) { 4428 auto *UserInsn = cast<Instruction>(U); 4429 if (Visited.insert(UserInsn).second) 4430 Worklist.push_back(UserInsn); 4431 } 4432 } 4433 4434 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4435 SmallVector<Instruction *, 16> Worklist; 4436 SmallPtrSet<Instruction *, 8> Visited; 4437 SmallVector<const SCEV *, 8> ToForget; 4438 Visited.insert(PN); 4439 Worklist.push_back(PN); 4440 while (!Worklist.empty()) { 4441 Instruction *I = Worklist.pop_back_val(); 4442 4443 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4444 if (It != ValueExprMap.end()) { 4445 const SCEV *Old = It->second; 4446 4447 // Short-circuit the def-use traversal if the symbolic name 4448 // ceases to appear in expressions. 4449 if (Old != SymName && !hasOperand(Old, SymName)) 4450 continue; 4451 4452 // SCEVUnknown for a PHI either means that it has an unrecognized 4453 // structure, it's a PHI that's in the progress of being computed 4454 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4455 // additional loop trip count information isn't going to change anything. 4456 // In the second case, createNodeForPHI will perform the necessary 4457 // updates on its own when it gets to that point. In the third, we do 4458 // want to forget the SCEVUnknown. 4459 if (!isa<PHINode>(I) || 4460 !isa<SCEVUnknown>(Old) || 4461 (I != PN && Old == SymName)) { 4462 eraseValueFromMap(It->first); 4463 ToForget.push_back(Old); 4464 } 4465 } 4466 4467 PushDefUseChildren(I, Worklist, Visited); 4468 } 4469 forgetMemoizedResults(ToForget); 4470 } 4471 4472 namespace { 4473 4474 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4475 /// expression in case its Loop is L. If it is not L then 4476 /// if IgnoreOtherLoops is true then use AddRec itself 4477 /// otherwise rewrite cannot be done. 4478 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4479 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4480 public: 4481 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4482 bool IgnoreOtherLoops = true) { 4483 SCEVInitRewriter Rewriter(L, SE); 4484 const SCEV *Result = Rewriter.visit(S); 4485 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4486 return SE.getCouldNotCompute(); 4487 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4488 ? SE.getCouldNotCompute() 4489 : Result; 4490 } 4491 4492 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4493 if (!SE.isLoopInvariant(Expr, L)) 4494 SeenLoopVariantSCEVUnknown = true; 4495 return Expr; 4496 } 4497 4498 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4499 // Only re-write AddRecExprs for this loop. 4500 if (Expr->getLoop() == L) 4501 return Expr->getStart(); 4502 SeenOtherLoops = true; 4503 return Expr; 4504 } 4505 4506 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4507 4508 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4509 4510 private: 4511 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4512 : SCEVRewriteVisitor(SE), L(L) {} 4513 4514 const Loop *L; 4515 bool SeenLoopVariantSCEVUnknown = false; 4516 bool SeenOtherLoops = false; 4517 }; 4518 4519 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4520 /// increment expression in case its Loop is L. If it is not L then 4521 /// use AddRec itself. 4522 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4523 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4524 public: 4525 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4526 SCEVPostIncRewriter Rewriter(L, SE); 4527 const SCEV *Result = Rewriter.visit(S); 4528 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4529 ? SE.getCouldNotCompute() 4530 : Result; 4531 } 4532 4533 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4534 if (!SE.isLoopInvariant(Expr, L)) 4535 SeenLoopVariantSCEVUnknown = true; 4536 return Expr; 4537 } 4538 4539 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4540 // Only re-write AddRecExprs for this loop. 4541 if (Expr->getLoop() == L) 4542 return Expr->getPostIncExpr(SE); 4543 SeenOtherLoops = true; 4544 return Expr; 4545 } 4546 4547 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4548 4549 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4550 4551 private: 4552 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4553 : SCEVRewriteVisitor(SE), L(L) {} 4554 4555 const Loop *L; 4556 bool SeenLoopVariantSCEVUnknown = false; 4557 bool SeenOtherLoops = false; 4558 }; 4559 4560 /// This class evaluates the compare condition by matching it against the 4561 /// condition of loop latch. If there is a match we assume a true value 4562 /// for the condition while building SCEV nodes. 4563 class SCEVBackedgeConditionFolder 4564 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4565 public: 4566 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4567 ScalarEvolution &SE) { 4568 bool IsPosBECond = false; 4569 Value *BECond = nullptr; 4570 if (BasicBlock *Latch = L->getLoopLatch()) { 4571 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4572 if (BI && BI->isConditional()) { 4573 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4574 "Both outgoing branches should not target same header!"); 4575 BECond = BI->getCondition(); 4576 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4577 } else { 4578 return S; 4579 } 4580 } 4581 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4582 return Rewriter.visit(S); 4583 } 4584 4585 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4586 const SCEV *Result = Expr; 4587 bool InvariantF = SE.isLoopInvariant(Expr, L); 4588 4589 if (!InvariantF) { 4590 Instruction *I = cast<Instruction>(Expr->getValue()); 4591 switch (I->getOpcode()) { 4592 case Instruction::Select: { 4593 SelectInst *SI = cast<SelectInst>(I); 4594 Optional<const SCEV *> Res = 4595 compareWithBackedgeCondition(SI->getCondition()); 4596 if (Res.hasValue()) { 4597 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4598 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4599 } 4600 break; 4601 } 4602 default: { 4603 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4604 if (Res.hasValue()) 4605 Result = Res.getValue(); 4606 break; 4607 } 4608 } 4609 } 4610 return Result; 4611 } 4612 4613 private: 4614 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4615 bool IsPosBECond, ScalarEvolution &SE) 4616 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4617 IsPositiveBECond(IsPosBECond) {} 4618 4619 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4620 4621 const Loop *L; 4622 /// Loop back condition. 4623 Value *BackedgeCond = nullptr; 4624 /// Set to true if loop back is on positive branch condition. 4625 bool IsPositiveBECond; 4626 }; 4627 4628 Optional<const SCEV *> 4629 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4630 4631 // If value matches the backedge condition for loop latch, 4632 // then return a constant evolution node based on loopback 4633 // branch taken. 4634 if (BackedgeCond == IC) 4635 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4636 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4637 return None; 4638 } 4639 4640 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4641 public: 4642 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4643 ScalarEvolution &SE) { 4644 SCEVShiftRewriter Rewriter(L, SE); 4645 const SCEV *Result = Rewriter.visit(S); 4646 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4647 } 4648 4649 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4650 // Only allow AddRecExprs for this loop. 4651 if (!SE.isLoopInvariant(Expr, L)) 4652 Valid = false; 4653 return Expr; 4654 } 4655 4656 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4657 if (Expr->getLoop() == L && Expr->isAffine()) 4658 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4659 Valid = false; 4660 return Expr; 4661 } 4662 4663 bool isValid() { return Valid; } 4664 4665 private: 4666 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4667 : SCEVRewriteVisitor(SE), L(L) {} 4668 4669 const Loop *L; 4670 bool Valid = true; 4671 }; 4672 4673 } // end anonymous namespace 4674 4675 SCEV::NoWrapFlags 4676 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4677 if (!AR->isAffine()) 4678 return SCEV::FlagAnyWrap; 4679 4680 using OBO = OverflowingBinaryOperator; 4681 4682 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4683 4684 if (!AR->hasNoSignedWrap()) { 4685 ConstantRange AddRecRange = getSignedRange(AR); 4686 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4687 4688 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4689 Instruction::Add, IncRange, OBO::NoSignedWrap); 4690 if (NSWRegion.contains(AddRecRange)) 4691 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4692 } 4693 4694 if (!AR->hasNoUnsignedWrap()) { 4695 ConstantRange AddRecRange = getUnsignedRange(AR); 4696 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4697 4698 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4699 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4700 if (NUWRegion.contains(AddRecRange)) 4701 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4702 } 4703 4704 return Result; 4705 } 4706 4707 SCEV::NoWrapFlags 4708 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4709 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4710 4711 if (AR->hasNoSignedWrap()) 4712 return Result; 4713 4714 if (!AR->isAffine()) 4715 return Result; 4716 4717 const SCEV *Step = AR->getStepRecurrence(*this); 4718 const Loop *L = AR->getLoop(); 4719 4720 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4721 // Note that this serves two purposes: It filters out loops that are 4722 // simply not analyzable, and it covers the case where this code is 4723 // being called from within backedge-taken count analysis, such that 4724 // attempting to ask for the backedge-taken count would likely result 4725 // in infinite recursion. In the later case, the analysis code will 4726 // cope with a conservative value, and it will take care to purge 4727 // that value once it has finished. 4728 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4729 4730 // Normally, in the cases we can prove no-overflow via a 4731 // backedge guarding condition, we can also compute a backedge 4732 // taken count for the loop. The exceptions are assumptions and 4733 // guards present in the loop -- SCEV is not great at exploiting 4734 // these to compute max backedge taken counts, but can still use 4735 // these to prove lack of overflow. Use this fact to avoid 4736 // doing extra work that may not pay off. 4737 4738 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4739 AC.assumptions().empty()) 4740 return Result; 4741 4742 // If the backedge is guarded by a comparison with the pre-inc value the 4743 // addrec is safe. Also, if the entry is guarded by a comparison with the 4744 // start value and the backedge is guarded by a comparison with the post-inc 4745 // value, the addrec is safe. 4746 ICmpInst::Predicate Pred; 4747 const SCEV *OverflowLimit = 4748 getSignedOverflowLimitForStep(Step, &Pred, this); 4749 if (OverflowLimit && 4750 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4751 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4752 Result = setFlags(Result, SCEV::FlagNSW); 4753 } 4754 return Result; 4755 } 4756 SCEV::NoWrapFlags 4757 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4758 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4759 4760 if (AR->hasNoUnsignedWrap()) 4761 return Result; 4762 4763 if (!AR->isAffine()) 4764 return Result; 4765 4766 const SCEV *Step = AR->getStepRecurrence(*this); 4767 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4768 const Loop *L = AR->getLoop(); 4769 4770 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4771 // Note that this serves two purposes: It filters out loops that are 4772 // simply not analyzable, and it covers the case where this code is 4773 // being called from within backedge-taken count analysis, such that 4774 // attempting to ask for the backedge-taken count would likely result 4775 // in infinite recursion. In the later case, the analysis code will 4776 // cope with a conservative value, and it will take care to purge 4777 // that value once it has finished. 4778 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4779 4780 // Normally, in the cases we can prove no-overflow via a 4781 // backedge guarding condition, we can also compute a backedge 4782 // taken count for the loop. The exceptions are assumptions and 4783 // guards present in the loop -- SCEV is not great at exploiting 4784 // these to compute max backedge taken counts, but can still use 4785 // these to prove lack of overflow. Use this fact to avoid 4786 // doing extra work that may not pay off. 4787 4788 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4789 AC.assumptions().empty()) 4790 return Result; 4791 4792 // If the backedge is guarded by a comparison with the pre-inc value the 4793 // addrec is safe. Also, if the entry is guarded by a comparison with the 4794 // start value and the backedge is guarded by a comparison with the post-inc 4795 // value, the addrec is safe. 4796 if (isKnownPositive(Step)) { 4797 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4798 getUnsignedRangeMax(Step)); 4799 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4800 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4801 Result = setFlags(Result, SCEV::FlagNUW); 4802 } 4803 } 4804 4805 return Result; 4806 } 4807 4808 namespace { 4809 4810 /// Represents an abstract binary operation. This may exist as a 4811 /// normal instruction or constant expression, or may have been 4812 /// derived from an expression tree. 4813 struct BinaryOp { 4814 unsigned Opcode; 4815 Value *LHS; 4816 Value *RHS; 4817 bool IsNSW = false; 4818 bool IsNUW = false; 4819 4820 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4821 /// constant expression. 4822 Operator *Op = nullptr; 4823 4824 explicit BinaryOp(Operator *Op) 4825 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4826 Op(Op) { 4827 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4828 IsNSW = OBO->hasNoSignedWrap(); 4829 IsNUW = OBO->hasNoUnsignedWrap(); 4830 } 4831 } 4832 4833 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4834 bool IsNUW = false) 4835 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4836 }; 4837 4838 } // end anonymous namespace 4839 4840 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4841 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4842 auto *Op = dyn_cast<Operator>(V); 4843 if (!Op) 4844 return None; 4845 4846 // Implementation detail: all the cleverness here should happen without 4847 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4848 // SCEV expressions when possible, and we should not break that. 4849 4850 switch (Op->getOpcode()) { 4851 case Instruction::Add: 4852 case Instruction::Sub: 4853 case Instruction::Mul: 4854 case Instruction::UDiv: 4855 case Instruction::URem: 4856 case Instruction::And: 4857 case Instruction::Or: 4858 case Instruction::AShr: 4859 case Instruction::Shl: 4860 return BinaryOp(Op); 4861 4862 case Instruction::Xor: 4863 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4864 // If the RHS of the xor is a signmask, then this is just an add. 4865 // Instcombine turns add of signmask into xor as a strength reduction step. 4866 if (RHSC->getValue().isSignMask()) 4867 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4868 return BinaryOp(Op); 4869 4870 case Instruction::LShr: 4871 // Turn logical shift right of a constant into a unsigned divide. 4872 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4873 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4874 4875 // If the shift count is not less than the bitwidth, the result of 4876 // the shift is undefined. Don't try to analyze it, because the 4877 // resolution chosen here may differ from the resolution chosen in 4878 // other parts of the compiler. 4879 if (SA->getValue().ult(BitWidth)) { 4880 Constant *X = 4881 ConstantInt::get(SA->getContext(), 4882 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4883 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4884 } 4885 } 4886 return BinaryOp(Op); 4887 4888 case Instruction::ExtractValue: { 4889 auto *EVI = cast<ExtractValueInst>(Op); 4890 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4891 break; 4892 4893 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4894 if (!WO) 4895 break; 4896 4897 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4898 bool Signed = WO->isSigned(); 4899 // TODO: Should add nuw/nsw flags for mul as well. 4900 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4901 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4902 4903 // Now that we know that all uses of the arithmetic-result component of 4904 // CI are guarded by the overflow check, we can go ahead and pretend 4905 // that the arithmetic is non-overflowing. 4906 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4907 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4908 } 4909 4910 default: 4911 break; 4912 } 4913 4914 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4915 // semantics as a Sub, return a binary sub expression. 4916 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4917 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4918 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4919 4920 return None; 4921 } 4922 4923 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4924 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4925 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4926 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4927 /// follows one of the following patterns: 4928 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4929 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4930 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4931 /// we return the type of the truncation operation, and indicate whether the 4932 /// truncated type should be treated as signed/unsigned by setting 4933 /// \p Signed to true/false, respectively. 4934 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4935 bool &Signed, ScalarEvolution &SE) { 4936 // The case where Op == SymbolicPHI (that is, with no type conversions on 4937 // the way) is handled by the regular add recurrence creating logic and 4938 // would have already been triggered in createAddRecForPHI. Reaching it here 4939 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4940 // because one of the other operands of the SCEVAddExpr updating this PHI is 4941 // not invariant). 4942 // 4943 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4944 // this case predicates that allow us to prove that Op == SymbolicPHI will 4945 // be added. 4946 if (Op == SymbolicPHI) 4947 return nullptr; 4948 4949 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4950 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4951 if (SourceBits != NewBits) 4952 return nullptr; 4953 4954 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4955 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4956 if (!SExt && !ZExt) 4957 return nullptr; 4958 const SCEVTruncateExpr *Trunc = 4959 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4960 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4961 if (!Trunc) 4962 return nullptr; 4963 const SCEV *X = Trunc->getOperand(); 4964 if (X != SymbolicPHI) 4965 return nullptr; 4966 Signed = SExt != nullptr; 4967 return Trunc->getType(); 4968 } 4969 4970 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4971 if (!PN->getType()->isIntegerTy()) 4972 return nullptr; 4973 const Loop *L = LI.getLoopFor(PN->getParent()); 4974 if (!L || L->getHeader() != PN->getParent()) 4975 return nullptr; 4976 return L; 4977 } 4978 4979 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4980 // computation that updates the phi follows the following pattern: 4981 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4982 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4983 // If so, try to see if it can be rewritten as an AddRecExpr under some 4984 // Predicates. If successful, return them as a pair. Also cache the results 4985 // of the analysis. 4986 // 4987 // Example usage scenario: 4988 // Say the Rewriter is called for the following SCEV: 4989 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4990 // where: 4991 // %X = phi i64 (%Start, %BEValue) 4992 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4993 // and call this function with %SymbolicPHI = %X. 4994 // 4995 // The analysis will find that the value coming around the backedge has 4996 // the following SCEV: 4997 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4998 // Upon concluding that this matches the desired pattern, the function 4999 // will return the pair {NewAddRec, SmallPredsVec} where: 5000 // NewAddRec = {%Start,+,%Step} 5001 // SmallPredsVec = {P1, P2, P3} as follows: 5002 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 5003 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 5004 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 5005 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 5006 // under the predicates {P1,P2,P3}. 5007 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 5008 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 5009 // 5010 // TODO's: 5011 // 5012 // 1) Extend the Induction descriptor to also support inductions that involve 5013 // casts: When needed (namely, when we are called in the context of the 5014 // vectorizer induction analysis), a Set of cast instructions will be 5015 // populated by this method, and provided back to isInductionPHI. This is 5016 // needed to allow the vectorizer to properly record them to be ignored by 5017 // the cost model and to avoid vectorizing them (otherwise these casts, 5018 // which are redundant under the runtime overflow checks, will be 5019 // vectorized, which can be costly). 5020 // 5021 // 2) Support additional induction/PHISCEV patterns: We also want to support 5022 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5023 // after the induction update operation (the induction increment): 5024 // 5025 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5026 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5027 // 5028 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5029 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5030 // 5031 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5032 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5033 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5034 SmallVector<const SCEVPredicate *, 3> Predicates; 5035 5036 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5037 // return an AddRec expression under some predicate. 5038 5039 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5040 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5041 assert(L && "Expecting an integer loop header phi"); 5042 5043 // The loop may have multiple entrances or multiple exits; we can analyze 5044 // this phi as an addrec if it has a unique entry value and a unique 5045 // backedge value. 5046 Value *BEValueV = nullptr, *StartValueV = nullptr; 5047 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5048 Value *V = PN->getIncomingValue(i); 5049 if (L->contains(PN->getIncomingBlock(i))) { 5050 if (!BEValueV) { 5051 BEValueV = V; 5052 } else if (BEValueV != V) { 5053 BEValueV = nullptr; 5054 break; 5055 } 5056 } else if (!StartValueV) { 5057 StartValueV = V; 5058 } else if (StartValueV != V) { 5059 StartValueV = nullptr; 5060 break; 5061 } 5062 } 5063 if (!BEValueV || !StartValueV) 5064 return None; 5065 5066 const SCEV *BEValue = getSCEV(BEValueV); 5067 5068 // If the value coming around the backedge is an add with the symbolic 5069 // value we just inserted, possibly with casts that we can ignore under 5070 // an appropriate runtime guard, then we found a simple induction variable! 5071 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5072 if (!Add) 5073 return None; 5074 5075 // If there is a single occurrence of the symbolic value, possibly 5076 // casted, replace it with a recurrence. 5077 unsigned FoundIndex = Add->getNumOperands(); 5078 Type *TruncTy = nullptr; 5079 bool Signed; 5080 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5081 if ((TruncTy = 5082 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5083 if (FoundIndex == e) { 5084 FoundIndex = i; 5085 break; 5086 } 5087 5088 if (FoundIndex == Add->getNumOperands()) 5089 return None; 5090 5091 // Create an add with everything but the specified operand. 5092 SmallVector<const SCEV *, 8> Ops; 5093 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5094 if (i != FoundIndex) 5095 Ops.push_back(Add->getOperand(i)); 5096 const SCEV *Accum = getAddExpr(Ops); 5097 5098 // The runtime checks will not be valid if the step amount is 5099 // varying inside the loop. 5100 if (!isLoopInvariant(Accum, L)) 5101 return None; 5102 5103 // *** Part2: Create the predicates 5104 5105 // Analysis was successful: we have a phi-with-cast pattern for which we 5106 // can return an AddRec expression under the following predicates: 5107 // 5108 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5109 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5110 // P2: An Equal predicate that guarantees that 5111 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5112 // P3: An Equal predicate that guarantees that 5113 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5114 // 5115 // As we next prove, the above predicates guarantee that: 5116 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5117 // 5118 // 5119 // More formally, we want to prove that: 5120 // Expr(i+1) = Start + (i+1) * Accum 5121 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5122 // 5123 // Given that: 5124 // 1) Expr(0) = Start 5125 // 2) Expr(1) = Start + Accum 5126 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5127 // 3) Induction hypothesis (step i): 5128 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5129 // 5130 // Proof: 5131 // Expr(i+1) = 5132 // = Start + (i+1)*Accum 5133 // = (Start + i*Accum) + Accum 5134 // = Expr(i) + Accum 5135 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5136 // :: from step i 5137 // 5138 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5139 // 5140 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5141 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5142 // + Accum :: from P3 5143 // 5144 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5145 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5146 // 5147 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5148 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5149 // 5150 // By induction, the same applies to all iterations 1<=i<n: 5151 // 5152 5153 // Create a truncated addrec for which we will add a no overflow check (P1). 5154 const SCEV *StartVal = getSCEV(StartValueV); 5155 const SCEV *PHISCEV = 5156 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5157 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5158 5159 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5160 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5161 // will be constant. 5162 // 5163 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5164 // add P1. 5165 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5166 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5167 Signed ? SCEVWrapPredicate::IncrementNSSW 5168 : SCEVWrapPredicate::IncrementNUSW; 5169 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5170 Predicates.push_back(AddRecPred); 5171 } 5172 5173 // Create the Equal Predicates P2,P3: 5174 5175 // It is possible that the predicates P2 and/or P3 are computable at 5176 // compile time due to StartVal and/or Accum being constants. 5177 // If either one is, then we can check that now and escape if either P2 5178 // or P3 is false. 5179 5180 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5181 // for each of StartVal and Accum 5182 auto getExtendedExpr = [&](const SCEV *Expr, 5183 bool CreateSignExtend) -> const SCEV * { 5184 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5185 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5186 const SCEV *ExtendedExpr = 5187 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5188 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5189 return ExtendedExpr; 5190 }; 5191 5192 // Given: 5193 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5194 // = getExtendedExpr(Expr) 5195 // Determine whether the predicate P: Expr == ExtendedExpr 5196 // is known to be false at compile time 5197 auto PredIsKnownFalse = [&](const SCEV *Expr, 5198 const SCEV *ExtendedExpr) -> bool { 5199 return Expr != ExtendedExpr && 5200 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5201 }; 5202 5203 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5204 if (PredIsKnownFalse(StartVal, StartExtended)) { 5205 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5206 return None; 5207 } 5208 5209 // The Step is always Signed (because the overflow checks are either 5210 // NSSW or NUSW) 5211 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5212 if (PredIsKnownFalse(Accum, AccumExtended)) { 5213 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5214 return None; 5215 } 5216 5217 auto AppendPredicate = [&](const SCEV *Expr, 5218 const SCEV *ExtendedExpr) -> void { 5219 if (Expr != ExtendedExpr && 5220 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5221 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5222 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5223 Predicates.push_back(Pred); 5224 } 5225 }; 5226 5227 AppendPredicate(StartVal, StartExtended); 5228 AppendPredicate(Accum, AccumExtended); 5229 5230 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5231 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5232 // into NewAR if it will also add the runtime overflow checks specified in 5233 // Predicates. 5234 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5235 5236 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5237 std::make_pair(NewAR, Predicates); 5238 // Remember the result of the analysis for this SCEV at this locayyytion. 5239 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5240 return PredRewrite; 5241 } 5242 5243 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5244 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5245 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5246 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5247 if (!L) 5248 return None; 5249 5250 // Check to see if we already analyzed this PHI. 5251 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5252 if (I != PredicatedSCEVRewrites.end()) { 5253 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5254 I->second; 5255 // Analysis was done before and failed to create an AddRec: 5256 if (Rewrite.first == SymbolicPHI) 5257 return None; 5258 // Analysis was done before and succeeded to create an AddRec under 5259 // a predicate: 5260 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5261 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5262 return Rewrite; 5263 } 5264 5265 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5266 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5267 5268 // Record in the cache that the analysis failed 5269 if (!Rewrite) { 5270 SmallVector<const SCEVPredicate *, 3> Predicates; 5271 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5272 return None; 5273 } 5274 5275 return Rewrite; 5276 } 5277 5278 // FIXME: This utility is currently required because the Rewriter currently 5279 // does not rewrite this expression: 5280 // {0, +, (sext ix (trunc iy to ix) to iy)} 5281 // into {0, +, %step}, 5282 // even when the following Equal predicate exists: 5283 // "%step == (sext ix (trunc iy to ix) to iy)". 5284 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5285 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5286 if (AR1 == AR2) 5287 return true; 5288 5289 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5290 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5291 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5292 return false; 5293 return true; 5294 }; 5295 5296 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5297 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5298 return false; 5299 return true; 5300 } 5301 5302 /// A helper function for createAddRecFromPHI to handle simple cases. 5303 /// 5304 /// This function tries to find an AddRec expression for the simplest (yet most 5305 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5306 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5307 /// technique for finding the AddRec expression. 5308 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5309 Value *BEValueV, 5310 Value *StartValueV) { 5311 const Loop *L = LI.getLoopFor(PN->getParent()); 5312 assert(L && L->getHeader() == PN->getParent()); 5313 assert(BEValueV && StartValueV); 5314 5315 auto BO = MatchBinaryOp(BEValueV, DT); 5316 if (!BO) 5317 return nullptr; 5318 5319 if (BO->Opcode != Instruction::Add) 5320 return nullptr; 5321 5322 const SCEV *Accum = nullptr; 5323 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5324 Accum = getSCEV(BO->RHS); 5325 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5326 Accum = getSCEV(BO->LHS); 5327 5328 if (!Accum) 5329 return nullptr; 5330 5331 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5332 if (BO->IsNUW) 5333 Flags = setFlags(Flags, SCEV::FlagNUW); 5334 if (BO->IsNSW) 5335 Flags = setFlags(Flags, SCEV::FlagNSW); 5336 5337 const SCEV *StartVal = getSCEV(StartValueV); 5338 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5339 5340 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5341 5342 // We can add Flags to the post-inc expression only if we 5343 // know that it is *undefined behavior* for BEValueV to 5344 // overflow. 5345 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5346 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5347 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5348 5349 return PHISCEV; 5350 } 5351 5352 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5353 const Loop *L = LI.getLoopFor(PN->getParent()); 5354 if (!L || L->getHeader() != PN->getParent()) 5355 return nullptr; 5356 5357 // The loop may have multiple entrances or multiple exits; we can analyze 5358 // this phi as an addrec if it has a unique entry value and a unique 5359 // backedge value. 5360 Value *BEValueV = nullptr, *StartValueV = nullptr; 5361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5362 Value *V = PN->getIncomingValue(i); 5363 if (L->contains(PN->getIncomingBlock(i))) { 5364 if (!BEValueV) { 5365 BEValueV = V; 5366 } else if (BEValueV != V) { 5367 BEValueV = nullptr; 5368 break; 5369 } 5370 } else if (!StartValueV) { 5371 StartValueV = V; 5372 } else if (StartValueV != V) { 5373 StartValueV = nullptr; 5374 break; 5375 } 5376 } 5377 if (!BEValueV || !StartValueV) 5378 return nullptr; 5379 5380 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5381 "PHI node already processed?"); 5382 5383 // First, try to find AddRec expression without creating a fictituos symbolic 5384 // value for PN. 5385 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5386 return S; 5387 5388 // Handle PHI node value symbolically. 5389 const SCEV *SymbolicName = getUnknown(PN); 5390 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5391 5392 // Using this symbolic name for the PHI, analyze the value coming around 5393 // the back-edge. 5394 const SCEV *BEValue = getSCEV(BEValueV); 5395 5396 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5397 // has a special value for the first iteration of the loop. 5398 5399 // If the value coming around the backedge is an add with the symbolic 5400 // value we just inserted, then we found a simple induction variable! 5401 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5402 // If there is a single occurrence of the symbolic value, replace it 5403 // with a recurrence. 5404 unsigned FoundIndex = Add->getNumOperands(); 5405 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5406 if (Add->getOperand(i) == SymbolicName) 5407 if (FoundIndex == e) { 5408 FoundIndex = i; 5409 break; 5410 } 5411 5412 if (FoundIndex != Add->getNumOperands()) { 5413 // Create an add with everything but the specified operand. 5414 SmallVector<const SCEV *, 8> Ops; 5415 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5416 if (i != FoundIndex) 5417 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5418 L, *this)); 5419 const SCEV *Accum = getAddExpr(Ops); 5420 5421 // This is not a valid addrec if the step amount is varying each 5422 // loop iteration, but is not itself an addrec in this loop. 5423 if (isLoopInvariant(Accum, L) || 5424 (isa<SCEVAddRecExpr>(Accum) && 5425 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5426 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5427 5428 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5429 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5430 if (BO->IsNUW) 5431 Flags = setFlags(Flags, SCEV::FlagNUW); 5432 if (BO->IsNSW) 5433 Flags = setFlags(Flags, SCEV::FlagNSW); 5434 } 5435 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5436 // If the increment is an inbounds GEP, then we know the address 5437 // space cannot be wrapped around. We cannot make any guarantee 5438 // about signed or unsigned overflow because pointers are 5439 // unsigned but we may have a negative index from the base 5440 // pointer. We can guarantee that no unsigned wrap occurs if the 5441 // indices form a positive value. 5442 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5443 Flags = setFlags(Flags, SCEV::FlagNW); 5444 5445 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5446 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5447 Flags = setFlags(Flags, SCEV::FlagNUW); 5448 } 5449 5450 // We cannot transfer nuw and nsw flags from subtraction 5451 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5452 // for instance. 5453 } 5454 5455 const SCEV *StartVal = getSCEV(StartValueV); 5456 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5457 5458 // Okay, for the entire analysis of this edge we assumed the PHI 5459 // to be symbolic. We now need to go back and purge all of the 5460 // entries for the scalars that use the symbolic expression. 5461 forgetSymbolicName(PN, SymbolicName); 5462 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5463 5464 // We can add Flags to the post-inc expression only if we 5465 // know that it is *undefined behavior* for BEValueV to 5466 // overflow. 5467 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5468 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5469 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5470 5471 return PHISCEV; 5472 } 5473 } 5474 } else { 5475 // Otherwise, this could be a loop like this: 5476 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5477 // In this case, j = {1,+,1} and BEValue is j. 5478 // Because the other in-value of i (0) fits the evolution of BEValue 5479 // i really is an addrec evolution. 5480 // 5481 // We can generalize this saying that i is the shifted value of BEValue 5482 // by one iteration: 5483 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5484 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5485 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5486 if (Shifted != getCouldNotCompute() && 5487 Start != getCouldNotCompute()) { 5488 const SCEV *StartVal = getSCEV(StartValueV); 5489 if (Start == StartVal) { 5490 // Okay, for the entire analysis of this edge we assumed the PHI 5491 // to be symbolic. We now need to go back and purge all of the 5492 // entries for the scalars that use the symbolic expression. 5493 forgetSymbolicName(PN, SymbolicName); 5494 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5495 return Shifted; 5496 } 5497 } 5498 } 5499 5500 // Remove the temporary PHI node SCEV that has been inserted while intending 5501 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5502 // as it will prevent later (possibly simpler) SCEV expressions to be added 5503 // to the ValueExprMap. 5504 eraseValueFromMap(PN); 5505 5506 return nullptr; 5507 } 5508 5509 // Checks if the SCEV S is available at BB. S is considered available at BB 5510 // if S can be materialized at BB without introducing a fault. 5511 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5512 BasicBlock *BB) { 5513 struct CheckAvailable { 5514 bool TraversalDone = false; 5515 bool Available = true; 5516 5517 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5518 BasicBlock *BB = nullptr; 5519 DominatorTree &DT; 5520 5521 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5522 : L(L), BB(BB), DT(DT) {} 5523 5524 bool setUnavailable() { 5525 TraversalDone = true; 5526 Available = false; 5527 return false; 5528 } 5529 5530 bool follow(const SCEV *S) { 5531 switch (S->getSCEVType()) { 5532 case scConstant: 5533 case scPtrToInt: 5534 case scTruncate: 5535 case scZeroExtend: 5536 case scSignExtend: 5537 case scAddExpr: 5538 case scMulExpr: 5539 case scUMaxExpr: 5540 case scSMaxExpr: 5541 case scUMinExpr: 5542 case scSMinExpr: 5543 // These expressions are available if their operand(s) is/are. 5544 return true; 5545 5546 case scAddRecExpr: { 5547 // We allow add recurrences that are on the loop BB is in, or some 5548 // outer loop. This guarantees availability because the value of the 5549 // add recurrence at BB is simply the "current" value of the induction 5550 // variable. We can relax this in the future; for instance an add 5551 // recurrence on a sibling dominating loop is also available at BB. 5552 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5553 if (L && (ARLoop == L || ARLoop->contains(L))) 5554 return true; 5555 5556 return setUnavailable(); 5557 } 5558 5559 case scUnknown: { 5560 // For SCEVUnknown, we check for simple dominance. 5561 const auto *SU = cast<SCEVUnknown>(S); 5562 Value *V = SU->getValue(); 5563 5564 if (isa<Argument>(V)) 5565 return false; 5566 5567 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5568 return false; 5569 5570 return setUnavailable(); 5571 } 5572 5573 case scUDivExpr: 5574 case scCouldNotCompute: 5575 // We do not try to smart about these at all. 5576 return setUnavailable(); 5577 } 5578 llvm_unreachable("Unknown SCEV kind!"); 5579 } 5580 5581 bool isDone() { return TraversalDone; } 5582 }; 5583 5584 CheckAvailable CA(L, BB, DT); 5585 SCEVTraversal<CheckAvailable> ST(CA); 5586 5587 ST.visitAll(S); 5588 return CA.Available; 5589 } 5590 5591 // Try to match a control flow sequence that branches out at BI and merges back 5592 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5593 // match. 5594 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5595 Value *&C, Value *&LHS, Value *&RHS) { 5596 C = BI->getCondition(); 5597 5598 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5599 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5600 5601 if (!LeftEdge.isSingleEdge()) 5602 return false; 5603 5604 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5605 5606 Use &LeftUse = Merge->getOperandUse(0); 5607 Use &RightUse = Merge->getOperandUse(1); 5608 5609 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5610 LHS = LeftUse; 5611 RHS = RightUse; 5612 return true; 5613 } 5614 5615 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5616 LHS = RightUse; 5617 RHS = LeftUse; 5618 return true; 5619 } 5620 5621 return false; 5622 } 5623 5624 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5625 auto IsReachable = 5626 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5627 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5628 const Loop *L = LI.getLoopFor(PN->getParent()); 5629 5630 // We don't want to break LCSSA, even in a SCEV expression tree. 5631 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5632 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5633 return nullptr; 5634 5635 // Try to match 5636 // 5637 // br %cond, label %left, label %right 5638 // left: 5639 // br label %merge 5640 // right: 5641 // br label %merge 5642 // merge: 5643 // V = phi [ %x, %left ], [ %y, %right ] 5644 // 5645 // as "select %cond, %x, %y" 5646 5647 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5648 assert(IDom && "At least the entry block should dominate PN"); 5649 5650 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5651 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5652 5653 if (BI && BI->isConditional() && 5654 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5655 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5656 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5657 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5658 } 5659 5660 return nullptr; 5661 } 5662 5663 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5664 if (const SCEV *S = createAddRecFromPHI(PN)) 5665 return S; 5666 5667 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5668 return S; 5669 5670 // If the PHI has a single incoming value, follow that value, unless the 5671 // PHI's incoming blocks are in a different loop, in which case doing so 5672 // risks breaking LCSSA form. Instcombine would normally zap these, but 5673 // it doesn't have DominatorTree information, so it may miss cases. 5674 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5675 if (LI.replacementPreservesLCSSAForm(PN, V)) 5676 return getSCEV(V); 5677 5678 // If it's not a loop phi, we can't handle it yet. 5679 return getUnknown(PN); 5680 } 5681 5682 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5683 Value *Cond, 5684 Value *TrueVal, 5685 Value *FalseVal) { 5686 // Handle "constant" branch or select. This can occur for instance when a 5687 // loop pass transforms an inner loop and moves on to process the outer loop. 5688 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5689 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5690 5691 // Try to match some simple smax or umax patterns. 5692 auto *ICI = dyn_cast<ICmpInst>(Cond); 5693 if (!ICI) 5694 return getUnknown(I); 5695 5696 Value *LHS = ICI->getOperand(0); 5697 Value *RHS = ICI->getOperand(1); 5698 5699 switch (ICI->getPredicate()) { 5700 case ICmpInst::ICMP_SLT: 5701 case ICmpInst::ICMP_SLE: 5702 case ICmpInst::ICMP_ULT: 5703 case ICmpInst::ICMP_ULE: 5704 std::swap(LHS, RHS); 5705 LLVM_FALLTHROUGH; 5706 case ICmpInst::ICMP_SGT: 5707 case ICmpInst::ICMP_SGE: 5708 case ICmpInst::ICMP_UGT: 5709 case ICmpInst::ICMP_UGE: 5710 // a > b ? a+x : b+x -> max(a, b)+x 5711 // a > b ? b+x : a+x -> min(a, b)+x 5712 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5713 bool Signed = ICI->isSigned(); 5714 const SCEV *LA = getSCEV(TrueVal); 5715 const SCEV *RA = getSCEV(FalseVal); 5716 const SCEV *LS = getSCEV(LHS); 5717 const SCEV *RS = getSCEV(RHS); 5718 if (LA->getType()->isPointerTy()) { 5719 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5720 // Need to make sure we can't produce weird expressions involving 5721 // negated pointers. 5722 if (LA == LS && RA == RS) 5723 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5724 if (LA == RS && RA == LS) 5725 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5726 } 5727 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5728 if (Op->getType()->isPointerTy()) { 5729 Op = getLosslessPtrToIntExpr(Op); 5730 if (isa<SCEVCouldNotCompute>(Op)) 5731 return Op; 5732 } 5733 if (Signed) 5734 Op = getNoopOrSignExtend(Op, I->getType()); 5735 else 5736 Op = getNoopOrZeroExtend(Op, I->getType()); 5737 return Op; 5738 }; 5739 LS = CoerceOperand(LS); 5740 RS = CoerceOperand(RS); 5741 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5742 break; 5743 const SCEV *LDiff = getMinusSCEV(LA, LS); 5744 const SCEV *RDiff = getMinusSCEV(RA, RS); 5745 if (LDiff == RDiff) 5746 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5747 LDiff); 5748 LDiff = getMinusSCEV(LA, RS); 5749 RDiff = getMinusSCEV(RA, LS); 5750 if (LDiff == RDiff) 5751 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5752 LDiff); 5753 } 5754 break; 5755 case ICmpInst::ICMP_NE: 5756 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5757 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5758 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5759 const SCEV *One = getOne(I->getType()); 5760 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5761 const SCEV *LA = getSCEV(TrueVal); 5762 const SCEV *RA = getSCEV(FalseVal); 5763 const SCEV *LDiff = getMinusSCEV(LA, LS); 5764 const SCEV *RDiff = getMinusSCEV(RA, One); 5765 if (LDiff == RDiff) 5766 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5767 } 5768 break; 5769 case ICmpInst::ICMP_EQ: 5770 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5771 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5772 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5773 const SCEV *One = getOne(I->getType()); 5774 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5775 const SCEV *LA = getSCEV(TrueVal); 5776 const SCEV *RA = getSCEV(FalseVal); 5777 const SCEV *LDiff = getMinusSCEV(LA, One); 5778 const SCEV *RDiff = getMinusSCEV(RA, LS); 5779 if (LDiff == RDiff) 5780 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5781 } 5782 break; 5783 default: 5784 break; 5785 } 5786 5787 return getUnknown(I); 5788 } 5789 5790 /// Expand GEP instructions into add and multiply operations. This allows them 5791 /// to be analyzed by regular SCEV code. 5792 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5793 // Don't attempt to analyze GEPs over unsized objects. 5794 if (!GEP->getSourceElementType()->isSized()) 5795 return getUnknown(GEP); 5796 5797 SmallVector<const SCEV *, 4> IndexExprs; 5798 for (Value *Index : GEP->indices()) 5799 IndexExprs.push_back(getSCEV(Index)); 5800 return getGEPExpr(GEP, IndexExprs); 5801 } 5802 5803 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5804 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5805 return C->getAPInt().countTrailingZeros(); 5806 5807 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5808 return GetMinTrailingZeros(I->getOperand()); 5809 5810 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5811 return std::min(GetMinTrailingZeros(T->getOperand()), 5812 (uint32_t)getTypeSizeInBits(T->getType())); 5813 5814 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5815 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5816 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5817 ? getTypeSizeInBits(E->getType()) 5818 : OpRes; 5819 } 5820 5821 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5822 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5823 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5824 ? getTypeSizeInBits(E->getType()) 5825 : OpRes; 5826 } 5827 5828 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5829 // The result is the min of all operands results. 5830 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5831 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5832 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5833 return MinOpRes; 5834 } 5835 5836 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5837 // The result is the sum of all operands results. 5838 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5839 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5840 for (unsigned i = 1, e = M->getNumOperands(); 5841 SumOpRes != BitWidth && i != e; ++i) 5842 SumOpRes = 5843 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5844 return SumOpRes; 5845 } 5846 5847 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5848 // The result is the min of all operands results. 5849 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5850 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5851 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5852 return MinOpRes; 5853 } 5854 5855 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5856 // The result is the min of all operands results. 5857 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5858 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5859 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5860 return MinOpRes; 5861 } 5862 5863 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5864 // The result is the min of all operands results. 5865 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5866 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5867 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5868 return MinOpRes; 5869 } 5870 5871 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5872 // For a SCEVUnknown, ask ValueTracking. 5873 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5874 return Known.countMinTrailingZeros(); 5875 } 5876 5877 // SCEVUDivExpr 5878 return 0; 5879 } 5880 5881 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5882 auto I = MinTrailingZerosCache.find(S); 5883 if (I != MinTrailingZerosCache.end()) 5884 return I->second; 5885 5886 uint32_t Result = GetMinTrailingZerosImpl(S); 5887 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5888 assert(InsertPair.second && "Should insert a new key"); 5889 return InsertPair.first->second; 5890 } 5891 5892 /// Helper method to assign a range to V from metadata present in the IR. 5893 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5894 if (Instruction *I = dyn_cast<Instruction>(V)) 5895 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5896 return getConstantRangeFromMetadata(*MD); 5897 5898 return None; 5899 } 5900 5901 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5902 SCEV::NoWrapFlags Flags) { 5903 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5904 AddRec->setNoWrapFlags(Flags); 5905 UnsignedRanges.erase(AddRec); 5906 SignedRanges.erase(AddRec); 5907 } 5908 } 5909 5910 ConstantRange ScalarEvolution:: 5911 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5912 const DataLayout &DL = getDataLayout(); 5913 5914 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5915 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5916 5917 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5918 // use information about the trip count to improve our available range. Note 5919 // that the trip count independent cases are already handled by known bits. 5920 // WARNING: The definition of recurrence used here is subtly different than 5921 // the one used by AddRec (and thus most of this file). Step is allowed to 5922 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5923 // and other addrecs in the same loop (for non-affine addrecs). The code 5924 // below intentionally handles the case where step is not loop invariant. 5925 auto *P = dyn_cast<PHINode>(U->getValue()); 5926 if (!P) 5927 return FullSet; 5928 5929 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5930 // even the values that are not available in these blocks may come from them, 5931 // and this leads to false-positive recurrence test. 5932 for (auto *Pred : predecessors(P->getParent())) 5933 if (!DT.isReachableFromEntry(Pred)) 5934 return FullSet; 5935 5936 BinaryOperator *BO; 5937 Value *Start, *Step; 5938 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5939 return FullSet; 5940 5941 // If we found a recurrence in reachable code, we must be in a loop. Note 5942 // that BO might be in some subloop of L, and that's completely okay. 5943 auto *L = LI.getLoopFor(P->getParent()); 5944 assert(L && L->getHeader() == P->getParent()); 5945 if (!L->contains(BO->getParent())) 5946 // NOTE: This bailout should be an assert instead. However, asserting 5947 // the condition here exposes a case where LoopFusion is querying SCEV 5948 // with malformed loop information during the midst of the transform. 5949 // There doesn't appear to be an obvious fix, so for the moment bailout 5950 // until the caller issue can be fixed. PR49566 tracks the bug. 5951 return FullSet; 5952 5953 // TODO: Extend to other opcodes such as mul, and div 5954 switch (BO->getOpcode()) { 5955 default: 5956 return FullSet; 5957 case Instruction::AShr: 5958 case Instruction::LShr: 5959 case Instruction::Shl: 5960 break; 5961 }; 5962 5963 if (BO->getOperand(0) != P) 5964 // TODO: Handle the power function forms some day. 5965 return FullSet; 5966 5967 unsigned TC = getSmallConstantMaxTripCount(L); 5968 if (!TC || TC >= BitWidth) 5969 return FullSet; 5970 5971 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5972 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5973 assert(KnownStart.getBitWidth() == BitWidth && 5974 KnownStep.getBitWidth() == BitWidth); 5975 5976 // Compute total shift amount, being careful of overflow and bitwidths. 5977 auto MaxShiftAmt = KnownStep.getMaxValue(); 5978 APInt TCAP(BitWidth, TC-1); 5979 bool Overflow = false; 5980 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5981 if (Overflow) 5982 return FullSet; 5983 5984 switch (BO->getOpcode()) { 5985 default: 5986 llvm_unreachable("filtered out above"); 5987 case Instruction::AShr: { 5988 // For each ashr, three cases: 5989 // shift = 0 => unchanged value 5990 // saturation => 0 or -1 5991 // other => a value closer to zero (of the same sign) 5992 // Thus, the end value is closer to zero than the start. 5993 auto KnownEnd = KnownBits::ashr(KnownStart, 5994 KnownBits::makeConstant(TotalShift)); 5995 if (KnownStart.isNonNegative()) 5996 // Analogous to lshr (simply not yet canonicalized) 5997 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5998 KnownStart.getMaxValue() + 1); 5999 if (KnownStart.isNegative()) 6000 // End >=u Start && End <=s Start 6001 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 6002 KnownEnd.getMaxValue() + 1); 6003 break; 6004 } 6005 case Instruction::LShr: { 6006 // For each lshr, three cases: 6007 // shift = 0 => unchanged value 6008 // saturation => 0 6009 // other => a smaller positive number 6010 // Thus, the low end of the unsigned range is the last value produced. 6011 auto KnownEnd = KnownBits::lshr(KnownStart, 6012 KnownBits::makeConstant(TotalShift)); 6013 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6014 KnownStart.getMaxValue() + 1); 6015 } 6016 case Instruction::Shl: { 6017 // Iff no bits are shifted out, value increases on every shift. 6018 auto KnownEnd = KnownBits::shl(KnownStart, 6019 KnownBits::makeConstant(TotalShift)); 6020 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6021 return ConstantRange(KnownStart.getMinValue(), 6022 KnownEnd.getMaxValue() + 1); 6023 break; 6024 } 6025 }; 6026 return FullSet; 6027 } 6028 6029 /// Determine the range for a particular SCEV. If SignHint is 6030 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6031 /// with a "cleaner" unsigned (resp. signed) representation. 6032 const ConstantRange & 6033 ScalarEvolution::getRangeRef(const SCEV *S, 6034 ScalarEvolution::RangeSignHint SignHint) { 6035 DenseMap<const SCEV *, ConstantRange> &Cache = 6036 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6037 : SignedRanges; 6038 ConstantRange::PreferredRangeType RangeType = 6039 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6040 ? ConstantRange::Unsigned : ConstantRange::Signed; 6041 6042 // See if we've computed this range already. 6043 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6044 if (I != Cache.end()) 6045 return I->second; 6046 6047 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6048 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6049 6050 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6051 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6052 using OBO = OverflowingBinaryOperator; 6053 6054 // If the value has known zeros, the maximum value will have those known zeros 6055 // as well. 6056 uint32_t TZ = GetMinTrailingZeros(S); 6057 if (TZ != 0) { 6058 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6059 ConservativeResult = 6060 ConstantRange(APInt::getMinValue(BitWidth), 6061 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6062 else 6063 ConservativeResult = ConstantRange( 6064 APInt::getSignedMinValue(BitWidth), 6065 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6066 } 6067 6068 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6069 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6070 unsigned WrapType = OBO::AnyWrap; 6071 if (Add->hasNoSignedWrap()) 6072 WrapType |= OBO::NoSignedWrap; 6073 if (Add->hasNoUnsignedWrap()) 6074 WrapType |= OBO::NoUnsignedWrap; 6075 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6076 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6077 WrapType, RangeType); 6078 return setRange(Add, SignHint, 6079 ConservativeResult.intersectWith(X, RangeType)); 6080 } 6081 6082 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6083 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6084 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6085 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6086 return setRange(Mul, SignHint, 6087 ConservativeResult.intersectWith(X, RangeType)); 6088 } 6089 6090 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6091 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6092 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6093 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6094 return setRange(SMax, SignHint, 6095 ConservativeResult.intersectWith(X, RangeType)); 6096 } 6097 6098 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6099 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6100 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6101 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6102 return setRange(UMax, SignHint, 6103 ConservativeResult.intersectWith(X, RangeType)); 6104 } 6105 6106 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6107 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6108 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6109 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6110 return setRange(SMin, SignHint, 6111 ConservativeResult.intersectWith(X, RangeType)); 6112 } 6113 6114 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6115 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6116 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6117 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6118 return setRange(UMin, SignHint, 6119 ConservativeResult.intersectWith(X, RangeType)); 6120 } 6121 6122 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6123 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6124 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6125 return setRange(UDiv, SignHint, 6126 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6127 } 6128 6129 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6130 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6131 return setRange(ZExt, SignHint, 6132 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6133 RangeType)); 6134 } 6135 6136 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6137 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6138 return setRange(SExt, SignHint, 6139 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6140 RangeType)); 6141 } 6142 6143 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6144 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6145 return setRange(PtrToInt, SignHint, X); 6146 } 6147 6148 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6149 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6150 return setRange(Trunc, SignHint, 6151 ConservativeResult.intersectWith(X.truncate(BitWidth), 6152 RangeType)); 6153 } 6154 6155 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6156 // If there's no unsigned wrap, the value will never be less than its 6157 // initial value. 6158 if (AddRec->hasNoUnsignedWrap()) { 6159 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6160 if (!UnsignedMinValue.isZero()) 6161 ConservativeResult = ConservativeResult.intersectWith( 6162 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6163 } 6164 6165 // If there's no signed wrap, and all the operands except initial value have 6166 // the same sign or zero, the value won't ever be: 6167 // 1: smaller than initial value if operands are non negative, 6168 // 2: bigger than initial value if operands are non positive. 6169 // For both cases, value can not cross signed min/max boundary. 6170 if (AddRec->hasNoSignedWrap()) { 6171 bool AllNonNeg = true; 6172 bool AllNonPos = true; 6173 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6174 if (!isKnownNonNegative(AddRec->getOperand(i))) 6175 AllNonNeg = false; 6176 if (!isKnownNonPositive(AddRec->getOperand(i))) 6177 AllNonPos = false; 6178 } 6179 if (AllNonNeg) 6180 ConservativeResult = ConservativeResult.intersectWith( 6181 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6182 APInt::getSignedMinValue(BitWidth)), 6183 RangeType); 6184 else if (AllNonPos) 6185 ConservativeResult = ConservativeResult.intersectWith( 6186 ConstantRange::getNonEmpty( 6187 APInt::getSignedMinValue(BitWidth), 6188 getSignedRangeMax(AddRec->getStart()) + 1), 6189 RangeType); 6190 } 6191 6192 // TODO: non-affine addrec 6193 if (AddRec->isAffine()) { 6194 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6195 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6196 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6197 auto RangeFromAffine = getRangeForAffineAR( 6198 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6199 BitWidth); 6200 ConservativeResult = 6201 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6202 6203 auto RangeFromFactoring = getRangeViaFactoring( 6204 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6205 BitWidth); 6206 ConservativeResult = 6207 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6208 } 6209 6210 // Now try symbolic BE count and more powerful methods. 6211 if (UseExpensiveRangeSharpening) { 6212 const SCEV *SymbolicMaxBECount = 6213 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6214 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6215 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6216 AddRec->hasNoSelfWrap()) { 6217 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6218 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6219 ConservativeResult = 6220 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6221 } 6222 } 6223 } 6224 6225 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6226 } 6227 6228 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6229 6230 // Check if the IR explicitly contains !range metadata. 6231 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6232 if (MDRange.hasValue()) 6233 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6234 RangeType); 6235 6236 // Use facts about recurrences in the underlying IR. Note that add 6237 // recurrences are AddRecExprs and thus don't hit this path. This 6238 // primarily handles shift recurrences. 6239 auto CR = getRangeForUnknownRecurrence(U); 6240 ConservativeResult = ConservativeResult.intersectWith(CR); 6241 6242 // See if ValueTracking can give us a useful range. 6243 const DataLayout &DL = getDataLayout(); 6244 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6245 if (Known.getBitWidth() != BitWidth) 6246 Known = Known.zextOrTrunc(BitWidth); 6247 6248 // ValueTracking may be able to compute a tighter result for the number of 6249 // sign bits than for the value of those sign bits. 6250 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6251 if (U->getType()->isPointerTy()) { 6252 // If the pointer size is larger than the index size type, this can cause 6253 // NS to be larger than BitWidth. So compensate for this. 6254 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6255 int ptrIdxDiff = ptrSize - BitWidth; 6256 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6257 NS -= ptrIdxDiff; 6258 } 6259 6260 if (NS > 1) { 6261 // If we know any of the sign bits, we know all of the sign bits. 6262 if (!Known.Zero.getHiBits(NS).isZero()) 6263 Known.Zero.setHighBits(NS); 6264 if (!Known.One.getHiBits(NS).isZero()) 6265 Known.One.setHighBits(NS); 6266 } 6267 6268 if (Known.getMinValue() != Known.getMaxValue() + 1) 6269 ConservativeResult = ConservativeResult.intersectWith( 6270 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6271 RangeType); 6272 if (NS > 1) 6273 ConservativeResult = ConservativeResult.intersectWith( 6274 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6275 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6276 RangeType); 6277 6278 // A range of Phi is a subset of union of all ranges of its input. 6279 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6280 // Make sure that we do not run over cycled Phis. 6281 if (PendingPhiRanges.insert(Phi).second) { 6282 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6283 for (auto &Op : Phi->operands()) { 6284 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6285 RangeFromOps = RangeFromOps.unionWith(OpRange); 6286 // No point to continue if we already have a full set. 6287 if (RangeFromOps.isFullSet()) 6288 break; 6289 } 6290 ConservativeResult = 6291 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6292 bool Erased = PendingPhiRanges.erase(Phi); 6293 assert(Erased && "Failed to erase Phi properly?"); 6294 (void) Erased; 6295 } 6296 } 6297 6298 return setRange(U, SignHint, std::move(ConservativeResult)); 6299 } 6300 6301 return setRange(S, SignHint, std::move(ConservativeResult)); 6302 } 6303 6304 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6305 // values that the expression can take. Initially, the expression has a value 6306 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6307 // argument defines if we treat Step as signed or unsigned. 6308 static ConstantRange getRangeForAffineARHelper(APInt Step, 6309 const ConstantRange &StartRange, 6310 const APInt &MaxBECount, 6311 unsigned BitWidth, bool Signed) { 6312 // If either Step or MaxBECount is 0, then the expression won't change, and we 6313 // just need to return the initial range. 6314 if (Step == 0 || MaxBECount == 0) 6315 return StartRange; 6316 6317 // If we don't know anything about the initial value (i.e. StartRange is 6318 // FullRange), then we don't know anything about the final range either. 6319 // Return FullRange. 6320 if (StartRange.isFullSet()) 6321 return ConstantRange::getFull(BitWidth); 6322 6323 // If Step is signed and negative, then we use its absolute value, but we also 6324 // note that we're moving in the opposite direction. 6325 bool Descending = Signed && Step.isNegative(); 6326 6327 if (Signed) 6328 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6329 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6330 // This equations hold true due to the well-defined wrap-around behavior of 6331 // APInt. 6332 Step = Step.abs(); 6333 6334 // Check if Offset is more than full span of BitWidth. If it is, the 6335 // expression is guaranteed to overflow. 6336 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6337 return ConstantRange::getFull(BitWidth); 6338 6339 // Offset is by how much the expression can change. Checks above guarantee no 6340 // overflow here. 6341 APInt Offset = Step * MaxBECount; 6342 6343 // Minimum value of the final range will match the minimal value of StartRange 6344 // if the expression is increasing and will be decreased by Offset otherwise. 6345 // Maximum value of the final range will match the maximal value of StartRange 6346 // if the expression is decreasing and will be increased by Offset otherwise. 6347 APInt StartLower = StartRange.getLower(); 6348 APInt StartUpper = StartRange.getUpper() - 1; 6349 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6350 : (StartUpper + std::move(Offset)); 6351 6352 // It's possible that the new minimum/maximum value will fall into the initial 6353 // range (due to wrap around). This means that the expression can take any 6354 // value in this bitwidth, and we have to return full range. 6355 if (StartRange.contains(MovedBoundary)) 6356 return ConstantRange::getFull(BitWidth); 6357 6358 APInt NewLower = 6359 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6360 APInt NewUpper = 6361 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6362 NewUpper += 1; 6363 6364 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6365 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6366 } 6367 6368 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6369 const SCEV *Step, 6370 const SCEV *MaxBECount, 6371 unsigned BitWidth) { 6372 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6373 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6374 "Precondition!"); 6375 6376 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6377 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6378 6379 // First, consider step signed. 6380 ConstantRange StartSRange = getSignedRange(Start); 6381 ConstantRange StepSRange = getSignedRange(Step); 6382 6383 // If Step can be both positive and negative, we need to find ranges for the 6384 // maximum absolute step values in both directions and union them. 6385 ConstantRange SR = 6386 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6387 MaxBECountValue, BitWidth, /* Signed = */ true); 6388 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6389 StartSRange, MaxBECountValue, 6390 BitWidth, /* Signed = */ true)); 6391 6392 // Next, consider step unsigned. 6393 ConstantRange UR = getRangeForAffineARHelper( 6394 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6395 MaxBECountValue, BitWidth, /* Signed = */ false); 6396 6397 // Finally, intersect signed and unsigned ranges. 6398 return SR.intersectWith(UR, ConstantRange::Smallest); 6399 } 6400 6401 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6402 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6403 ScalarEvolution::RangeSignHint SignHint) { 6404 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6405 assert(AddRec->hasNoSelfWrap() && 6406 "This only works for non-self-wrapping AddRecs!"); 6407 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6408 const SCEV *Step = AddRec->getStepRecurrence(*this); 6409 // Only deal with constant step to save compile time. 6410 if (!isa<SCEVConstant>(Step)) 6411 return ConstantRange::getFull(BitWidth); 6412 // Let's make sure that we can prove that we do not self-wrap during 6413 // MaxBECount iterations. We need this because MaxBECount is a maximum 6414 // iteration count estimate, and we might infer nw from some exit for which we 6415 // do not know max exit count (or any other side reasoning). 6416 // TODO: Turn into assert at some point. 6417 if (getTypeSizeInBits(MaxBECount->getType()) > 6418 getTypeSizeInBits(AddRec->getType())) 6419 return ConstantRange::getFull(BitWidth); 6420 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6421 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6422 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6423 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6424 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6425 MaxItersWithoutWrap)) 6426 return ConstantRange::getFull(BitWidth); 6427 6428 ICmpInst::Predicate LEPred = 6429 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6430 ICmpInst::Predicate GEPred = 6431 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6432 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6433 6434 // We know that there is no self-wrap. Let's take Start and End values and 6435 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6436 // the iteration. They either lie inside the range [Min(Start, End), 6437 // Max(Start, End)] or outside it: 6438 // 6439 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6440 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6441 // 6442 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6443 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6444 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6445 // Start <= End and step is positive, or Start >= End and step is negative. 6446 const SCEV *Start = AddRec->getStart(); 6447 ConstantRange StartRange = getRangeRef(Start, SignHint); 6448 ConstantRange EndRange = getRangeRef(End, SignHint); 6449 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6450 // If they already cover full iteration space, we will know nothing useful 6451 // even if we prove what we want to prove. 6452 if (RangeBetween.isFullSet()) 6453 return RangeBetween; 6454 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6455 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6456 : RangeBetween.isWrappedSet(); 6457 if (IsWrappedSet) 6458 return ConstantRange::getFull(BitWidth); 6459 6460 if (isKnownPositive(Step) && 6461 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6462 return RangeBetween; 6463 else if (isKnownNegative(Step) && 6464 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6465 return RangeBetween; 6466 return ConstantRange::getFull(BitWidth); 6467 } 6468 6469 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6470 const SCEV *Step, 6471 const SCEV *MaxBECount, 6472 unsigned BitWidth) { 6473 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6474 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6475 6476 struct SelectPattern { 6477 Value *Condition = nullptr; 6478 APInt TrueValue; 6479 APInt FalseValue; 6480 6481 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6482 const SCEV *S) { 6483 Optional<unsigned> CastOp; 6484 APInt Offset(BitWidth, 0); 6485 6486 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6487 "Should be!"); 6488 6489 // Peel off a constant offset: 6490 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6491 // In the future we could consider being smarter here and handle 6492 // {Start+Step,+,Step} too. 6493 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6494 return; 6495 6496 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6497 S = SA->getOperand(1); 6498 } 6499 6500 // Peel off a cast operation 6501 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6502 CastOp = SCast->getSCEVType(); 6503 S = SCast->getOperand(); 6504 } 6505 6506 using namespace llvm::PatternMatch; 6507 6508 auto *SU = dyn_cast<SCEVUnknown>(S); 6509 const APInt *TrueVal, *FalseVal; 6510 if (!SU || 6511 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6512 m_APInt(FalseVal)))) { 6513 Condition = nullptr; 6514 return; 6515 } 6516 6517 TrueValue = *TrueVal; 6518 FalseValue = *FalseVal; 6519 6520 // Re-apply the cast we peeled off earlier 6521 if (CastOp.hasValue()) 6522 switch (*CastOp) { 6523 default: 6524 llvm_unreachable("Unknown SCEV cast type!"); 6525 6526 case scTruncate: 6527 TrueValue = TrueValue.trunc(BitWidth); 6528 FalseValue = FalseValue.trunc(BitWidth); 6529 break; 6530 case scZeroExtend: 6531 TrueValue = TrueValue.zext(BitWidth); 6532 FalseValue = FalseValue.zext(BitWidth); 6533 break; 6534 case scSignExtend: 6535 TrueValue = TrueValue.sext(BitWidth); 6536 FalseValue = FalseValue.sext(BitWidth); 6537 break; 6538 } 6539 6540 // Re-apply the constant offset we peeled off earlier 6541 TrueValue += Offset; 6542 FalseValue += Offset; 6543 } 6544 6545 bool isRecognized() { return Condition != nullptr; } 6546 }; 6547 6548 SelectPattern StartPattern(*this, BitWidth, Start); 6549 if (!StartPattern.isRecognized()) 6550 return ConstantRange::getFull(BitWidth); 6551 6552 SelectPattern StepPattern(*this, BitWidth, Step); 6553 if (!StepPattern.isRecognized()) 6554 return ConstantRange::getFull(BitWidth); 6555 6556 if (StartPattern.Condition != StepPattern.Condition) { 6557 // We don't handle this case today; but we could, by considering four 6558 // possibilities below instead of two. I'm not sure if there are cases where 6559 // that will help over what getRange already does, though. 6560 return ConstantRange::getFull(BitWidth); 6561 } 6562 6563 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6564 // construct arbitrary general SCEV expressions here. This function is called 6565 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6566 // say) can end up caching a suboptimal value. 6567 6568 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6569 // C2352 and C2512 (otherwise it isn't needed). 6570 6571 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6572 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6573 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6574 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6575 6576 ConstantRange TrueRange = 6577 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6578 ConstantRange FalseRange = 6579 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6580 6581 return TrueRange.unionWith(FalseRange); 6582 } 6583 6584 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6585 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6586 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6587 6588 // Return early if there are no flags to propagate to the SCEV. 6589 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6590 if (BinOp->hasNoUnsignedWrap()) 6591 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6592 if (BinOp->hasNoSignedWrap()) 6593 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6594 if (Flags == SCEV::FlagAnyWrap) 6595 return SCEV::FlagAnyWrap; 6596 6597 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6598 } 6599 6600 const Instruction * 6601 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6602 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6603 return &*AddRec->getLoop()->getHeader()->begin(); 6604 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6605 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6606 return I; 6607 return nullptr; 6608 } 6609 6610 const Instruction * 6611 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6612 // Do a bounded search of the def relation of the requested SCEVs. 6613 SmallSet<const SCEV *, 16> Visited; 6614 SmallVector<const SCEV *> Worklist; 6615 auto pushOp = [&](const SCEV *S) { 6616 if (!Visited.insert(S).second) 6617 return; 6618 // Threshold of 30 here is arbitrary. 6619 if (Visited.size() > 30) 6620 return; 6621 Worklist.push_back(S); 6622 }; 6623 6624 for (auto *S : Ops) 6625 pushOp(S); 6626 6627 const Instruction *Bound = nullptr; 6628 while (!Worklist.empty()) { 6629 auto *S = Worklist.pop_back_val(); 6630 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6631 if (!Bound || DT.dominates(Bound, DefI)) 6632 Bound = DefI; 6633 } else if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6634 for (auto *Op : S2->operands()) 6635 pushOp(Op); 6636 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6637 for (auto *Op : S2->operands()) 6638 pushOp(Op); 6639 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6640 for (auto *Op : S2->operands()) 6641 pushOp(Op); 6642 } 6643 return Bound ? Bound : &*F.getEntryBlock().begin(); 6644 } 6645 6646 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6647 const Instruction *B) { 6648 if (A->getParent() == B->getParent() && 6649 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6650 B->getIterator())) 6651 return true; 6652 6653 auto *BLoop = LI.getLoopFor(B->getParent()); 6654 if (BLoop && BLoop->getHeader() == B->getParent() && 6655 BLoop->getLoopPreheader() == A->getParent() && 6656 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6657 A->getParent()->end()) && 6658 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6659 B->getIterator())) 6660 return true; 6661 return false; 6662 } 6663 6664 6665 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6666 // Only proceed if we can prove that I does not yield poison. 6667 if (!programUndefinedIfPoison(I)) 6668 return false; 6669 6670 // At this point we know that if I is executed, then it does not wrap 6671 // according to at least one of NSW or NUW. If I is not executed, then we do 6672 // not know if the calculation that I represents would wrap. Multiple 6673 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6674 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6675 // derived from other instructions that map to the same SCEV. We cannot make 6676 // that guarantee for cases where I is not executed. So we need to find a 6677 // upper bound on the defining scope for the SCEV, and prove that I is 6678 // executed every time we enter that scope. When the bounding scope is a 6679 // loop (the common case), this is equivalent to proving I executes on every 6680 // iteration of that loop. 6681 SmallVector<const SCEV *> SCEVOps; 6682 for (const Use &Op : I->operands()) { 6683 // I could be an extractvalue from a call to an overflow intrinsic. 6684 // TODO: We can do better here in some cases. 6685 if (isSCEVable(Op->getType())) 6686 SCEVOps.push_back(getSCEV(Op)); 6687 } 6688 auto *DefI = getDefiningScopeBound(SCEVOps); 6689 return isGuaranteedToTransferExecutionTo(DefI, I); 6690 } 6691 6692 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6693 // If we know that \c I can never be poison period, then that's enough. 6694 if (isSCEVExprNeverPoison(I)) 6695 return true; 6696 6697 // For an add recurrence specifically, we assume that infinite loops without 6698 // side effects are undefined behavior, and then reason as follows: 6699 // 6700 // If the add recurrence is poison in any iteration, it is poison on all 6701 // future iterations (since incrementing poison yields poison). If the result 6702 // of the add recurrence is fed into the loop latch condition and the loop 6703 // does not contain any throws or exiting blocks other than the latch, we now 6704 // have the ability to "choose" whether the backedge is taken or not (by 6705 // choosing a sufficiently evil value for the poison feeding into the branch) 6706 // for every iteration including and after the one in which \p I first became 6707 // poison. There are two possibilities (let's call the iteration in which \p 6708 // I first became poison as K): 6709 // 6710 // 1. In the set of iterations including and after K, the loop body executes 6711 // no side effects. In this case executing the backege an infinte number 6712 // of times will yield undefined behavior. 6713 // 6714 // 2. In the set of iterations including and after K, the loop body executes 6715 // at least one side effect. In this case, that specific instance of side 6716 // effect is control dependent on poison, which also yields undefined 6717 // behavior. 6718 6719 auto *ExitingBB = L->getExitingBlock(); 6720 auto *LatchBB = L->getLoopLatch(); 6721 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6722 return false; 6723 6724 SmallPtrSet<const Instruction *, 16> Pushed; 6725 SmallVector<const Instruction *, 8> PoisonStack; 6726 6727 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6728 // things that are known to be poison under that assumption go on the 6729 // PoisonStack. 6730 Pushed.insert(I); 6731 PoisonStack.push_back(I); 6732 6733 bool LatchControlDependentOnPoison = false; 6734 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6735 const Instruction *Poison = PoisonStack.pop_back_val(); 6736 6737 for (auto *PoisonUser : Poison->users()) { 6738 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6739 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6740 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6741 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6742 assert(BI->isConditional() && "Only possibility!"); 6743 if (BI->getParent() == LatchBB) { 6744 LatchControlDependentOnPoison = true; 6745 break; 6746 } 6747 } 6748 } 6749 } 6750 6751 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6752 } 6753 6754 ScalarEvolution::LoopProperties 6755 ScalarEvolution::getLoopProperties(const Loop *L) { 6756 using LoopProperties = ScalarEvolution::LoopProperties; 6757 6758 auto Itr = LoopPropertiesCache.find(L); 6759 if (Itr == LoopPropertiesCache.end()) { 6760 auto HasSideEffects = [](Instruction *I) { 6761 if (auto *SI = dyn_cast<StoreInst>(I)) 6762 return !SI->isSimple(); 6763 6764 return I->mayThrow() || I->mayWriteToMemory(); 6765 }; 6766 6767 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6768 /*HasNoSideEffects*/ true}; 6769 6770 for (auto *BB : L->getBlocks()) 6771 for (auto &I : *BB) { 6772 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6773 LP.HasNoAbnormalExits = false; 6774 if (HasSideEffects(&I)) 6775 LP.HasNoSideEffects = false; 6776 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6777 break; // We're already as pessimistic as we can get. 6778 } 6779 6780 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6781 assert(InsertPair.second && "We just checked!"); 6782 Itr = InsertPair.first; 6783 } 6784 6785 return Itr->second; 6786 } 6787 6788 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6789 // A mustprogress loop without side effects must be finite. 6790 // TODO: The check used here is very conservative. It's only *specific* 6791 // side effects which are well defined in infinite loops. 6792 return isMustProgress(L) && loopHasNoSideEffects(L); 6793 } 6794 6795 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6796 if (!isSCEVable(V->getType())) 6797 return getUnknown(V); 6798 6799 if (Instruction *I = dyn_cast<Instruction>(V)) { 6800 // Don't attempt to analyze instructions in blocks that aren't 6801 // reachable. Such instructions don't matter, and they aren't required 6802 // to obey basic rules for definitions dominating uses which this 6803 // analysis depends on. 6804 if (!DT.isReachableFromEntry(I->getParent())) 6805 return getUnknown(UndefValue::get(V->getType())); 6806 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6807 return getConstant(CI); 6808 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6809 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6810 else if (!isa<ConstantExpr>(V)) 6811 return getUnknown(V); 6812 6813 Operator *U = cast<Operator>(V); 6814 if (auto BO = MatchBinaryOp(U, DT)) { 6815 switch (BO->Opcode) { 6816 case Instruction::Add: { 6817 // The simple thing to do would be to just call getSCEV on both operands 6818 // and call getAddExpr with the result. However if we're looking at a 6819 // bunch of things all added together, this can be quite inefficient, 6820 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6821 // Instead, gather up all the operands and make a single getAddExpr call. 6822 // LLVM IR canonical form means we need only traverse the left operands. 6823 SmallVector<const SCEV *, 4> AddOps; 6824 do { 6825 if (BO->Op) { 6826 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6827 AddOps.push_back(OpSCEV); 6828 break; 6829 } 6830 6831 // If a NUW or NSW flag can be applied to the SCEV for this 6832 // addition, then compute the SCEV for this addition by itself 6833 // with a separate call to getAddExpr. We need to do that 6834 // instead of pushing the operands of the addition onto AddOps, 6835 // since the flags are only known to apply to this particular 6836 // addition - they may not apply to other additions that can be 6837 // formed with operands from AddOps. 6838 const SCEV *RHS = getSCEV(BO->RHS); 6839 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6840 if (Flags != SCEV::FlagAnyWrap) { 6841 const SCEV *LHS = getSCEV(BO->LHS); 6842 if (BO->Opcode == Instruction::Sub) 6843 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6844 else 6845 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6846 break; 6847 } 6848 } 6849 6850 if (BO->Opcode == Instruction::Sub) 6851 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6852 else 6853 AddOps.push_back(getSCEV(BO->RHS)); 6854 6855 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6856 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6857 NewBO->Opcode != Instruction::Sub)) { 6858 AddOps.push_back(getSCEV(BO->LHS)); 6859 break; 6860 } 6861 BO = NewBO; 6862 } while (true); 6863 6864 return getAddExpr(AddOps); 6865 } 6866 6867 case Instruction::Mul: { 6868 SmallVector<const SCEV *, 4> MulOps; 6869 do { 6870 if (BO->Op) { 6871 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6872 MulOps.push_back(OpSCEV); 6873 break; 6874 } 6875 6876 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6877 if (Flags != SCEV::FlagAnyWrap) { 6878 MulOps.push_back( 6879 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6880 break; 6881 } 6882 } 6883 6884 MulOps.push_back(getSCEV(BO->RHS)); 6885 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6886 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6887 MulOps.push_back(getSCEV(BO->LHS)); 6888 break; 6889 } 6890 BO = NewBO; 6891 } while (true); 6892 6893 return getMulExpr(MulOps); 6894 } 6895 case Instruction::UDiv: 6896 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6897 case Instruction::URem: 6898 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6899 case Instruction::Sub: { 6900 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6901 if (BO->Op) 6902 Flags = getNoWrapFlagsFromUB(BO->Op); 6903 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6904 } 6905 case Instruction::And: 6906 // For an expression like x&255 that merely masks off the high bits, 6907 // use zext(trunc(x)) as the SCEV expression. 6908 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6909 if (CI->isZero()) 6910 return getSCEV(BO->RHS); 6911 if (CI->isMinusOne()) 6912 return getSCEV(BO->LHS); 6913 const APInt &A = CI->getValue(); 6914 6915 // Instcombine's ShrinkDemandedConstant may strip bits out of 6916 // constants, obscuring what would otherwise be a low-bits mask. 6917 // Use computeKnownBits to compute what ShrinkDemandedConstant 6918 // knew about to reconstruct a low-bits mask value. 6919 unsigned LZ = A.countLeadingZeros(); 6920 unsigned TZ = A.countTrailingZeros(); 6921 unsigned BitWidth = A.getBitWidth(); 6922 KnownBits Known(BitWidth); 6923 computeKnownBits(BO->LHS, Known, getDataLayout(), 6924 0, &AC, nullptr, &DT); 6925 6926 APInt EffectiveMask = 6927 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6928 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6929 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6930 const SCEV *LHS = getSCEV(BO->LHS); 6931 const SCEV *ShiftedLHS = nullptr; 6932 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6933 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6934 // For an expression like (x * 8) & 8, simplify the multiply. 6935 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6936 unsigned GCD = std::min(MulZeros, TZ); 6937 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6938 SmallVector<const SCEV*, 4> MulOps; 6939 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6940 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6941 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6942 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6943 } 6944 } 6945 if (!ShiftedLHS) 6946 ShiftedLHS = getUDivExpr(LHS, MulCount); 6947 return getMulExpr( 6948 getZeroExtendExpr( 6949 getTruncateExpr(ShiftedLHS, 6950 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6951 BO->LHS->getType()), 6952 MulCount); 6953 } 6954 } 6955 break; 6956 6957 case Instruction::Or: 6958 // If the RHS of the Or is a constant, we may have something like: 6959 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6960 // optimizations will transparently handle this case. 6961 // 6962 // In order for this transformation to be safe, the LHS must be of the 6963 // form X*(2^n) and the Or constant must be less than 2^n. 6964 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6965 const SCEV *LHS = getSCEV(BO->LHS); 6966 const APInt &CIVal = CI->getValue(); 6967 if (GetMinTrailingZeros(LHS) >= 6968 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6969 // Build a plain add SCEV. 6970 return getAddExpr(LHS, getSCEV(CI), 6971 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6972 } 6973 } 6974 break; 6975 6976 case Instruction::Xor: 6977 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6978 // If the RHS of xor is -1, then this is a not operation. 6979 if (CI->isMinusOne()) 6980 return getNotSCEV(getSCEV(BO->LHS)); 6981 6982 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6983 // This is a variant of the check for xor with -1, and it handles 6984 // the case where instcombine has trimmed non-demanded bits out 6985 // of an xor with -1. 6986 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6987 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6988 if (LBO->getOpcode() == Instruction::And && 6989 LCI->getValue() == CI->getValue()) 6990 if (const SCEVZeroExtendExpr *Z = 6991 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6992 Type *UTy = BO->LHS->getType(); 6993 const SCEV *Z0 = Z->getOperand(); 6994 Type *Z0Ty = Z0->getType(); 6995 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6996 6997 // If C is a low-bits mask, the zero extend is serving to 6998 // mask off the high bits. Complement the operand and 6999 // re-apply the zext. 7000 if (CI->getValue().isMask(Z0TySize)) 7001 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 7002 7003 // If C is a single bit, it may be in the sign-bit position 7004 // before the zero-extend. In this case, represent the xor 7005 // using an add, which is equivalent, and re-apply the zext. 7006 APInt Trunc = CI->getValue().trunc(Z0TySize); 7007 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 7008 Trunc.isSignMask()) 7009 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 7010 UTy); 7011 } 7012 } 7013 break; 7014 7015 case Instruction::Shl: 7016 // Turn shift left of a constant amount into a multiply. 7017 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7018 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7019 7020 // If the shift count is not less than the bitwidth, the result of 7021 // the shift is undefined. Don't try to analyze it, because the 7022 // resolution chosen here may differ from the resolution chosen in 7023 // other parts of the compiler. 7024 if (SA->getValue().uge(BitWidth)) 7025 break; 7026 7027 // We can safely preserve the nuw flag in all cases. It's also safe to 7028 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7029 // requires special handling. It can be preserved as long as we're not 7030 // left shifting by bitwidth - 1. 7031 auto Flags = SCEV::FlagAnyWrap; 7032 if (BO->Op) { 7033 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7034 if ((MulFlags & SCEV::FlagNSW) && 7035 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7036 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7037 if (MulFlags & SCEV::FlagNUW) 7038 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7039 } 7040 7041 Constant *X = ConstantInt::get( 7042 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7043 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7044 } 7045 break; 7046 7047 case Instruction::AShr: { 7048 // AShr X, C, where C is a constant. 7049 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7050 if (!CI) 7051 break; 7052 7053 Type *OuterTy = BO->LHS->getType(); 7054 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7055 // If the shift count is not less than the bitwidth, the result of 7056 // the shift is undefined. Don't try to analyze it, because the 7057 // resolution chosen here may differ from the resolution chosen in 7058 // other parts of the compiler. 7059 if (CI->getValue().uge(BitWidth)) 7060 break; 7061 7062 if (CI->isZero()) 7063 return getSCEV(BO->LHS); // shift by zero --> noop 7064 7065 uint64_t AShrAmt = CI->getZExtValue(); 7066 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7067 7068 Operator *L = dyn_cast<Operator>(BO->LHS); 7069 if (L && L->getOpcode() == Instruction::Shl) { 7070 // X = Shl A, n 7071 // Y = AShr X, m 7072 // Both n and m are constant. 7073 7074 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7075 if (L->getOperand(1) == BO->RHS) 7076 // For a two-shift sext-inreg, i.e. n = m, 7077 // use sext(trunc(x)) as the SCEV expression. 7078 return getSignExtendExpr( 7079 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7080 7081 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7082 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7083 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7084 if (ShlAmt > AShrAmt) { 7085 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7086 // expression. We already checked that ShlAmt < BitWidth, so 7087 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7088 // ShlAmt - AShrAmt < Amt. 7089 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7090 ShlAmt - AShrAmt); 7091 return getSignExtendExpr( 7092 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7093 getConstant(Mul)), OuterTy); 7094 } 7095 } 7096 } 7097 break; 7098 } 7099 } 7100 } 7101 7102 switch (U->getOpcode()) { 7103 case Instruction::Trunc: 7104 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7105 7106 case Instruction::ZExt: 7107 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7108 7109 case Instruction::SExt: 7110 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7111 // The NSW flag of a subtract does not always survive the conversion to 7112 // A + (-1)*B. By pushing sign extension onto its operands we are much 7113 // more likely to preserve NSW and allow later AddRec optimisations. 7114 // 7115 // NOTE: This is effectively duplicating this logic from getSignExtend: 7116 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7117 // but by that point the NSW information has potentially been lost. 7118 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7119 Type *Ty = U->getType(); 7120 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7121 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7122 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7123 } 7124 } 7125 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7126 7127 case Instruction::BitCast: 7128 // BitCasts are no-op casts so we just eliminate the cast. 7129 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7130 return getSCEV(U->getOperand(0)); 7131 break; 7132 7133 case Instruction::PtrToInt: { 7134 // Pointer to integer cast is straight-forward, so do model it. 7135 const SCEV *Op = getSCEV(U->getOperand(0)); 7136 Type *DstIntTy = U->getType(); 7137 // But only if effective SCEV (integer) type is wide enough to represent 7138 // all possible pointer values. 7139 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7140 if (isa<SCEVCouldNotCompute>(IntOp)) 7141 return getUnknown(V); 7142 return IntOp; 7143 } 7144 case Instruction::IntToPtr: 7145 // Just don't deal with inttoptr casts. 7146 return getUnknown(V); 7147 7148 case Instruction::SDiv: 7149 // If both operands are non-negative, this is just an udiv. 7150 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7151 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7152 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7153 break; 7154 7155 case Instruction::SRem: 7156 // If both operands are non-negative, this is just an urem. 7157 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7158 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7159 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7160 break; 7161 7162 case Instruction::GetElementPtr: 7163 return createNodeForGEP(cast<GEPOperator>(U)); 7164 7165 case Instruction::PHI: 7166 return createNodeForPHI(cast<PHINode>(U)); 7167 7168 case Instruction::Select: 7169 // U can also be a select constant expr, which let fall through. Since 7170 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7171 // constant expressions cannot have instructions as operands, we'd have 7172 // returned getUnknown for a select constant expressions anyway. 7173 if (isa<Instruction>(U)) 7174 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7175 U->getOperand(1), U->getOperand(2)); 7176 break; 7177 7178 case Instruction::Call: 7179 case Instruction::Invoke: 7180 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7181 return getSCEV(RV); 7182 7183 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7184 switch (II->getIntrinsicID()) { 7185 case Intrinsic::abs: 7186 return getAbsExpr( 7187 getSCEV(II->getArgOperand(0)), 7188 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7189 case Intrinsic::umax: 7190 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7191 getSCEV(II->getArgOperand(1))); 7192 case Intrinsic::umin: 7193 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7194 getSCEV(II->getArgOperand(1))); 7195 case Intrinsic::smax: 7196 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7197 getSCEV(II->getArgOperand(1))); 7198 case Intrinsic::smin: 7199 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7200 getSCEV(II->getArgOperand(1))); 7201 case Intrinsic::usub_sat: { 7202 const SCEV *X = getSCEV(II->getArgOperand(0)); 7203 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7204 const SCEV *ClampedY = getUMinExpr(X, Y); 7205 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7206 } 7207 case Intrinsic::uadd_sat: { 7208 const SCEV *X = getSCEV(II->getArgOperand(0)); 7209 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7210 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7211 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7212 } 7213 case Intrinsic::start_loop_iterations: 7214 // A start_loop_iterations is just equivalent to the first operand for 7215 // SCEV purposes. 7216 return getSCEV(II->getArgOperand(0)); 7217 default: 7218 break; 7219 } 7220 } 7221 break; 7222 } 7223 7224 return getUnknown(V); 7225 } 7226 7227 //===----------------------------------------------------------------------===// 7228 // Iteration Count Computation Code 7229 // 7230 7231 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7232 bool Extend) { 7233 if (isa<SCEVCouldNotCompute>(ExitCount)) 7234 return getCouldNotCompute(); 7235 7236 auto *ExitCountType = ExitCount->getType(); 7237 assert(ExitCountType->isIntegerTy()); 7238 7239 if (!Extend) 7240 return getAddExpr(ExitCount, getOne(ExitCountType)); 7241 7242 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7243 1 + ExitCountType->getScalarSizeInBits()); 7244 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7245 getOne(WiderType)); 7246 } 7247 7248 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7249 if (!ExitCount) 7250 return 0; 7251 7252 ConstantInt *ExitConst = ExitCount->getValue(); 7253 7254 // Guard against huge trip counts. 7255 if (ExitConst->getValue().getActiveBits() > 32) 7256 return 0; 7257 7258 // In case of integer overflow, this returns 0, which is correct. 7259 return ((unsigned)ExitConst->getZExtValue()) + 1; 7260 } 7261 7262 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7263 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7264 return getConstantTripCount(ExitCount); 7265 } 7266 7267 unsigned 7268 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7269 const BasicBlock *ExitingBlock) { 7270 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7271 assert(L->isLoopExiting(ExitingBlock) && 7272 "Exiting block must actually branch out of the loop!"); 7273 const SCEVConstant *ExitCount = 7274 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7275 return getConstantTripCount(ExitCount); 7276 } 7277 7278 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7279 const auto *MaxExitCount = 7280 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7281 return getConstantTripCount(MaxExitCount); 7282 } 7283 7284 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7285 SmallVector<BasicBlock *, 8> ExitingBlocks; 7286 L->getExitingBlocks(ExitingBlocks); 7287 7288 Optional<unsigned> Res = None; 7289 for (auto *ExitingBB : ExitingBlocks) { 7290 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7291 if (!Res) 7292 Res = Multiple; 7293 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7294 } 7295 return Res.getValueOr(1); 7296 } 7297 7298 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7299 const SCEV *ExitCount) { 7300 if (ExitCount == getCouldNotCompute()) 7301 return 1; 7302 7303 // Get the trip count 7304 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7305 7306 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7307 if (!TC) 7308 // Attempt to factor more general cases. Returns the greatest power of 7309 // two divisor. If overflow happens, the trip count expression is still 7310 // divisible by the greatest power of 2 divisor returned. 7311 return 1U << std::min((uint32_t)31, 7312 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7313 7314 ConstantInt *Result = TC->getValue(); 7315 7316 // Guard against huge trip counts (this requires checking 7317 // for zero to handle the case where the trip count == -1 and the 7318 // addition wraps). 7319 if (!Result || Result->getValue().getActiveBits() > 32 || 7320 Result->getValue().getActiveBits() == 0) 7321 return 1; 7322 7323 return (unsigned)Result->getZExtValue(); 7324 } 7325 7326 /// Returns the largest constant divisor of the trip count of this loop as a 7327 /// normal unsigned value, if possible. This means that the actual trip count is 7328 /// always a multiple of the returned value (don't forget the trip count could 7329 /// very well be zero as well!). 7330 /// 7331 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7332 /// multiple of a constant (which is also the case if the trip count is simply 7333 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7334 /// if the trip count is very large (>= 2^32). 7335 /// 7336 /// As explained in the comments for getSmallConstantTripCount, this assumes 7337 /// that control exits the loop via ExitingBlock. 7338 unsigned 7339 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7340 const BasicBlock *ExitingBlock) { 7341 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7342 assert(L->isLoopExiting(ExitingBlock) && 7343 "Exiting block must actually branch out of the loop!"); 7344 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7345 return getSmallConstantTripMultiple(L, ExitCount); 7346 } 7347 7348 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7349 const BasicBlock *ExitingBlock, 7350 ExitCountKind Kind) { 7351 switch (Kind) { 7352 case Exact: 7353 case SymbolicMaximum: 7354 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7355 case ConstantMaximum: 7356 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7357 }; 7358 llvm_unreachable("Invalid ExitCountKind!"); 7359 } 7360 7361 const SCEV * 7362 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7363 SCEVUnionPredicate &Preds) { 7364 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7365 } 7366 7367 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7368 ExitCountKind Kind) { 7369 switch (Kind) { 7370 case Exact: 7371 return getBackedgeTakenInfo(L).getExact(L, this); 7372 case ConstantMaximum: 7373 return getBackedgeTakenInfo(L).getConstantMax(this); 7374 case SymbolicMaximum: 7375 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7376 }; 7377 llvm_unreachable("Invalid ExitCountKind!"); 7378 } 7379 7380 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7381 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7382 } 7383 7384 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7385 static void PushLoopPHIs(const Loop *L, 7386 SmallVectorImpl<Instruction *> &Worklist, 7387 SmallPtrSetImpl<Instruction *> &Visited) { 7388 BasicBlock *Header = L->getHeader(); 7389 7390 // Push all Loop-header PHIs onto the Worklist stack. 7391 for (PHINode &PN : Header->phis()) 7392 if (Visited.insert(&PN).second) 7393 Worklist.push_back(&PN); 7394 } 7395 7396 const ScalarEvolution::BackedgeTakenInfo & 7397 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7398 auto &BTI = getBackedgeTakenInfo(L); 7399 if (BTI.hasFullInfo()) 7400 return BTI; 7401 7402 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7403 7404 if (!Pair.second) 7405 return Pair.first->second; 7406 7407 BackedgeTakenInfo Result = 7408 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7409 7410 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7411 } 7412 7413 ScalarEvolution::BackedgeTakenInfo & 7414 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7415 // Initially insert an invalid entry for this loop. If the insertion 7416 // succeeds, proceed to actually compute a backedge-taken count and 7417 // update the value. The temporary CouldNotCompute value tells SCEV 7418 // code elsewhere that it shouldn't attempt to request a new 7419 // backedge-taken count, which could result in infinite recursion. 7420 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7421 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7422 if (!Pair.second) 7423 return Pair.first->second; 7424 7425 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7426 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7427 // must be cleared in this scope. 7428 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7429 7430 // In product build, there are no usage of statistic. 7431 (void)NumTripCountsComputed; 7432 (void)NumTripCountsNotComputed; 7433 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7434 const SCEV *BEExact = Result.getExact(L, this); 7435 if (BEExact != getCouldNotCompute()) { 7436 assert(isLoopInvariant(BEExact, L) && 7437 isLoopInvariant(Result.getConstantMax(this), L) && 7438 "Computed backedge-taken count isn't loop invariant for loop!"); 7439 ++NumTripCountsComputed; 7440 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7441 isa<PHINode>(L->getHeader()->begin())) { 7442 // Only count loops that have phi nodes as not being computable. 7443 ++NumTripCountsNotComputed; 7444 } 7445 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7446 7447 // Now that we know more about the trip count for this loop, forget any 7448 // existing SCEV values for PHI nodes in this loop since they are only 7449 // conservative estimates made without the benefit of trip count 7450 // information. This is similar to the code in forgetLoop, except that 7451 // it handles SCEVUnknown PHI nodes specially. 7452 if (Result.hasAnyInfo()) { 7453 SmallVector<Instruction *, 16> Worklist; 7454 SmallPtrSet<Instruction *, 8> Discovered; 7455 SmallVector<const SCEV *, 8> ToForget; 7456 PushLoopPHIs(L, Worklist, Discovered); 7457 while (!Worklist.empty()) { 7458 Instruction *I = Worklist.pop_back_val(); 7459 7460 ValueExprMapType::iterator It = 7461 ValueExprMap.find_as(static_cast<Value *>(I)); 7462 if (It != ValueExprMap.end()) { 7463 const SCEV *Old = It->second; 7464 7465 // SCEVUnknown for a PHI either means that it has an unrecognized 7466 // structure, or it's a PHI that's in the progress of being computed 7467 // by createNodeForPHI. In the former case, additional loop trip 7468 // count information isn't going to change anything. In the later 7469 // case, createNodeForPHI will perform the necessary updates on its 7470 // own when it gets to that point. 7471 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7472 eraseValueFromMap(It->first); 7473 ToForget.push_back(Old); 7474 } 7475 if (PHINode *PN = dyn_cast<PHINode>(I)) 7476 ConstantEvolutionLoopExitValue.erase(PN); 7477 } 7478 7479 // Since we don't need to invalidate anything for correctness and we're 7480 // only invalidating to make SCEV's results more precise, we get to stop 7481 // early to avoid invalidating too much. This is especially important in 7482 // cases like: 7483 // 7484 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7485 // loop0: 7486 // %pn0 = phi 7487 // ... 7488 // loop1: 7489 // %pn1 = phi 7490 // ... 7491 // 7492 // where both loop0 and loop1's backedge taken count uses the SCEV 7493 // expression for %v. If we don't have the early stop below then in cases 7494 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7495 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7496 // count for loop1, effectively nullifying SCEV's trip count cache. 7497 for (auto *U : I->users()) 7498 if (auto *I = dyn_cast<Instruction>(U)) { 7499 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7500 if (LoopForUser && L->contains(LoopForUser) && 7501 Discovered.insert(I).second) 7502 Worklist.push_back(I); 7503 } 7504 } 7505 forgetMemoizedResults(ToForget); 7506 } 7507 7508 // Re-lookup the insert position, since the call to 7509 // computeBackedgeTakenCount above could result in a 7510 // recusive call to getBackedgeTakenInfo (on a different 7511 // loop), which would invalidate the iterator computed 7512 // earlier. 7513 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7514 } 7515 7516 void ScalarEvolution::forgetAllLoops() { 7517 // This method is intended to forget all info about loops. It should 7518 // invalidate caches as if the following happened: 7519 // - The trip counts of all loops have changed arbitrarily 7520 // - Every llvm::Value has been updated in place to produce a different 7521 // result. 7522 BackedgeTakenCounts.clear(); 7523 PredicatedBackedgeTakenCounts.clear(); 7524 LoopPropertiesCache.clear(); 7525 ConstantEvolutionLoopExitValue.clear(); 7526 ValueExprMap.clear(); 7527 ValuesAtScopes.clear(); 7528 LoopDispositions.clear(); 7529 BlockDispositions.clear(); 7530 UnsignedRanges.clear(); 7531 SignedRanges.clear(); 7532 ExprValueMap.clear(); 7533 HasRecMap.clear(); 7534 MinTrailingZerosCache.clear(); 7535 PredicatedSCEVRewrites.clear(); 7536 } 7537 7538 void ScalarEvolution::forgetLoop(const Loop *L) { 7539 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7540 SmallVector<Instruction *, 32> Worklist; 7541 SmallPtrSet<Instruction *, 16> Visited; 7542 SmallVector<const SCEV *, 16> ToForget; 7543 7544 // Iterate over all the loops and sub-loops to drop SCEV information. 7545 while (!LoopWorklist.empty()) { 7546 auto *CurrL = LoopWorklist.pop_back_val(); 7547 7548 // Drop any stored trip count value. 7549 BackedgeTakenCounts.erase(CurrL); 7550 PredicatedBackedgeTakenCounts.erase(CurrL); 7551 7552 // Drop information about predicated SCEV rewrites for this loop. 7553 for (auto I = PredicatedSCEVRewrites.begin(); 7554 I != PredicatedSCEVRewrites.end();) { 7555 std::pair<const SCEV *, const Loop *> Entry = I->first; 7556 if (Entry.second == CurrL) 7557 PredicatedSCEVRewrites.erase(I++); 7558 else 7559 ++I; 7560 } 7561 7562 auto LoopUsersItr = LoopUsers.find(CurrL); 7563 if (LoopUsersItr != LoopUsers.end()) { 7564 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 7565 LoopUsersItr->second.end()); 7566 LoopUsers.erase(LoopUsersItr); 7567 } 7568 7569 // Drop information about expressions based on loop-header PHIs. 7570 PushLoopPHIs(CurrL, Worklist, Visited); 7571 7572 while (!Worklist.empty()) { 7573 Instruction *I = Worklist.pop_back_val(); 7574 7575 ValueExprMapType::iterator It = 7576 ValueExprMap.find_as(static_cast<Value *>(I)); 7577 if (It != ValueExprMap.end()) { 7578 eraseValueFromMap(It->first); 7579 ToForget.push_back(It->second); 7580 if (PHINode *PN = dyn_cast<PHINode>(I)) 7581 ConstantEvolutionLoopExitValue.erase(PN); 7582 } 7583 7584 PushDefUseChildren(I, Worklist, Visited); 7585 } 7586 7587 LoopPropertiesCache.erase(CurrL); 7588 // Forget all contained loops too, to avoid dangling entries in the 7589 // ValuesAtScopes map. 7590 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7591 } 7592 forgetMemoizedResults(ToForget); 7593 } 7594 7595 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7596 while (Loop *Parent = L->getParentLoop()) 7597 L = Parent; 7598 forgetLoop(L); 7599 } 7600 7601 void ScalarEvolution::forgetValue(Value *V) { 7602 Instruction *I = dyn_cast<Instruction>(V); 7603 if (!I) return; 7604 7605 // Drop information about expressions based on loop-header PHIs. 7606 SmallVector<Instruction *, 16> Worklist; 7607 SmallPtrSet<Instruction *, 8> Visited; 7608 SmallVector<const SCEV *, 8> ToForget; 7609 Worklist.push_back(I); 7610 Visited.insert(I); 7611 7612 while (!Worklist.empty()) { 7613 I = Worklist.pop_back_val(); 7614 ValueExprMapType::iterator It = 7615 ValueExprMap.find_as(static_cast<Value *>(I)); 7616 if (It != ValueExprMap.end()) { 7617 eraseValueFromMap(It->first); 7618 ToForget.push_back(It->second); 7619 if (PHINode *PN = dyn_cast<PHINode>(I)) 7620 ConstantEvolutionLoopExitValue.erase(PN); 7621 } 7622 7623 PushDefUseChildren(I, Worklist, Visited); 7624 } 7625 forgetMemoizedResults(ToForget); 7626 } 7627 7628 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7629 LoopDispositions.clear(); 7630 } 7631 7632 /// Get the exact loop backedge taken count considering all loop exits. A 7633 /// computable result can only be returned for loops with all exiting blocks 7634 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7635 /// is never skipped. This is a valid assumption as long as the loop exits via 7636 /// that test. For precise results, it is the caller's responsibility to specify 7637 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7638 const SCEV * 7639 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7640 SCEVUnionPredicate *Preds) const { 7641 // If any exits were not computable, the loop is not computable. 7642 if (!isComplete() || ExitNotTaken.empty()) 7643 return SE->getCouldNotCompute(); 7644 7645 const BasicBlock *Latch = L->getLoopLatch(); 7646 // All exiting blocks we have collected must dominate the only backedge. 7647 if (!Latch) 7648 return SE->getCouldNotCompute(); 7649 7650 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7651 // count is simply a minimum out of all these calculated exit counts. 7652 SmallVector<const SCEV *, 2> Ops; 7653 for (auto &ENT : ExitNotTaken) { 7654 const SCEV *BECount = ENT.ExactNotTaken; 7655 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7656 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7657 "We should only have known counts for exiting blocks that dominate " 7658 "latch!"); 7659 7660 Ops.push_back(BECount); 7661 7662 if (Preds && !ENT.hasAlwaysTruePredicate()) 7663 Preds->add(ENT.Predicate.get()); 7664 7665 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7666 "Predicate should be always true!"); 7667 } 7668 7669 return SE->getUMinFromMismatchedTypes(Ops); 7670 } 7671 7672 /// Get the exact not taken count for this loop exit. 7673 const SCEV * 7674 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7675 ScalarEvolution *SE) const { 7676 for (auto &ENT : ExitNotTaken) 7677 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7678 return ENT.ExactNotTaken; 7679 7680 return SE->getCouldNotCompute(); 7681 } 7682 7683 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7684 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7685 for (auto &ENT : ExitNotTaken) 7686 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7687 return ENT.MaxNotTaken; 7688 7689 return SE->getCouldNotCompute(); 7690 } 7691 7692 /// getConstantMax - Get the constant max backedge taken count for the loop. 7693 const SCEV * 7694 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7695 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7696 return !ENT.hasAlwaysTruePredicate(); 7697 }; 7698 7699 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 7700 return SE->getCouldNotCompute(); 7701 7702 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7703 isa<SCEVConstant>(getConstantMax())) && 7704 "No point in having a non-constant max backedge taken count!"); 7705 return getConstantMax(); 7706 } 7707 7708 const SCEV * 7709 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7710 ScalarEvolution *SE) { 7711 if (!SymbolicMax) 7712 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7713 return SymbolicMax; 7714 } 7715 7716 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7717 ScalarEvolution *SE) const { 7718 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7719 return !ENT.hasAlwaysTruePredicate(); 7720 }; 7721 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7722 } 7723 7724 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7725 return Operands.contains(S); 7726 } 7727 7728 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7729 : ExitLimit(E, E, false, None) { 7730 } 7731 7732 ScalarEvolution::ExitLimit::ExitLimit( 7733 const SCEV *E, const SCEV *M, bool MaxOrZero, 7734 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7735 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7736 // If we prove the max count is zero, so is the symbolic bound. This happens 7737 // in practice due to differences in a) how context sensitive we've chosen 7738 // to be and b) how we reason about bounds impied by UB. 7739 if (MaxNotTaken->isZero()) 7740 ExactNotTaken = MaxNotTaken; 7741 7742 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7743 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7744 "Exact is not allowed to be less precise than Max"); 7745 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7746 isa<SCEVConstant>(MaxNotTaken)) && 7747 "No point in having a non-constant max backedge taken count!"); 7748 for (auto *PredSet : PredSetList) 7749 for (auto *P : *PredSet) 7750 addPredicate(P); 7751 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7752 "Backedge count should be int"); 7753 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7754 "Max backedge count should be int"); 7755 } 7756 7757 ScalarEvolution::ExitLimit::ExitLimit( 7758 const SCEV *E, const SCEV *M, bool MaxOrZero, 7759 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7760 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7761 } 7762 7763 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7764 bool MaxOrZero) 7765 : ExitLimit(E, M, MaxOrZero, None) { 7766 } 7767 7768 class SCEVRecordOperands { 7769 SmallPtrSetImpl<const SCEV *> &Operands; 7770 7771 public: 7772 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7773 : Operands(Operands) {} 7774 bool follow(const SCEV *S) { 7775 Operands.insert(S); 7776 return true; 7777 } 7778 bool isDone() { return false; } 7779 }; 7780 7781 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7782 /// computable exit into a persistent ExitNotTakenInfo array. 7783 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7784 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7785 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7786 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7787 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7788 7789 ExitNotTaken.reserve(ExitCounts.size()); 7790 std::transform( 7791 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7792 [&](const EdgeExitInfo &EEI) { 7793 BasicBlock *ExitBB = EEI.first; 7794 const ExitLimit &EL = EEI.second; 7795 if (EL.Predicates.empty()) 7796 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7797 nullptr); 7798 7799 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7800 for (auto *Pred : EL.Predicates) 7801 Predicate->add(Pred); 7802 7803 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7804 std::move(Predicate)); 7805 }); 7806 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7807 isa<SCEVConstant>(ConstantMax)) && 7808 "No point in having a non-constant max backedge taken count!"); 7809 7810 SCEVRecordOperands RecordOperands(Operands); 7811 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7812 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7813 ST.visitAll(ConstantMax); 7814 for (auto &ENT : ExitNotTaken) 7815 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7816 ST.visitAll(ENT.ExactNotTaken); 7817 } 7818 7819 /// Compute the number of times the backedge of the specified loop will execute. 7820 ScalarEvolution::BackedgeTakenInfo 7821 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7822 bool AllowPredicates) { 7823 SmallVector<BasicBlock *, 8> ExitingBlocks; 7824 L->getExitingBlocks(ExitingBlocks); 7825 7826 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7827 7828 SmallVector<EdgeExitInfo, 4> ExitCounts; 7829 bool CouldComputeBECount = true; 7830 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7831 const SCEV *MustExitMaxBECount = nullptr; 7832 const SCEV *MayExitMaxBECount = nullptr; 7833 bool MustExitMaxOrZero = false; 7834 7835 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7836 // and compute maxBECount. 7837 // Do a union of all the predicates here. 7838 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7839 BasicBlock *ExitBB = ExitingBlocks[i]; 7840 7841 // We canonicalize untaken exits to br (constant), ignore them so that 7842 // proving an exit untaken doesn't negatively impact our ability to reason 7843 // about the loop as whole. 7844 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7845 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7846 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7847 if (ExitIfTrue == CI->isZero()) 7848 continue; 7849 } 7850 7851 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7852 7853 assert((AllowPredicates || EL.Predicates.empty()) && 7854 "Predicated exit limit when predicates are not allowed!"); 7855 7856 // 1. For each exit that can be computed, add an entry to ExitCounts. 7857 // CouldComputeBECount is true only if all exits can be computed. 7858 if (EL.ExactNotTaken == getCouldNotCompute()) 7859 // We couldn't compute an exact value for this exit, so 7860 // we won't be able to compute an exact value for the loop. 7861 CouldComputeBECount = false; 7862 else 7863 ExitCounts.emplace_back(ExitBB, EL); 7864 7865 // 2. Derive the loop's MaxBECount from each exit's max number of 7866 // non-exiting iterations. Partition the loop exits into two kinds: 7867 // LoopMustExits and LoopMayExits. 7868 // 7869 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7870 // is a LoopMayExit. If any computable LoopMustExit is found, then 7871 // MaxBECount is the minimum EL.MaxNotTaken of computable 7872 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7873 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7874 // computable EL.MaxNotTaken. 7875 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7876 DT.dominates(ExitBB, Latch)) { 7877 if (!MustExitMaxBECount) { 7878 MustExitMaxBECount = EL.MaxNotTaken; 7879 MustExitMaxOrZero = EL.MaxOrZero; 7880 } else { 7881 MustExitMaxBECount = 7882 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7883 } 7884 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7885 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7886 MayExitMaxBECount = EL.MaxNotTaken; 7887 else { 7888 MayExitMaxBECount = 7889 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7890 } 7891 } 7892 } 7893 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7894 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7895 // The loop backedge will be taken the maximum or zero times if there's 7896 // a single exit that must be taken the maximum or zero times. 7897 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7898 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7899 MaxBECount, MaxOrZero); 7900 } 7901 7902 ScalarEvolution::ExitLimit 7903 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7904 bool AllowPredicates) { 7905 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7906 // If our exiting block does not dominate the latch, then its connection with 7907 // loop's exit limit may be far from trivial. 7908 const BasicBlock *Latch = L->getLoopLatch(); 7909 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7910 return getCouldNotCompute(); 7911 7912 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7913 Instruction *Term = ExitingBlock->getTerminator(); 7914 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7915 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7916 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7917 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7918 "It should have one successor in loop and one exit block!"); 7919 // Proceed to the next level to examine the exit condition expression. 7920 return computeExitLimitFromCond( 7921 L, BI->getCondition(), ExitIfTrue, 7922 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7923 } 7924 7925 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7926 // For switch, make sure that there is a single exit from the loop. 7927 BasicBlock *Exit = nullptr; 7928 for (auto *SBB : successors(ExitingBlock)) 7929 if (!L->contains(SBB)) { 7930 if (Exit) // Multiple exit successors. 7931 return getCouldNotCompute(); 7932 Exit = SBB; 7933 } 7934 assert(Exit && "Exiting block must have at least one exit"); 7935 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7936 /*ControlsExit=*/IsOnlyExit); 7937 } 7938 7939 return getCouldNotCompute(); 7940 } 7941 7942 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7943 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7944 bool ControlsExit, bool AllowPredicates) { 7945 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7946 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7947 ControlsExit, AllowPredicates); 7948 } 7949 7950 Optional<ScalarEvolution::ExitLimit> 7951 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7952 bool ExitIfTrue, bool ControlsExit, 7953 bool AllowPredicates) { 7954 (void)this->L; 7955 (void)this->ExitIfTrue; 7956 (void)this->AllowPredicates; 7957 7958 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7959 this->AllowPredicates == AllowPredicates && 7960 "Variance in assumed invariant key components!"); 7961 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7962 if (Itr == TripCountMap.end()) 7963 return None; 7964 return Itr->second; 7965 } 7966 7967 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7968 bool ExitIfTrue, 7969 bool ControlsExit, 7970 bool AllowPredicates, 7971 const ExitLimit &EL) { 7972 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7973 this->AllowPredicates == AllowPredicates && 7974 "Variance in assumed invariant key components!"); 7975 7976 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7977 assert(InsertResult.second && "Expected successful insertion!"); 7978 (void)InsertResult; 7979 (void)ExitIfTrue; 7980 } 7981 7982 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7983 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7984 bool ControlsExit, bool AllowPredicates) { 7985 7986 if (auto MaybeEL = 7987 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7988 return *MaybeEL; 7989 7990 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7991 ControlsExit, AllowPredicates); 7992 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7993 return EL; 7994 } 7995 7996 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7997 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7998 bool ControlsExit, bool AllowPredicates) { 7999 // Handle BinOp conditions (And, Or). 8000 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 8001 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8002 return *LimitFromBinOp; 8003 8004 // With an icmp, it may be feasible to compute an exact backedge-taken count. 8005 // Proceed to the next level to examine the icmp. 8006 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 8007 ExitLimit EL = 8008 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 8009 if (EL.hasFullInfo() || !AllowPredicates) 8010 return EL; 8011 8012 // Try again, but use SCEV predicates this time. 8013 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8014 /*AllowPredicates=*/true); 8015 } 8016 8017 // Check for a constant condition. These are normally stripped out by 8018 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8019 // preserve the CFG and is temporarily leaving constant conditions 8020 // in place. 8021 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8022 if (ExitIfTrue == !CI->getZExtValue()) 8023 // The backedge is always taken. 8024 return getCouldNotCompute(); 8025 else 8026 // The backedge is never taken. 8027 return getZero(CI->getType()); 8028 } 8029 8030 // If it's not an integer or pointer comparison then compute it the hard way. 8031 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8032 } 8033 8034 Optional<ScalarEvolution::ExitLimit> 8035 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8036 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8037 bool ControlsExit, bool AllowPredicates) { 8038 // Check if the controlling expression for this loop is an And or Or. 8039 Value *Op0, *Op1; 8040 bool IsAnd = false; 8041 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8042 IsAnd = true; 8043 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8044 IsAnd = false; 8045 else 8046 return None; 8047 8048 // EitherMayExit is true in these two cases: 8049 // br (and Op0 Op1), loop, exit 8050 // br (or Op0 Op1), exit, loop 8051 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8052 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8053 ControlsExit && !EitherMayExit, 8054 AllowPredicates); 8055 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8056 ControlsExit && !EitherMayExit, 8057 AllowPredicates); 8058 8059 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8060 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8061 if (isa<ConstantInt>(Op1)) 8062 return Op1 == NeutralElement ? EL0 : EL1; 8063 if (isa<ConstantInt>(Op0)) 8064 return Op0 == NeutralElement ? EL1 : EL0; 8065 8066 const SCEV *BECount = getCouldNotCompute(); 8067 const SCEV *MaxBECount = getCouldNotCompute(); 8068 if (EitherMayExit) { 8069 // Both conditions must be same for the loop to continue executing. 8070 // Choose the less conservative count. 8071 // If ExitCond is a short-circuit form (select), using 8072 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 8073 // To see the detailed examples, please see 8074 // test/Analysis/ScalarEvolution/exit-count-select.ll 8075 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 8076 if (!PoisonSafe) 8077 // Even if ExitCond is select, we can safely derive BECount using both 8078 // EL0 and EL1 in these cases: 8079 // (1) EL0.ExactNotTaken is non-zero 8080 // (2) EL1.ExactNotTaken is non-poison 8081 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 8082 // it cannot be umin(0, ..)) 8083 // The PoisonSafe assignment below is simplified and the assertion after 8084 // BECount calculation fully guarantees the condition (3). 8085 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 8086 isa<SCEVConstant>(EL1.ExactNotTaken); 8087 if (EL0.ExactNotTaken != getCouldNotCompute() && 8088 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 8089 BECount = 8090 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 8091 8092 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8093 // it should have been simplified to zero (see the condition (3) above) 8094 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8095 BECount->isZero()); 8096 } 8097 if (EL0.MaxNotTaken == getCouldNotCompute()) 8098 MaxBECount = EL1.MaxNotTaken; 8099 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8100 MaxBECount = EL0.MaxNotTaken; 8101 else 8102 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8103 } else { 8104 // Both conditions must be same at the same time for the loop to exit. 8105 // For now, be conservative. 8106 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8107 BECount = EL0.ExactNotTaken; 8108 } 8109 8110 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8111 // to be more aggressive when computing BECount than when computing 8112 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8113 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8114 // to not. 8115 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8116 !isa<SCEVCouldNotCompute>(BECount)) 8117 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8118 8119 return ExitLimit(BECount, MaxBECount, false, 8120 { &EL0.Predicates, &EL1.Predicates }); 8121 } 8122 8123 ScalarEvolution::ExitLimit 8124 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8125 ICmpInst *ExitCond, 8126 bool ExitIfTrue, 8127 bool ControlsExit, 8128 bool AllowPredicates) { 8129 // If the condition was exit on true, convert the condition to exit on false 8130 ICmpInst::Predicate Pred; 8131 if (!ExitIfTrue) 8132 Pred = ExitCond->getPredicate(); 8133 else 8134 Pred = ExitCond->getInversePredicate(); 8135 const ICmpInst::Predicate OriginalPred = Pred; 8136 8137 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8138 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8139 8140 // Try to evaluate any dependencies out of the loop. 8141 LHS = getSCEVAtScope(LHS, L); 8142 RHS = getSCEVAtScope(RHS, L); 8143 8144 // At this point, we would like to compute how many iterations of the 8145 // loop the predicate will return true for these inputs. 8146 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8147 // If there is a loop-invariant, force it into the RHS. 8148 std::swap(LHS, RHS); 8149 Pred = ICmpInst::getSwappedPredicate(Pred); 8150 } 8151 8152 // Simplify the operands before analyzing them. 8153 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8154 8155 // If we have a comparison of a chrec against a constant, try to use value 8156 // ranges to answer this query. 8157 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8158 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8159 if (AddRec->getLoop() == L) { 8160 // Form the constant range. 8161 ConstantRange CompRange = 8162 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8163 8164 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8165 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8166 } 8167 8168 switch (Pred) { 8169 case ICmpInst::ICMP_NE: { // while (X != Y) 8170 // Convert to: while (X-Y != 0) 8171 if (LHS->getType()->isPointerTy()) { 8172 LHS = getLosslessPtrToIntExpr(LHS); 8173 if (isa<SCEVCouldNotCompute>(LHS)) 8174 return LHS; 8175 } 8176 if (RHS->getType()->isPointerTy()) { 8177 RHS = getLosslessPtrToIntExpr(RHS); 8178 if (isa<SCEVCouldNotCompute>(RHS)) 8179 return RHS; 8180 } 8181 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8182 AllowPredicates); 8183 if (EL.hasAnyInfo()) return EL; 8184 break; 8185 } 8186 case ICmpInst::ICMP_EQ: { // while (X == Y) 8187 // Convert to: while (X-Y == 0) 8188 if (LHS->getType()->isPointerTy()) { 8189 LHS = getLosslessPtrToIntExpr(LHS); 8190 if (isa<SCEVCouldNotCompute>(LHS)) 8191 return LHS; 8192 } 8193 if (RHS->getType()->isPointerTy()) { 8194 RHS = getLosslessPtrToIntExpr(RHS); 8195 if (isa<SCEVCouldNotCompute>(RHS)) 8196 return RHS; 8197 } 8198 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8199 if (EL.hasAnyInfo()) return EL; 8200 break; 8201 } 8202 case ICmpInst::ICMP_SLT: 8203 case ICmpInst::ICMP_ULT: { // while (X < Y) 8204 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8205 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8206 AllowPredicates); 8207 if (EL.hasAnyInfo()) return EL; 8208 break; 8209 } 8210 case ICmpInst::ICMP_SGT: 8211 case ICmpInst::ICMP_UGT: { // while (X > Y) 8212 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8213 ExitLimit EL = 8214 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8215 AllowPredicates); 8216 if (EL.hasAnyInfo()) return EL; 8217 break; 8218 } 8219 default: 8220 break; 8221 } 8222 8223 auto *ExhaustiveCount = 8224 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8225 8226 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8227 return ExhaustiveCount; 8228 8229 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8230 ExitCond->getOperand(1), L, OriginalPred); 8231 } 8232 8233 ScalarEvolution::ExitLimit 8234 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8235 SwitchInst *Switch, 8236 BasicBlock *ExitingBlock, 8237 bool ControlsExit) { 8238 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8239 8240 // Give up if the exit is the default dest of a switch. 8241 if (Switch->getDefaultDest() == ExitingBlock) 8242 return getCouldNotCompute(); 8243 8244 assert(L->contains(Switch->getDefaultDest()) && 8245 "Default case must not exit the loop!"); 8246 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8247 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8248 8249 // while (X != Y) --> while (X-Y != 0) 8250 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8251 if (EL.hasAnyInfo()) 8252 return EL; 8253 8254 return getCouldNotCompute(); 8255 } 8256 8257 static ConstantInt * 8258 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8259 ScalarEvolution &SE) { 8260 const SCEV *InVal = SE.getConstant(C); 8261 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8262 assert(isa<SCEVConstant>(Val) && 8263 "Evaluation of SCEV at constant didn't fold correctly?"); 8264 return cast<SCEVConstant>(Val)->getValue(); 8265 } 8266 8267 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8268 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8269 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8270 if (!RHS) 8271 return getCouldNotCompute(); 8272 8273 const BasicBlock *Latch = L->getLoopLatch(); 8274 if (!Latch) 8275 return getCouldNotCompute(); 8276 8277 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8278 if (!Predecessor) 8279 return getCouldNotCompute(); 8280 8281 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8282 // Return LHS in OutLHS and shift_opt in OutOpCode. 8283 auto MatchPositiveShift = 8284 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8285 8286 using namespace PatternMatch; 8287 8288 ConstantInt *ShiftAmt; 8289 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8290 OutOpCode = Instruction::LShr; 8291 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8292 OutOpCode = Instruction::AShr; 8293 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8294 OutOpCode = Instruction::Shl; 8295 else 8296 return false; 8297 8298 return ShiftAmt->getValue().isStrictlyPositive(); 8299 }; 8300 8301 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8302 // 8303 // loop: 8304 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8305 // %iv.shifted = lshr i32 %iv, <positive constant> 8306 // 8307 // Return true on a successful match. Return the corresponding PHI node (%iv 8308 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8309 auto MatchShiftRecurrence = 8310 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8311 Optional<Instruction::BinaryOps> PostShiftOpCode; 8312 8313 { 8314 Instruction::BinaryOps OpC; 8315 Value *V; 8316 8317 // If we encounter a shift instruction, "peel off" the shift operation, 8318 // and remember that we did so. Later when we inspect %iv's backedge 8319 // value, we will make sure that the backedge value uses the same 8320 // operation. 8321 // 8322 // Note: the peeled shift operation does not have to be the same 8323 // instruction as the one feeding into the PHI's backedge value. We only 8324 // really care about it being the same *kind* of shift instruction -- 8325 // that's all that is required for our later inferences to hold. 8326 if (MatchPositiveShift(LHS, V, OpC)) { 8327 PostShiftOpCode = OpC; 8328 LHS = V; 8329 } 8330 } 8331 8332 PNOut = dyn_cast<PHINode>(LHS); 8333 if (!PNOut || PNOut->getParent() != L->getHeader()) 8334 return false; 8335 8336 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8337 Value *OpLHS; 8338 8339 return 8340 // The backedge value for the PHI node must be a shift by a positive 8341 // amount 8342 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8343 8344 // of the PHI node itself 8345 OpLHS == PNOut && 8346 8347 // and the kind of shift should be match the kind of shift we peeled 8348 // off, if any. 8349 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8350 }; 8351 8352 PHINode *PN; 8353 Instruction::BinaryOps OpCode; 8354 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8355 return getCouldNotCompute(); 8356 8357 const DataLayout &DL = getDataLayout(); 8358 8359 // The key rationale for this optimization is that for some kinds of shift 8360 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8361 // within a finite number of iterations. If the condition guarding the 8362 // backedge (in the sense that the backedge is taken if the condition is true) 8363 // is false for the value the shift recurrence stabilizes to, then we know 8364 // that the backedge is taken only a finite number of times. 8365 8366 ConstantInt *StableValue = nullptr; 8367 switch (OpCode) { 8368 default: 8369 llvm_unreachable("Impossible case!"); 8370 8371 case Instruction::AShr: { 8372 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8373 // bitwidth(K) iterations. 8374 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8375 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8376 Predecessor->getTerminator(), &DT); 8377 auto *Ty = cast<IntegerType>(RHS->getType()); 8378 if (Known.isNonNegative()) 8379 StableValue = ConstantInt::get(Ty, 0); 8380 else if (Known.isNegative()) 8381 StableValue = ConstantInt::get(Ty, -1, true); 8382 else 8383 return getCouldNotCompute(); 8384 8385 break; 8386 } 8387 case Instruction::LShr: 8388 case Instruction::Shl: 8389 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8390 // stabilize to 0 in at most bitwidth(K) iterations. 8391 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8392 break; 8393 } 8394 8395 auto *Result = 8396 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8397 assert(Result->getType()->isIntegerTy(1) && 8398 "Otherwise cannot be an operand to a branch instruction"); 8399 8400 if (Result->isZeroValue()) { 8401 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8402 const SCEV *UpperBound = 8403 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8404 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8405 } 8406 8407 return getCouldNotCompute(); 8408 } 8409 8410 /// Return true if we can constant fold an instruction of the specified type, 8411 /// assuming that all operands were constants. 8412 static bool CanConstantFold(const Instruction *I) { 8413 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8414 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8415 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8416 return true; 8417 8418 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8419 if (const Function *F = CI->getCalledFunction()) 8420 return canConstantFoldCallTo(CI, F); 8421 return false; 8422 } 8423 8424 /// Determine whether this instruction can constant evolve within this loop 8425 /// assuming its operands can all constant evolve. 8426 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8427 // An instruction outside of the loop can't be derived from a loop PHI. 8428 if (!L->contains(I)) return false; 8429 8430 if (isa<PHINode>(I)) { 8431 // We don't currently keep track of the control flow needed to evaluate 8432 // PHIs, so we cannot handle PHIs inside of loops. 8433 return L->getHeader() == I->getParent(); 8434 } 8435 8436 // If we won't be able to constant fold this expression even if the operands 8437 // are constants, bail early. 8438 return CanConstantFold(I); 8439 } 8440 8441 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8442 /// recursing through each instruction operand until reaching a loop header phi. 8443 static PHINode * 8444 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8445 DenseMap<Instruction *, PHINode *> &PHIMap, 8446 unsigned Depth) { 8447 if (Depth > MaxConstantEvolvingDepth) 8448 return nullptr; 8449 8450 // Otherwise, we can evaluate this instruction if all of its operands are 8451 // constant or derived from a PHI node themselves. 8452 PHINode *PHI = nullptr; 8453 for (Value *Op : UseInst->operands()) { 8454 if (isa<Constant>(Op)) continue; 8455 8456 Instruction *OpInst = dyn_cast<Instruction>(Op); 8457 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8458 8459 PHINode *P = dyn_cast<PHINode>(OpInst); 8460 if (!P) 8461 // If this operand is already visited, reuse the prior result. 8462 // We may have P != PHI if this is the deepest point at which the 8463 // inconsistent paths meet. 8464 P = PHIMap.lookup(OpInst); 8465 if (!P) { 8466 // Recurse and memoize the results, whether a phi is found or not. 8467 // This recursive call invalidates pointers into PHIMap. 8468 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8469 PHIMap[OpInst] = P; 8470 } 8471 if (!P) 8472 return nullptr; // Not evolving from PHI 8473 if (PHI && PHI != P) 8474 return nullptr; // Evolving from multiple different PHIs. 8475 PHI = P; 8476 } 8477 // This is a expression evolving from a constant PHI! 8478 return PHI; 8479 } 8480 8481 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8482 /// in the loop that V is derived from. We allow arbitrary operations along the 8483 /// way, but the operands of an operation must either be constants or a value 8484 /// derived from a constant PHI. If this expression does not fit with these 8485 /// constraints, return null. 8486 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8487 Instruction *I = dyn_cast<Instruction>(V); 8488 if (!I || !canConstantEvolve(I, L)) return nullptr; 8489 8490 if (PHINode *PN = dyn_cast<PHINode>(I)) 8491 return PN; 8492 8493 // Record non-constant instructions contained by the loop. 8494 DenseMap<Instruction *, PHINode *> PHIMap; 8495 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8496 } 8497 8498 /// EvaluateExpression - Given an expression that passes the 8499 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8500 /// in the loop has the value PHIVal. If we can't fold this expression for some 8501 /// reason, return null. 8502 static Constant *EvaluateExpression(Value *V, const Loop *L, 8503 DenseMap<Instruction *, Constant *> &Vals, 8504 const DataLayout &DL, 8505 const TargetLibraryInfo *TLI) { 8506 // Convenient constant check, but redundant for recursive calls. 8507 if (Constant *C = dyn_cast<Constant>(V)) return C; 8508 Instruction *I = dyn_cast<Instruction>(V); 8509 if (!I) return nullptr; 8510 8511 if (Constant *C = Vals.lookup(I)) return C; 8512 8513 // An instruction inside the loop depends on a value outside the loop that we 8514 // weren't given a mapping for, or a value such as a call inside the loop. 8515 if (!canConstantEvolve(I, L)) return nullptr; 8516 8517 // An unmapped PHI can be due to a branch or another loop inside this loop, 8518 // or due to this not being the initial iteration through a loop where we 8519 // couldn't compute the evolution of this particular PHI last time. 8520 if (isa<PHINode>(I)) return nullptr; 8521 8522 std::vector<Constant*> Operands(I->getNumOperands()); 8523 8524 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8525 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8526 if (!Operand) { 8527 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8528 if (!Operands[i]) return nullptr; 8529 continue; 8530 } 8531 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8532 Vals[Operand] = C; 8533 if (!C) return nullptr; 8534 Operands[i] = C; 8535 } 8536 8537 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8538 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8539 Operands[1], DL, TLI); 8540 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8541 if (!LI->isVolatile()) 8542 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8543 } 8544 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8545 } 8546 8547 8548 // If every incoming value to PN except the one for BB is a specific Constant, 8549 // return that, else return nullptr. 8550 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8551 Constant *IncomingVal = nullptr; 8552 8553 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8554 if (PN->getIncomingBlock(i) == BB) 8555 continue; 8556 8557 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8558 if (!CurrentVal) 8559 return nullptr; 8560 8561 if (IncomingVal != CurrentVal) { 8562 if (IncomingVal) 8563 return nullptr; 8564 IncomingVal = CurrentVal; 8565 } 8566 } 8567 8568 return IncomingVal; 8569 } 8570 8571 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8572 /// in the header of its containing loop, we know the loop executes a 8573 /// constant number of times, and the PHI node is just a recurrence 8574 /// involving constants, fold it. 8575 Constant * 8576 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8577 const APInt &BEs, 8578 const Loop *L) { 8579 auto I = ConstantEvolutionLoopExitValue.find(PN); 8580 if (I != ConstantEvolutionLoopExitValue.end()) 8581 return I->second; 8582 8583 if (BEs.ugt(MaxBruteForceIterations)) 8584 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8585 8586 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8587 8588 DenseMap<Instruction *, Constant *> CurrentIterVals; 8589 BasicBlock *Header = L->getHeader(); 8590 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8591 8592 BasicBlock *Latch = L->getLoopLatch(); 8593 if (!Latch) 8594 return nullptr; 8595 8596 for (PHINode &PHI : Header->phis()) { 8597 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8598 CurrentIterVals[&PHI] = StartCST; 8599 } 8600 if (!CurrentIterVals.count(PN)) 8601 return RetVal = nullptr; 8602 8603 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8604 8605 // Execute the loop symbolically to determine the exit value. 8606 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8607 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8608 8609 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8610 unsigned IterationNum = 0; 8611 const DataLayout &DL = getDataLayout(); 8612 for (; ; ++IterationNum) { 8613 if (IterationNum == NumIterations) 8614 return RetVal = CurrentIterVals[PN]; // Got exit value! 8615 8616 // Compute the value of the PHIs for the next iteration. 8617 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8618 DenseMap<Instruction *, Constant *> NextIterVals; 8619 Constant *NextPHI = 8620 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8621 if (!NextPHI) 8622 return nullptr; // Couldn't evaluate! 8623 NextIterVals[PN] = NextPHI; 8624 8625 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8626 8627 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8628 // cease to be able to evaluate one of them or if they stop evolving, 8629 // because that doesn't necessarily prevent us from computing PN. 8630 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8631 for (const auto &I : CurrentIterVals) { 8632 PHINode *PHI = dyn_cast<PHINode>(I.first); 8633 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8634 PHIsToCompute.emplace_back(PHI, I.second); 8635 } 8636 // We use two distinct loops because EvaluateExpression may invalidate any 8637 // iterators into CurrentIterVals. 8638 for (const auto &I : PHIsToCompute) { 8639 PHINode *PHI = I.first; 8640 Constant *&NextPHI = NextIterVals[PHI]; 8641 if (!NextPHI) { // Not already computed. 8642 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8643 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8644 } 8645 if (NextPHI != I.second) 8646 StoppedEvolving = false; 8647 } 8648 8649 // If all entries in CurrentIterVals == NextIterVals then we can stop 8650 // iterating, the loop can't continue to change. 8651 if (StoppedEvolving) 8652 return RetVal = CurrentIterVals[PN]; 8653 8654 CurrentIterVals.swap(NextIterVals); 8655 } 8656 } 8657 8658 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8659 Value *Cond, 8660 bool ExitWhen) { 8661 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8662 if (!PN) return getCouldNotCompute(); 8663 8664 // If the loop is canonicalized, the PHI will have exactly two entries. 8665 // That's the only form we support here. 8666 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8667 8668 DenseMap<Instruction *, Constant *> CurrentIterVals; 8669 BasicBlock *Header = L->getHeader(); 8670 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8671 8672 BasicBlock *Latch = L->getLoopLatch(); 8673 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8674 8675 for (PHINode &PHI : Header->phis()) { 8676 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8677 CurrentIterVals[&PHI] = StartCST; 8678 } 8679 if (!CurrentIterVals.count(PN)) 8680 return getCouldNotCompute(); 8681 8682 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8683 // the loop symbolically to determine when the condition gets a value of 8684 // "ExitWhen". 8685 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8686 const DataLayout &DL = getDataLayout(); 8687 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8688 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8689 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8690 8691 // Couldn't symbolically evaluate. 8692 if (!CondVal) return getCouldNotCompute(); 8693 8694 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8695 ++NumBruteForceTripCountsComputed; 8696 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8697 } 8698 8699 // Update all the PHI nodes for the next iteration. 8700 DenseMap<Instruction *, Constant *> NextIterVals; 8701 8702 // Create a list of which PHIs we need to compute. We want to do this before 8703 // calling EvaluateExpression on them because that may invalidate iterators 8704 // into CurrentIterVals. 8705 SmallVector<PHINode *, 8> PHIsToCompute; 8706 for (const auto &I : CurrentIterVals) { 8707 PHINode *PHI = dyn_cast<PHINode>(I.first); 8708 if (!PHI || PHI->getParent() != Header) continue; 8709 PHIsToCompute.push_back(PHI); 8710 } 8711 for (PHINode *PHI : PHIsToCompute) { 8712 Constant *&NextPHI = NextIterVals[PHI]; 8713 if (NextPHI) continue; // Already computed! 8714 8715 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8716 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8717 } 8718 CurrentIterVals.swap(NextIterVals); 8719 } 8720 8721 // Too many iterations were needed to evaluate. 8722 return getCouldNotCompute(); 8723 } 8724 8725 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8726 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8727 ValuesAtScopes[V]; 8728 // Check to see if we've folded this expression at this loop before. 8729 for (auto &LS : Values) 8730 if (LS.first == L) 8731 return LS.second ? LS.second : V; 8732 8733 Values.emplace_back(L, nullptr); 8734 8735 // Otherwise compute it. 8736 const SCEV *C = computeSCEVAtScope(V, L); 8737 for (auto &LS : reverse(ValuesAtScopes[V])) 8738 if (LS.first == L) { 8739 LS.second = C; 8740 break; 8741 } 8742 return C; 8743 } 8744 8745 /// This builds up a Constant using the ConstantExpr interface. That way, we 8746 /// will return Constants for objects which aren't represented by a 8747 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8748 /// Returns NULL if the SCEV isn't representable as a Constant. 8749 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8750 switch (V->getSCEVType()) { 8751 case scCouldNotCompute: 8752 case scAddRecExpr: 8753 return nullptr; 8754 case scConstant: 8755 return cast<SCEVConstant>(V)->getValue(); 8756 case scUnknown: 8757 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8758 case scSignExtend: { 8759 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8760 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8761 return ConstantExpr::getSExt(CastOp, SS->getType()); 8762 return nullptr; 8763 } 8764 case scZeroExtend: { 8765 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8766 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8767 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8768 return nullptr; 8769 } 8770 case scPtrToInt: { 8771 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8772 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8773 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8774 8775 return nullptr; 8776 } 8777 case scTruncate: { 8778 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8779 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8780 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8781 return nullptr; 8782 } 8783 case scAddExpr: { 8784 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8785 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8786 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8787 unsigned AS = PTy->getAddressSpace(); 8788 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8789 C = ConstantExpr::getBitCast(C, DestPtrTy); 8790 } 8791 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8792 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8793 if (!C2) 8794 return nullptr; 8795 8796 // First pointer! 8797 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8798 unsigned AS = C2->getType()->getPointerAddressSpace(); 8799 std::swap(C, C2); 8800 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8801 // The offsets have been converted to bytes. We can add bytes to an 8802 // i8* by GEP with the byte count in the first index. 8803 C = ConstantExpr::getBitCast(C, DestPtrTy); 8804 } 8805 8806 // Don't bother trying to sum two pointers. We probably can't 8807 // statically compute a load that results from it anyway. 8808 if (C2->getType()->isPointerTy()) 8809 return nullptr; 8810 8811 if (C->getType()->isPointerTy()) { 8812 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8813 C, C2); 8814 } else { 8815 C = ConstantExpr::getAdd(C, C2); 8816 } 8817 } 8818 return C; 8819 } 8820 return nullptr; 8821 } 8822 case scMulExpr: { 8823 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8824 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8825 // Don't bother with pointers at all. 8826 if (C->getType()->isPointerTy()) 8827 return nullptr; 8828 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8829 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8830 if (!C2 || C2->getType()->isPointerTy()) 8831 return nullptr; 8832 C = ConstantExpr::getMul(C, C2); 8833 } 8834 return C; 8835 } 8836 return nullptr; 8837 } 8838 case scUDivExpr: { 8839 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8840 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8841 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8842 if (LHS->getType() == RHS->getType()) 8843 return ConstantExpr::getUDiv(LHS, RHS); 8844 return nullptr; 8845 } 8846 case scSMaxExpr: 8847 case scUMaxExpr: 8848 case scSMinExpr: 8849 case scUMinExpr: 8850 return nullptr; // TODO: smax, umax, smin, umax. 8851 } 8852 llvm_unreachable("Unknown SCEV kind!"); 8853 } 8854 8855 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8856 if (isa<SCEVConstant>(V)) return V; 8857 8858 // If this instruction is evolved from a constant-evolving PHI, compute the 8859 // exit value from the loop without using SCEVs. 8860 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8861 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8862 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8863 const Loop *CurrLoop = this->LI[I->getParent()]; 8864 // Looking for loop exit value. 8865 if (CurrLoop && CurrLoop->getParentLoop() == L && 8866 PN->getParent() == CurrLoop->getHeader()) { 8867 // Okay, there is no closed form solution for the PHI node. Check 8868 // to see if the loop that contains it has a known backedge-taken 8869 // count. If so, we may be able to force computation of the exit 8870 // value. 8871 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8872 // This trivial case can show up in some degenerate cases where 8873 // the incoming IR has not yet been fully simplified. 8874 if (BackedgeTakenCount->isZero()) { 8875 Value *InitValue = nullptr; 8876 bool MultipleInitValues = false; 8877 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8878 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8879 if (!InitValue) 8880 InitValue = PN->getIncomingValue(i); 8881 else if (InitValue != PN->getIncomingValue(i)) { 8882 MultipleInitValues = true; 8883 break; 8884 } 8885 } 8886 } 8887 if (!MultipleInitValues && InitValue) 8888 return getSCEV(InitValue); 8889 } 8890 // Do we have a loop invariant value flowing around the backedge 8891 // for a loop which must execute the backedge? 8892 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8893 isKnownPositive(BackedgeTakenCount) && 8894 PN->getNumIncomingValues() == 2) { 8895 8896 unsigned InLoopPred = 8897 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8898 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8899 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8900 return getSCEV(BackedgeVal); 8901 } 8902 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8903 // Okay, we know how many times the containing loop executes. If 8904 // this is a constant evolving PHI node, get the final value at 8905 // the specified iteration number. 8906 Constant *RV = getConstantEvolutionLoopExitValue( 8907 PN, BTCC->getAPInt(), CurrLoop); 8908 if (RV) return getSCEV(RV); 8909 } 8910 } 8911 8912 // If there is a single-input Phi, evaluate it at our scope. If we can 8913 // prove that this replacement does not break LCSSA form, use new value. 8914 if (PN->getNumOperands() == 1) { 8915 const SCEV *Input = getSCEV(PN->getOperand(0)); 8916 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8917 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8918 // for the simplest case just support constants. 8919 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8920 } 8921 } 8922 8923 // Okay, this is an expression that we cannot symbolically evaluate 8924 // into a SCEV. Check to see if it's possible to symbolically evaluate 8925 // the arguments into constants, and if so, try to constant propagate the 8926 // result. This is particularly useful for computing loop exit values. 8927 if (CanConstantFold(I)) { 8928 SmallVector<Constant *, 4> Operands; 8929 bool MadeImprovement = false; 8930 for (Value *Op : I->operands()) { 8931 if (Constant *C = dyn_cast<Constant>(Op)) { 8932 Operands.push_back(C); 8933 continue; 8934 } 8935 8936 // If any of the operands is non-constant and if they are 8937 // non-integer and non-pointer, don't even try to analyze them 8938 // with scev techniques. 8939 if (!isSCEVable(Op->getType())) 8940 return V; 8941 8942 const SCEV *OrigV = getSCEV(Op); 8943 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8944 MadeImprovement |= OrigV != OpV; 8945 8946 Constant *C = BuildConstantFromSCEV(OpV); 8947 if (!C) return V; 8948 if (C->getType() != Op->getType()) 8949 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8950 Op->getType(), 8951 false), 8952 C, Op->getType()); 8953 Operands.push_back(C); 8954 } 8955 8956 // Check to see if getSCEVAtScope actually made an improvement. 8957 if (MadeImprovement) { 8958 Constant *C = nullptr; 8959 const DataLayout &DL = getDataLayout(); 8960 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8961 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8962 Operands[1], DL, &TLI); 8963 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8964 if (!Load->isVolatile()) 8965 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8966 DL); 8967 } else 8968 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8969 if (!C) return V; 8970 return getSCEV(C); 8971 } 8972 } 8973 } 8974 8975 // This is some other type of SCEVUnknown, just return it. 8976 return V; 8977 } 8978 8979 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8980 // Avoid performing the look-up in the common case where the specified 8981 // expression has no loop-variant portions. 8982 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8983 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8984 if (OpAtScope != Comm->getOperand(i)) { 8985 // Okay, at least one of these operands is loop variant but might be 8986 // foldable. Build a new instance of the folded commutative expression. 8987 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8988 Comm->op_begin()+i); 8989 NewOps.push_back(OpAtScope); 8990 8991 for (++i; i != e; ++i) { 8992 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8993 NewOps.push_back(OpAtScope); 8994 } 8995 if (isa<SCEVAddExpr>(Comm)) 8996 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8997 if (isa<SCEVMulExpr>(Comm)) 8998 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8999 if (isa<SCEVMinMaxExpr>(Comm)) 9000 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9001 llvm_unreachable("Unknown commutative SCEV type!"); 9002 } 9003 } 9004 // If we got here, all operands are loop invariant. 9005 return Comm; 9006 } 9007 9008 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9009 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9010 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9011 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9012 return Div; // must be loop invariant 9013 return getUDivExpr(LHS, RHS); 9014 } 9015 9016 // If this is a loop recurrence for a loop that does not contain L, then we 9017 // are dealing with the final value computed by the loop. 9018 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9019 // First, attempt to evaluate each operand. 9020 // Avoid performing the look-up in the common case where the specified 9021 // expression has no loop-variant portions. 9022 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9023 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9024 if (OpAtScope == AddRec->getOperand(i)) 9025 continue; 9026 9027 // Okay, at least one of these operands is loop variant but might be 9028 // foldable. Build a new instance of the folded commutative expression. 9029 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9030 AddRec->op_begin()+i); 9031 NewOps.push_back(OpAtScope); 9032 for (++i; i != e; ++i) 9033 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9034 9035 const SCEV *FoldedRec = 9036 getAddRecExpr(NewOps, AddRec->getLoop(), 9037 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9038 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9039 // The addrec may be folded to a nonrecurrence, for example, if the 9040 // induction variable is multiplied by zero after constant folding. Go 9041 // ahead and return the folded value. 9042 if (!AddRec) 9043 return FoldedRec; 9044 break; 9045 } 9046 9047 // If the scope is outside the addrec's loop, evaluate it by using the 9048 // loop exit value of the addrec. 9049 if (!AddRec->getLoop()->contains(L)) { 9050 // To evaluate this recurrence, we need to know how many times the AddRec 9051 // loop iterates. Compute this now. 9052 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9053 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9054 9055 // Then, evaluate the AddRec. 9056 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9057 } 9058 9059 return AddRec; 9060 } 9061 9062 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9063 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9064 if (Op == Cast->getOperand()) 9065 return Cast; // must be loop invariant 9066 return getZeroExtendExpr(Op, Cast->getType()); 9067 } 9068 9069 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9070 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9071 if (Op == Cast->getOperand()) 9072 return Cast; // must be loop invariant 9073 return getSignExtendExpr(Op, Cast->getType()); 9074 } 9075 9076 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9077 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9078 if (Op == Cast->getOperand()) 9079 return Cast; // must be loop invariant 9080 return getTruncateExpr(Op, Cast->getType()); 9081 } 9082 9083 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9084 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9085 if (Op == Cast->getOperand()) 9086 return Cast; // must be loop invariant 9087 return getPtrToIntExpr(Op, Cast->getType()); 9088 } 9089 9090 llvm_unreachable("Unknown SCEV type!"); 9091 } 9092 9093 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9094 return getSCEVAtScope(getSCEV(V), L); 9095 } 9096 9097 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9098 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9099 return stripInjectiveFunctions(ZExt->getOperand()); 9100 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9101 return stripInjectiveFunctions(SExt->getOperand()); 9102 return S; 9103 } 9104 9105 /// Finds the minimum unsigned root of the following equation: 9106 /// 9107 /// A * X = B (mod N) 9108 /// 9109 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9110 /// A and B isn't important. 9111 /// 9112 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9113 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9114 ScalarEvolution &SE) { 9115 uint32_t BW = A.getBitWidth(); 9116 assert(BW == SE.getTypeSizeInBits(B->getType())); 9117 assert(A != 0 && "A must be non-zero."); 9118 9119 // 1. D = gcd(A, N) 9120 // 9121 // The gcd of A and N may have only one prime factor: 2. The number of 9122 // trailing zeros in A is its multiplicity 9123 uint32_t Mult2 = A.countTrailingZeros(); 9124 // D = 2^Mult2 9125 9126 // 2. Check if B is divisible by D. 9127 // 9128 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9129 // is not less than multiplicity of this prime factor for D. 9130 if (SE.GetMinTrailingZeros(B) < Mult2) 9131 return SE.getCouldNotCompute(); 9132 9133 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9134 // modulo (N / D). 9135 // 9136 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9137 // (N / D) in general. The inverse itself always fits into BW bits, though, 9138 // so we immediately truncate it. 9139 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9140 APInt Mod(BW + 1, 0); 9141 Mod.setBit(BW - Mult2); // Mod = N / D 9142 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9143 9144 // 4. Compute the minimum unsigned root of the equation: 9145 // I * (B / D) mod (N / D) 9146 // To simplify the computation, we factor out the divide by D: 9147 // (I * B mod N) / D 9148 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9149 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9150 } 9151 9152 /// For a given quadratic addrec, generate coefficients of the corresponding 9153 /// quadratic equation, multiplied by a common value to ensure that they are 9154 /// integers. 9155 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9156 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9157 /// were multiplied by, and BitWidth is the bit width of the original addrec 9158 /// coefficients. 9159 /// This function returns None if the addrec coefficients are not compile- 9160 /// time constants. 9161 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9162 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9163 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9164 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9165 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9166 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9167 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9168 << *AddRec << '\n'); 9169 9170 // We currently can only solve this if the coefficients are constants. 9171 if (!LC || !MC || !NC) { 9172 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9173 return None; 9174 } 9175 9176 APInt L = LC->getAPInt(); 9177 APInt M = MC->getAPInt(); 9178 APInt N = NC->getAPInt(); 9179 assert(!N.isZero() && "This is not a quadratic addrec"); 9180 9181 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9182 unsigned NewWidth = BitWidth + 1; 9183 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9184 << BitWidth << '\n'); 9185 // The sign-extension (as opposed to a zero-extension) here matches the 9186 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9187 N = N.sext(NewWidth); 9188 M = M.sext(NewWidth); 9189 L = L.sext(NewWidth); 9190 9191 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9192 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9193 // L+M, L+2M+N, L+3M+3N, ... 9194 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9195 // 9196 // The equation Acc = 0 is then 9197 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9198 // In a quadratic form it becomes: 9199 // N n^2 + (2M-N) n + 2L = 0. 9200 9201 APInt A = N; 9202 APInt B = 2 * M - A; 9203 APInt C = 2 * L; 9204 APInt T = APInt(NewWidth, 2); 9205 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9206 << "x + " << C << ", coeff bw: " << NewWidth 9207 << ", multiplied by " << T << '\n'); 9208 return std::make_tuple(A, B, C, T, BitWidth); 9209 } 9210 9211 /// Helper function to compare optional APInts: 9212 /// (a) if X and Y both exist, return min(X, Y), 9213 /// (b) if neither X nor Y exist, return None, 9214 /// (c) if exactly one of X and Y exists, return that value. 9215 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9216 if (X.hasValue() && Y.hasValue()) { 9217 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9218 APInt XW = X->sextOrSelf(W); 9219 APInt YW = Y->sextOrSelf(W); 9220 return XW.slt(YW) ? *X : *Y; 9221 } 9222 if (!X.hasValue() && !Y.hasValue()) 9223 return None; 9224 return X.hasValue() ? *X : *Y; 9225 } 9226 9227 /// Helper function to truncate an optional APInt to a given BitWidth. 9228 /// When solving addrec-related equations, it is preferable to return a value 9229 /// that has the same bit width as the original addrec's coefficients. If the 9230 /// solution fits in the original bit width, truncate it (except for i1). 9231 /// Returning a value of a different bit width may inhibit some optimizations. 9232 /// 9233 /// In general, a solution to a quadratic equation generated from an addrec 9234 /// may require BW+1 bits, where BW is the bit width of the addrec's 9235 /// coefficients. The reason is that the coefficients of the quadratic 9236 /// equation are BW+1 bits wide (to avoid truncation when converting from 9237 /// the addrec to the equation). 9238 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9239 if (!X.hasValue()) 9240 return None; 9241 unsigned W = X->getBitWidth(); 9242 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9243 return X->trunc(BitWidth); 9244 return X; 9245 } 9246 9247 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9248 /// iterations. The values L, M, N are assumed to be signed, and they 9249 /// should all have the same bit widths. 9250 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9251 /// where BW is the bit width of the addrec's coefficients. 9252 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9253 /// returned as such, otherwise the bit width of the returned value may 9254 /// be greater than BW. 9255 /// 9256 /// This function returns None if 9257 /// (a) the addrec coefficients are not constant, or 9258 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9259 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9260 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9261 static Optional<APInt> 9262 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9263 APInt A, B, C, M; 9264 unsigned BitWidth; 9265 auto T = GetQuadraticEquation(AddRec); 9266 if (!T.hasValue()) 9267 return None; 9268 9269 std::tie(A, B, C, M, BitWidth) = *T; 9270 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9271 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9272 if (!X.hasValue()) 9273 return None; 9274 9275 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9276 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9277 if (!V->isZero()) 9278 return None; 9279 9280 return TruncIfPossible(X, BitWidth); 9281 } 9282 9283 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9284 /// iterations. The values M, N are assumed to be signed, and they 9285 /// should all have the same bit widths. 9286 /// Find the least n such that c(n) does not belong to the given range, 9287 /// while c(n-1) does. 9288 /// 9289 /// This function returns None if 9290 /// (a) the addrec coefficients are not constant, or 9291 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9292 /// bounds of the range. 9293 static Optional<APInt> 9294 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9295 const ConstantRange &Range, ScalarEvolution &SE) { 9296 assert(AddRec->getOperand(0)->isZero() && 9297 "Starting value of addrec should be 0"); 9298 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9299 << Range << ", addrec " << *AddRec << '\n'); 9300 // This case is handled in getNumIterationsInRange. Here we can assume that 9301 // we start in the range. 9302 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9303 "Addrec's initial value should be in range"); 9304 9305 APInt A, B, C, M; 9306 unsigned BitWidth; 9307 auto T = GetQuadraticEquation(AddRec); 9308 if (!T.hasValue()) 9309 return None; 9310 9311 // Be careful about the return value: there can be two reasons for not 9312 // returning an actual number. First, if no solutions to the equations 9313 // were found, and second, if the solutions don't leave the given range. 9314 // The first case means that the actual solution is "unknown", the second 9315 // means that it's known, but not valid. If the solution is unknown, we 9316 // cannot make any conclusions. 9317 // Return a pair: the optional solution and a flag indicating if the 9318 // solution was found. 9319 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9320 // Solve for signed overflow and unsigned overflow, pick the lower 9321 // solution. 9322 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9323 << Bound << " (before multiplying by " << M << ")\n"); 9324 Bound *= M; // The quadratic equation multiplier. 9325 9326 Optional<APInt> SO = None; 9327 if (BitWidth > 1) { 9328 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9329 "signed overflow\n"); 9330 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9331 } 9332 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9333 "unsigned overflow\n"); 9334 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9335 BitWidth+1); 9336 9337 auto LeavesRange = [&] (const APInt &X) { 9338 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9339 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9340 if (Range.contains(V0->getValue())) 9341 return false; 9342 // X should be at least 1, so X-1 is non-negative. 9343 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9344 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9345 if (Range.contains(V1->getValue())) 9346 return true; 9347 return false; 9348 }; 9349 9350 // If SolveQuadraticEquationWrap returns None, it means that there can 9351 // be a solution, but the function failed to find it. We cannot treat it 9352 // as "no solution". 9353 if (!SO.hasValue() || !UO.hasValue()) 9354 return { None, false }; 9355 9356 // Check the smaller value first to see if it leaves the range. 9357 // At this point, both SO and UO must have values. 9358 Optional<APInt> Min = MinOptional(SO, UO); 9359 if (LeavesRange(*Min)) 9360 return { Min, true }; 9361 Optional<APInt> Max = Min == SO ? UO : SO; 9362 if (LeavesRange(*Max)) 9363 return { Max, true }; 9364 9365 // Solutions were found, but were eliminated, hence the "true". 9366 return { None, true }; 9367 }; 9368 9369 std::tie(A, B, C, M, BitWidth) = *T; 9370 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9371 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9372 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9373 auto SL = SolveForBoundary(Lower); 9374 auto SU = SolveForBoundary(Upper); 9375 // If any of the solutions was unknown, no meaninigful conclusions can 9376 // be made. 9377 if (!SL.second || !SU.second) 9378 return None; 9379 9380 // Claim: The correct solution is not some value between Min and Max. 9381 // 9382 // Justification: Assuming that Min and Max are different values, one of 9383 // them is when the first signed overflow happens, the other is when the 9384 // first unsigned overflow happens. Crossing the range boundary is only 9385 // possible via an overflow (treating 0 as a special case of it, modeling 9386 // an overflow as crossing k*2^W for some k). 9387 // 9388 // The interesting case here is when Min was eliminated as an invalid 9389 // solution, but Max was not. The argument is that if there was another 9390 // overflow between Min and Max, it would also have been eliminated if 9391 // it was considered. 9392 // 9393 // For a given boundary, it is possible to have two overflows of the same 9394 // type (signed/unsigned) without having the other type in between: this 9395 // can happen when the vertex of the parabola is between the iterations 9396 // corresponding to the overflows. This is only possible when the two 9397 // overflows cross k*2^W for the same k. In such case, if the second one 9398 // left the range (and was the first one to do so), the first overflow 9399 // would have to enter the range, which would mean that either we had left 9400 // the range before or that we started outside of it. Both of these cases 9401 // are contradictions. 9402 // 9403 // Claim: In the case where SolveForBoundary returns None, the correct 9404 // solution is not some value between the Max for this boundary and the 9405 // Min of the other boundary. 9406 // 9407 // Justification: Assume that we had such Max_A and Min_B corresponding 9408 // to range boundaries A and B and such that Max_A < Min_B. If there was 9409 // a solution between Max_A and Min_B, it would have to be caused by an 9410 // overflow corresponding to either A or B. It cannot correspond to B, 9411 // since Min_B is the first occurrence of such an overflow. If it 9412 // corresponded to A, it would have to be either a signed or an unsigned 9413 // overflow that is larger than both eliminated overflows for A. But 9414 // between the eliminated overflows and this overflow, the values would 9415 // cover the entire value space, thus crossing the other boundary, which 9416 // is a contradiction. 9417 9418 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9419 } 9420 9421 ScalarEvolution::ExitLimit 9422 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9423 bool AllowPredicates) { 9424 9425 // This is only used for loops with a "x != y" exit test. The exit condition 9426 // is now expressed as a single expression, V = x-y. So the exit test is 9427 // effectively V != 0. We know and take advantage of the fact that this 9428 // expression only being used in a comparison by zero context. 9429 9430 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9431 // If the value is a constant 9432 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9433 // If the value is already zero, the branch will execute zero times. 9434 if (C->getValue()->isZero()) return C; 9435 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9436 } 9437 9438 const SCEVAddRecExpr *AddRec = 9439 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9440 9441 if (!AddRec && AllowPredicates) 9442 // Try to make this an AddRec using runtime tests, in the first X 9443 // iterations of this loop, where X is the SCEV expression found by the 9444 // algorithm below. 9445 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9446 9447 if (!AddRec || AddRec->getLoop() != L) 9448 return getCouldNotCompute(); 9449 9450 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9451 // the quadratic equation to solve it. 9452 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9453 // We can only use this value if the chrec ends up with an exact zero 9454 // value at this index. When solving for "X*X != 5", for example, we 9455 // should not accept a root of 2. 9456 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9457 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9458 return ExitLimit(R, R, false, Predicates); 9459 } 9460 return getCouldNotCompute(); 9461 } 9462 9463 // Otherwise we can only handle this if it is affine. 9464 if (!AddRec->isAffine()) 9465 return getCouldNotCompute(); 9466 9467 // If this is an affine expression, the execution count of this branch is 9468 // the minimum unsigned root of the following equation: 9469 // 9470 // Start + Step*N = 0 (mod 2^BW) 9471 // 9472 // equivalent to: 9473 // 9474 // Step*N = -Start (mod 2^BW) 9475 // 9476 // where BW is the common bit width of Start and Step. 9477 9478 // Get the initial value for the loop. 9479 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9480 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9481 9482 // For now we handle only constant steps. 9483 // 9484 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9485 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9486 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9487 // We have not yet seen any such cases. 9488 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9489 if (!StepC || StepC->getValue()->isZero()) 9490 return getCouldNotCompute(); 9491 9492 // For positive steps (counting up until unsigned overflow): 9493 // N = -Start/Step (as unsigned) 9494 // For negative steps (counting down to zero): 9495 // N = Start/-Step 9496 // First compute the unsigned distance from zero in the direction of Step. 9497 bool CountDown = StepC->getAPInt().isNegative(); 9498 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9499 9500 // Handle unitary steps, which cannot wraparound. 9501 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9502 // N = Distance (as unsigned) 9503 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9504 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9505 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9506 if (MaxBECountBase.ult(MaxBECount)) 9507 MaxBECount = MaxBECountBase; 9508 9509 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9510 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9511 // case, and see if we can improve the bound. 9512 // 9513 // Explicitly handling this here is necessary because getUnsignedRange 9514 // isn't context-sensitive; it doesn't know that we only care about the 9515 // range inside the loop. 9516 const SCEV *Zero = getZero(Distance->getType()); 9517 const SCEV *One = getOne(Distance->getType()); 9518 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9519 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9520 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9521 // as "unsigned_max(Distance + 1) - 1". 9522 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9523 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9524 } 9525 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9526 } 9527 9528 // If the condition controls loop exit (the loop exits only if the expression 9529 // is true) and the addition is no-wrap we can use unsigned divide to 9530 // compute the backedge count. In this case, the step may not divide the 9531 // distance, but we don't care because if the condition is "missed" the loop 9532 // will have undefined behavior due to wrapping. 9533 if (ControlsExit && AddRec->hasNoSelfWrap() && 9534 loopHasNoAbnormalExits(AddRec->getLoop())) { 9535 const SCEV *Exact = 9536 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9537 const SCEV *Max = getCouldNotCompute(); 9538 if (Exact != getCouldNotCompute()) { 9539 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9540 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9541 if (BaseMaxInt.ult(MaxInt)) 9542 Max = getConstant(BaseMaxInt); 9543 else 9544 Max = getConstant(MaxInt); 9545 } 9546 return ExitLimit(Exact, Max, false, Predicates); 9547 } 9548 9549 // Solve the general equation. 9550 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9551 getNegativeSCEV(Start), *this); 9552 const SCEV *M = E == getCouldNotCompute() 9553 ? E 9554 : getConstant(getUnsignedRangeMax(E)); 9555 return ExitLimit(E, M, false, Predicates); 9556 } 9557 9558 ScalarEvolution::ExitLimit 9559 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9560 // Loops that look like: while (X == 0) are very strange indeed. We don't 9561 // handle them yet except for the trivial case. This could be expanded in the 9562 // future as needed. 9563 9564 // If the value is a constant, check to see if it is known to be non-zero 9565 // already. If so, the backedge will execute zero times. 9566 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9567 if (!C->getValue()->isZero()) 9568 return getZero(C->getType()); 9569 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9570 } 9571 9572 // We could implement others, but I really doubt anyone writes loops like 9573 // this, and if they did, they would already be constant folded. 9574 return getCouldNotCompute(); 9575 } 9576 9577 std::pair<const BasicBlock *, const BasicBlock *> 9578 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9579 const { 9580 // If the block has a unique predecessor, then there is no path from the 9581 // predecessor to the block that does not go through the direct edge 9582 // from the predecessor to the block. 9583 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9584 return {Pred, BB}; 9585 9586 // A loop's header is defined to be a block that dominates the loop. 9587 // If the header has a unique predecessor outside the loop, it must be 9588 // a block that has exactly one successor that can reach the loop. 9589 if (const Loop *L = LI.getLoopFor(BB)) 9590 return {L->getLoopPredecessor(), L->getHeader()}; 9591 9592 return {nullptr, nullptr}; 9593 } 9594 9595 /// SCEV structural equivalence is usually sufficient for testing whether two 9596 /// expressions are equal, however for the purposes of looking for a condition 9597 /// guarding a loop, it can be useful to be a little more general, since a 9598 /// front-end may have replicated the controlling expression. 9599 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9600 // Quick check to see if they are the same SCEV. 9601 if (A == B) return true; 9602 9603 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9604 // Not all instructions that are "identical" compute the same value. For 9605 // instance, two distinct alloca instructions allocating the same type are 9606 // identical and do not read memory; but compute distinct values. 9607 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9608 }; 9609 9610 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9611 // two different instructions with the same value. Check for this case. 9612 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9613 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9614 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9615 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9616 if (ComputesEqualValues(AI, BI)) 9617 return true; 9618 9619 // Otherwise assume they may have a different value. 9620 return false; 9621 } 9622 9623 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9624 const SCEV *&LHS, const SCEV *&RHS, 9625 unsigned Depth) { 9626 bool Changed = false; 9627 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9628 // '0 != 0'. 9629 auto TrivialCase = [&](bool TriviallyTrue) { 9630 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9631 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9632 return true; 9633 }; 9634 // If we hit the max recursion limit bail out. 9635 if (Depth >= 3) 9636 return false; 9637 9638 // Canonicalize a constant to the right side. 9639 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9640 // Check for both operands constant. 9641 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9642 if (ConstantExpr::getICmp(Pred, 9643 LHSC->getValue(), 9644 RHSC->getValue())->isNullValue()) 9645 return TrivialCase(false); 9646 else 9647 return TrivialCase(true); 9648 } 9649 // Otherwise swap the operands to put the constant on the right. 9650 std::swap(LHS, RHS); 9651 Pred = ICmpInst::getSwappedPredicate(Pred); 9652 Changed = true; 9653 } 9654 9655 // If we're comparing an addrec with a value which is loop-invariant in the 9656 // addrec's loop, put the addrec on the left. Also make a dominance check, 9657 // as both operands could be addrecs loop-invariant in each other's loop. 9658 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9659 const Loop *L = AR->getLoop(); 9660 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9661 std::swap(LHS, RHS); 9662 Pred = ICmpInst::getSwappedPredicate(Pred); 9663 Changed = true; 9664 } 9665 } 9666 9667 // If there's a constant operand, canonicalize comparisons with boundary 9668 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9669 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9670 const APInt &RA = RC->getAPInt(); 9671 9672 bool SimplifiedByConstantRange = false; 9673 9674 if (!ICmpInst::isEquality(Pred)) { 9675 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9676 if (ExactCR.isFullSet()) 9677 return TrivialCase(true); 9678 else if (ExactCR.isEmptySet()) 9679 return TrivialCase(false); 9680 9681 APInt NewRHS; 9682 CmpInst::Predicate NewPred; 9683 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9684 ICmpInst::isEquality(NewPred)) { 9685 // We were able to convert an inequality to an equality. 9686 Pred = NewPred; 9687 RHS = getConstant(NewRHS); 9688 Changed = SimplifiedByConstantRange = true; 9689 } 9690 } 9691 9692 if (!SimplifiedByConstantRange) { 9693 switch (Pred) { 9694 default: 9695 break; 9696 case ICmpInst::ICMP_EQ: 9697 case ICmpInst::ICMP_NE: 9698 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9699 if (!RA) 9700 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9701 if (const SCEVMulExpr *ME = 9702 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9703 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9704 ME->getOperand(0)->isAllOnesValue()) { 9705 RHS = AE->getOperand(1); 9706 LHS = ME->getOperand(1); 9707 Changed = true; 9708 } 9709 break; 9710 9711 9712 // The "Should have been caught earlier!" messages refer to the fact 9713 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9714 // should have fired on the corresponding cases, and canonicalized the 9715 // check to trivial case. 9716 9717 case ICmpInst::ICMP_UGE: 9718 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9719 Pred = ICmpInst::ICMP_UGT; 9720 RHS = getConstant(RA - 1); 9721 Changed = true; 9722 break; 9723 case ICmpInst::ICMP_ULE: 9724 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9725 Pred = ICmpInst::ICMP_ULT; 9726 RHS = getConstant(RA + 1); 9727 Changed = true; 9728 break; 9729 case ICmpInst::ICMP_SGE: 9730 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9731 Pred = ICmpInst::ICMP_SGT; 9732 RHS = getConstant(RA - 1); 9733 Changed = true; 9734 break; 9735 case ICmpInst::ICMP_SLE: 9736 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9737 Pred = ICmpInst::ICMP_SLT; 9738 RHS = getConstant(RA + 1); 9739 Changed = true; 9740 break; 9741 } 9742 } 9743 } 9744 9745 // Check for obvious equality. 9746 if (HasSameValue(LHS, RHS)) { 9747 if (ICmpInst::isTrueWhenEqual(Pred)) 9748 return TrivialCase(true); 9749 if (ICmpInst::isFalseWhenEqual(Pred)) 9750 return TrivialCase(false); 9751 } 9752 9753 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9754 // adding or subtracting 1 from one of the operands. 9755 switch (Pred) { 9756 case ICmpInst::ICMP_SLE: 9757 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9758 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9759 SCEV::FlagNSW); 9760 Pred = ICmpInst::ICMP_SLT; 9761 Changed = true; 9762 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9763 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9764 SCEV::FlagNSW); 9765 Pred = ICmpInst::ICMP_SLT; 9766 Changed = true; 9767 } 9768 break; 9769 case ICmpInst::ICMP_SGE: 9770 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9771 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9772 SCEV::FlagNSW); 9773 Pred = ICmpInst::ICMP_SGT; 9774 Changed = true; 9775 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9776 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9777 SCEV::FlagNSW); 9778 Pred = ICmpInst::ICMP_SGT; 9779 Changed = true; 9780 } 9781 break; 9782 case ICmpInst::ICMP_ULE: 9783 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9784 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9785 SCEV::FlagNUW); 9786 Pred = ICmpInst::ICMP_ULT; 9787 Changed = true; 9788 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9789 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9790 Pred = ICmpInst::ICMP_ULT; 9791 Changed = true; 9792 } 9793 break; 9794 case ICmpInst::ICMP_UGE: 9795 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9796 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9797 Pred = ICmpInst::ICMP_UGT; 9798 Changed = true; 9799 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9800 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9801 SCEV::FlagNUW); 9802 Pred = ICmpInst::ICMP_UGT; 9803 Changed = true; 9804 } 9805 break; 9806 default: 9807 break; 9808 } 9809 9810 // TODO: More simplifications are possible here. 9811 9812 // Recursively simplify until we either hit a recursion limit or nothing 9813 // changes. 9814 if (Changed) 9815 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9816 9817 return Changed; 9818 } 9819 9820 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9821 return getSignedRangeMax(S).isNegative(); 9822 } 9823 9824 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9825 return getSignedRangeMin(S).isStrictlyPositive(); 9826 } 9827 9828 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9829 return !getSignedRangeMin(S).isNegative(); 9830 } 9831 9832 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9833 return !getSignedRangeMax(S).isStrictlyPositive(); 9834 } 9835 9836 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9837 return getUnsignedRangeMin(S) != 0; 9838 } 9839 9840 std::pair<const SCEV *, const SCEV *> 9841 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9842 // Compute SCEV on entry of loop L. 9843 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9844 if (Start == getCouldNotCompute()) 9845 return { Start, Start }; 9846 // Compute post increment SCEV for loop L. 9847 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9848 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9849 return { Start, PostInc }; 9850 } 9851 9852 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9853 const SCEV *LHS, const SCEV *RHS) { 9854 // First collect all loops. 9855 SmallPtrSet<const Loop *, 8> LoopsUsed; 9856 getUsedLoops(LHS, LoopsUsed); 9857 getUsedLoops(RHS, LoopsUsed); 9858 9859 if (LoopsUsed.empty()) 9860 return false; 9861 9862 // Domination relationship must be a linear order on collected loops. 9863 #ifndef NDEBUG 9864 for (auto *L1 : LoopsUsed) 9865 for (auto *L2 : LoopsUsed) 9866 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9867 DT.dominates(L2->getHeader(), L1->getHeader())) && 9868 "Domination relationship is not a linear order"); 9869 #endif 9870 9871 const Loop *MDL = 9872 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9873 [&](const Loop *L1, const Loop *L2) { 9874 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9875 }); 9876 9877 // Get init and post increment value for LHS. 9878 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9879 // if LHS contains unknown non-invariant SCEV then bail out. 9880 if (SplitLHS.first == getCouldNotCompute()) 9881 return false; 9882 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9883 // Get init and post increment value for RHS. 9884 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9885 // if RHS contains unknown non-invariant SCEV then bail out. 9886 if (SplitRHS.first == getCouldNotCompute()) 9887 return false; 9888 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9889 // It is possible that init SCEV contains an invariant load but it does 9890 // not dominate MDL and is not available at MDL loop entry, so we should 9891 // check it here. 9892 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9893 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9894 return false; 9895 9896 // It seems backedge guard check is faster than entry one so in some cases 9897 // it can speed up whole estimation by short circuit 9898 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9899 SplitRHS.second) && 9900 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9901 } 9902 9903 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9904 const SCEV *LHS, const SCEV *RHS) { 9905 // Canonicalize the inputs first. 9906 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9907 9908 if (isKnownViaInduction(Pred, LHS, RHS)) 9909 return true; 9910 9911 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9912 return true; 9913 9914 // Otherwise see what can be done with some simple reasoning. 9915 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9916 } 9917 9918 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9919 const SCEV *LHS, 9920 const SCEV *RHS) { 9921 if (isKnownPredicate(Pred, LHS, RHS)) 9922 return true; 9923 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9924 return false; 9925 return None; 9926 } 9927 9928 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9929 const SCEV *LHS, const SCEV *RHS, 9930 const Instruction *CtxI) { 9931 // TODO: Analyze guards and assumes from Context's block. 9932 return isKnownPredicate(Pred, LHS, RHS) || 9933 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 9934 } 9935 9936 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 9937 const SCEV *LHS, 9938 const SCEV *RHS, 9939 const Instruction *CtxI) { 9940 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9941 if (KnownWithoutContext) 9942 return KnownWithoutContext; 9943 9944 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 9945 return true; 9946 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 9947 ICmpInst::getInversePredicate(Pred), 9948 LHS, RHS)) 9949 return false; 9950 return None; 9951 } 9952 9953 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9954 const SCEVAddRecExpr *LHS, 9955 const SCEV *RHS) { 9956 const Loop *L = LHS->getLoop(); 9957 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9958 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9959 } 9960 9961 Optional<ScalarEvolution::MonotonicPredicateType> 9962 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9963 ICmpInst::Predicate Pred) { 9964 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9965 9966 #ifndef NDEBUG 9967 // Verify an invariant: inverting the predicate should turn a monotonically 9968 // increasing change to a monotonically decreasing one, and vice versa. 9969 if (Result) { 9970 auto ResultSwapped = 9971 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9972 9973 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9974 assert(ResultSwapped.getValue() != Result.getValue() && 9975 "monotonicity should flip as we flip the predicate"); 9976 } 9977 #endif 9978 9979 return Result; 9980 } 9981 9982 Optional<ScalarEvolution::MonotonicPredicateType> 9983 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9984 ICmpInst::Predicate Pred) { 9985 // A zero step value for LHS means the induction variable is essentially a 9986 // loop invariant value. We don't really depend on the predicate actually 9987 // flipping from false to true (for increasing predicates, and the other way 9988 // around for decreasing predicates), all we care about is that *if* the 9989 // predicate changes then it only changes from false to true. 9990 // 9991 // A zero step value in itself is not very useful, but there may be places 9992 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9993 // as general as possible. 9994 9995 // Only handle LE/LT/GE/GT predicates. 9996 if (!ICmpInst::isRelational(Pred)) 9997 return None; 9998 9999 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10000 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10001 "Should be greater or less!"); 10002 10003 // Check that AR does not wrap. 10004 if (ICmpInst::isUnsigned(Pred)) { 10005 if (!LHS->hasNoUnsignedWrap()) 10006 return None; 10007 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10008 } else { 10009 assert(ICmpInst::isSigned(Pred) && 10010 "Relational predicate is either signed or unsigned!"); 10011 if (!LHS->hasNoSignedWrap()) 10012 return None; 10013 10014 const SCEV *Step = LHS->getStepRecurrence(*this); 10015 10016 if (isKnownNonNegative(Step)) 10017 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10018 10019 if (isKnownNonPositive(Step)) 10020 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10021 10022 return None; 10023 } 10024 } 10025 10026 Optional<ScalarEvolution::LoopInvariantPredicate> 10027 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10028 const SCEV *LHS, const SCEV *RHS, 10029 const Loop *L) { 10030 10031 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10032 if (!isLoopInvariant(RHS, L)) { 10033 if (!isLoopInvariant(LHS, L)) 10034 return None; 10035 10036 std::swap(LHS, RHS); 10037 Pred = ICmpInst::getSwappedPredicate(Pred); 10038 } 10039 10040 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10041 if (!ArLHS || ArLHS->getLoop() != L) 10042 return None; 10043 10044 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10045 if (!MonotonicType) 10046 return None; 10047 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10048 // true as the loop iterates, and the backedge is control dependent on 10049 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10050 // 10051 // * if the predicate was false in the first iteration then the predicate 10052 // is never evaluated again, since the loop exits without taking the 10053 // backedge. 10054 // * if the predicate was true in the first iteration then it will 10055 // continue to be true for all future iterations since it is 10056 // monotonically increasing. 10057 // 10058 // For both the above possibilities, we can replace the loop varying 10059 // predicate with its value on the first iteration of the loop (which is 10060 // loop invariant). 10061 // 10062 // A similar reasoning applies for a monotonically decreasing predicate, by 10063 // replacing true with false and false with true in the above two bullets. 10064 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10065 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10066 10067 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10068 return None; 10069 10070 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10071 } 10072 10073 Optional<ScalarEvolution::LoopInvariantPredicate> 10074 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10075 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10076 const Instruction *CtxI, const SCEV *MaxIter) { 10077 // Try to prove the following set of facts: 10078 // - The predicate is monotonic in the iteration space. 10079 // - If the check does not fail on the 1st iteration: 10080 // - No overflow will happen during first MaxIter iterations; 10081 // - It will not fail on the MaxIter'th iteration. 10082 // If the check does fail on the 1st iteration, we leave the loop and no 10083 // other checks matter. 10084 10085 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10086 if (!isLoopInvariant(RHS, L)) { 10087 if (!isLoopInvariant(LHS, L)) 10088 return None; 10089 10090 std::swap(LHS, RHS); 10091 Pred = ICmpInst::getSwappedPredicate(Pred); 10092 } 10093 10094 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10095 if (!AR || AR->getLoop() != L) 10096 return None; 10097 10098 // The predicate must be relational (i.e. <, <=, >=, >). 10099 if (!ICmpInst::isRelational(Pred)) 10100 return None; 10101 10102 // TODO: Support steps other than +/- 1. 10103 const SCEV *Step = AR->getStepRecurrence(*this); 10104 auto *One = getOne(Step->getType()); 10105 auto *MinusOne = getNegativeSCEV(One); 10106 if (Step != One && Step != MinusOne) 10107 return None; 10108 10109 // Type mismatch here means that MaxIter is potentially larger than max 10110 // unsigned value in start type, which mean we cannot prove no wrap for the 10111 // indvar. 10112 if (AR->getType() != MaxIter->getType()) 10113 return None; 10114 10115 // Value of IV on suggested last iteration. 10116 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10117 // Does it still meet the requirement? 10118 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10119 return None; 10120 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10121 // not exceed max unsigned value of this type), this effectively proves 10122 // that there is no wrap during the iteration. To prove that there is no 10123 // signed/unsigned wrap, we need to check that 10124 // Start <= Last for step = 1 or Start >= Last for step = -1. 10125 ICmpInst::Predicate NoOverflowPred = 10126 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10127 if (Step == MinusOne) 10128 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10129 const SCEV *Start = AR->getStart(); 10130 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10131 return None; 10132 10133 // Everything is fine. 10134 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10135 } 10136 10137 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10138 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10139 if (HasSameValue(LHS, RHS)) 10140 return ICmpInst::isTrueWhenEqual(Pred); 10141 10142 // This code is split out from isKnownPredicate because it is called from 10143 // within isLoopEntryGuardedByCond. 10144 10145 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10146 const ConstantRange &RangeRHS) { 10147 return RangeLHS.icmp(Pred, RangeRHS); 10148 }; 10149 10150 // The check at the top of the function catches the case where the values are 10151 // known to be equal. 10152 if (Pred == CmpInst::ICMP_EQ) 10153 return false; 10154 10155 if (Pred == CmpInst::ICMP_NE) { 10156 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10157 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10158 return true; 10159 auto *Diff = getMinusSCEV(LHS, RHS); 10160 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10161 } 10162 10163 if (CmpInst::isSigned(Pred)) 10164 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10165 10166 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10167 } 10168 10169 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10170 const SCEV *LHS, 10171 const SCEV *RHS) { 10172 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10173 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10174 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10175 // OutC1 and OutC2. 10176 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10177 APInt &OutC1, APInt &OutC2, 10178 SCEV::NoWrapFlags ExpectedFlags) { 10179 const SCEV *XNonConstOp, *XConstOp; 10180 const SCEV *YNonConstOp, *YConstOp; 10181 SCEV::NoWrapFlags XFlagsPresent; 10182 SCEV::NoWrapFlags YFlagsPresent; 10183 10184 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10185 XConstOp = getZero(X->getType()); 10186 XNonConstOp = X; 10187 XFlagsPresent = ExpectedFlags; 10188 } 10189 if (!isa<SCEVConstant>(XConstOp) || 10190 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10191 return false; 10192 10193 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10194 YConstOp = getZero(Y->getType()); 10195 YNonConstOp = Y; 10196 YFlagsPresent = ExpectedFlags; 10197 } 10198 10199 if (!isa<SCEVConstant>(YConstOp) || 10200 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10201 return false; 10202 10203 if (YNonConstOp != XNonConstOp) 10204 return false; 10205 10206 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10207 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10208 10209 return true; 10210 }; 10211 10212 APInt C1; 10213 APInt C2; 10214 10215 switch (Pred) { 10216 default: 10217 break; 10218 10219 case ICmpInst::ICMP_SGE: 10220 std::swap(LHS, RHS); 10221 LLVM_FALLTHROUGH; 10222 case ICmpInst::ICMP_SLE: 10223 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10224 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10225 return true; 10226 10227 break; 10228 10229 case ICmpInst::ICMP_SGT: 10230 std::swap(LHS, RHS); 10231 LLVM_FALLTHROUGH; 10232 case ICmpInst::ICMP_SLT: 10233 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10234 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10235 return true; 10236 10237 break; 10238 10239 case ICmpInst::ICMP_UGE: 10240 std::swap(LHS, RHS); 10241 LLVM_FALLTHROUGH; 10242 case ICmpInst::ICMP_ULE: 10243 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10244 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10245 return true; 10246 10247 break; 10248 10249 case ICmpInst::ICMP_UGT: 10250 std::swap(LHS, RHS); 10251 LLVM_FALLTHROUGH; 10252 case ICmpInst::ICMP_ULT: 10253 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10254 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10255 return true; 10256 break; 10257 } 10258 10259 return false; 10260 } 10261 10262 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10263 const SCEV *LHS, 10264 const SCEV *RHS) { 10265 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10266 return false; 10267 10268 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10269 // the stack can result in exponential time complexity. 10270 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10271 10272 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10273 // 10274 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10275 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10276 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10277 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10278 // use isKnownPredicate later if needed. 10279 return isKnownNonNegative(RHS) && 10280 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10281 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10282 } 10283 10284 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10285 ICmpInst::Predicate Pred, 10286 const SCEV *LHS, const SCEV *RHS) { 10287 // No need to even try if we know the module has no guards. 10288 if (!HasGuards) 10289 return false; 10290 10291 return any_of(*BB, [&](const Instruction &I) { 10292 using namespace llvm::PatternMatch; 10293 10294 Value *Condition; 10295 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10296 m_Value(Condition))) && 10297 isImpliedCond(Pred, LHS, RHS, Condition, false); 10298 }); 10299 } 10300 10301 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10302 /// protected by a conditional between LHS and RHS. This is used to 10303 /// to eliminate casts. 10304 bool 10305 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10306 ICmpInst::Predicate Pred, 10307 const SCEV *LHS, const SCEV *RHS) { 10308 // Interpret a null as meaning no loop, where there is obviously no guard 10309 // (interprocedural conditions notwithstanding). 10310 if (!L) return true; 10311 10312 if (VerifyIR) 10313 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10314 "This cannot be done on broken IR!"); 10315 10316 10317 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10318 return true; 10319 10320 BasicBlock *Latch = L->getLoopLatch(); 10321 if (!Latch) 10322 return false; 10323 10324 BranchInst *LoopContinuePredicate = 10325 dyn_cast<BranchInst>(Latch->getTerminator()); 10326 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10327 isImpliedCond(Pred, LHS, RHS, 10328 LoopContinuePredicate->getCondition(), 10329 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10330 return true; 10331 10332 // We don't want more than one activation of the following loops on the stack 10333 // -- that can lead to O(n!) time complexity. 10334 if (WalkingBEDominatingConds) 10335 return false; 10336 10337 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10338 10339 // See if we can exploit a trip count to prove the predicate. 10340 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10341 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10342 if (LatchBECount != getCouldNotCompute()) { 10343 // We know that Latch branches back to the loop header exactly 10344 // LatchBECount times. This means the backdege condition at Latch is 10345 // equivalent to "{0,+,1} u< LatchBECount". 10346 Type *Ty = LatchBECount->getType(); 10347 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10348 const SCEV *LoopCounter = 10349 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10350 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10351 LatchBECount)) 10352 return true; 10353 } 10354 10355 // Check conditions due to any @llvm.assume intrinsics. 10356 for (auto &AssumeVH : AC.assumptions()) { 10357 if (!AssumeVH) 10358 continue; 10359 auto *CI = cast<CallInst>(AssumeVH); 10360 if (!DT.dominates(CI, Latch->getTerminator())) 10361 continue; 10362 10363 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10364 return true; 10365 } 10366 10367 // If the loop is not reachable from the entry block, we risk running into an 10368 // infinite loop as we walk up into the dom tree. These loops do not matter 10369 // anyway, so we just return a conservative answer when we see them. 10370 if (!DT.isReachableFromEntry(L->getHeader())) 10371 return false; 10372 10373 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10374 return true; 10375 10376 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10377 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10378 assert(DTN && "should reach the loop header before reaching the root!"); 10379 10380 BasicBlock *BB = DTN->getBlock(); 10381 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10382 return true; 10383 10384 BasicBlock *PBB = BB->getSinglePredecessor(); 10385 if (!PBB) 10386 continue; 10387 10388 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10389 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10390 continue; 10391 10392 Value *Condition = ContinuePredicate->getCondition(); 10393 10394 // If we have an edge `E` within the loop body that dominates the only 10395 // latch, the condition guarding `E` also guards the backedge. This 10396 // reasoning works only for loops with a single latch. 10397 10398 BasicBlockEdge DominatingEdge(PBB, BB); 10399 if (DominatingEdge.isSingleEdge()) { 10400 // We're constructively (and conservatively) enumerating edges within the 10401 // loop body that dominate the latch. The dominator tree better agree 10402 // with us on this: 10403 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10404 10405 if (isImpliedCond(Pred, LHS, RHS, Condition, 10406 BB != ContinuePredicate->getSuccessor(0))) 10407 return true; 10408 } 10409 } 10410 10411 return false; 10412 } 10413 10414 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10415 ICmpInst::Predicate Pred, 10416 const SCEV *LHS, 10417 const SCEV *RHS) { 10418 if (VerifyIR) 10419 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10420 "This cannot be done on broken IR!"); 10421 10422 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10423 // the facts (a >= b && a != b) separately. A typical situation is when the 10424 // non-strict comparison is known from ranges and non-equality is known from 10425 // dominating predicates. If we are proving strict comparison, we always try 10426 // to prove non-equality and non-strict comparison separately. 10427 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10428 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10429 bool ProvedNonStrictComparison = false; 10430 bool ProvedNonEquality = false; 10431 10432 auto SplitAndProve = 10433 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10434 if (!ProvedNonStrictComparison) 10435 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10436 if (!ProvedNonEquality) 10437 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10438 if (ProvedNonStrictComparison && ProvedNonEquality) 10439 return true; 10440 return false; 10441 }; 10442 10443 if (ProvingStrictComparison) { 10444 auto ProofFn = [&](ICmpInst::Predicate P) { 10445 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10446 }; 10447 if (SplitAndProve(ProofFn)) 10448 return true; 10449 } 10450 10451 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10452 auto ProveViaGuard = [&](const BasicBlock *Block) { 10453 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10454 return true; 10455 if (ProvingStrictComparison) { 10456 auto ProofFn = [&](ICmpInst::Predicate P) { 10457 return isImpliedViaGuard(Block, P, LHS, RHS); 10458 }; 10459 if (SplitAndProve(ProofFn)) 10460 return true; 10461 } 10462 return false; 10463 }; 10464 10465 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10466 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10467 const Instruction *CtxI = &BB->front(); 10468 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10469 return true; 10470 if (ProvingStrictComparison) { 10471 auto ProofFn = [&](ICmpInst::Predicate P) { 10472 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10473 }; 10474 if (SplitAndProve(ProofFn)) 10475 return true; 10476 } 10477 return false; 10478 }; 10479 10480 // Starting at the block's predecessor, climb up the predecessor chain, as long 10481 // as there are predecessors that can be found that have unique successors 10482 // leading to the original block. 10483 const Loop *ContainingLoop = LI.getLoopFor(BB); 10484 const BasicBlock *PredBB; 10485 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10486 PredBB = ContainingLoop->getLoopPredecessor(); 10487 else 10488 PredBB = BB->getSinglePredecessor(); 10489 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10490 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10491 if (ProveViaGuard(Pair.first)) 10492 return true; 10493 10494 const BranchInst *LoopEntryPredicate = 10495 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10496 if (!LoopEntryPredicate || 10497 LoopEntryPredicate->isUnconditional()) 10498 continue; 10499 10500 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10501 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10502 return true; 10503 } 10504 10505 // Check conditions due to any @llvm.assume intrinsics. 10506 for (auto &AssumeVH : AC.assumptions()) { 10507 if (!AssumeVH) 10508 continue; 10509 auto *CI = cast<CallInst>(AssumeVH); 10510 if (!DT.dominates(CI, BB)) 10511 continue; 10512 10513 if (ProveViaCond(CI->getArgOperand(0), false)) 10514 return true; 10515 } 10516 10517 return false; 10518 } 10519 10520 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10521 ICmpInst::Predicate Pred, 10522 const SCEV *LHS, 10523 const SCEV *RHS) { 10524 // Interpret a null as meaning no loop, where there is obviously no guard 10525 // (interprocedural conditions notwithstanding). 10526 if (!L) 10527 return false; 10528 10529 // Both LHS and RHS must be available at loop entry. 10530 assert(isAvailableAtLoopEntry(LHS, L) && 10531 "LHS is not available at Loop Entry"); 10532 assert(isAvailableAtLoopEntry(RHS, L) && 10533 "RHS is not available at Loop Entry"); 10534 10535 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10536 return true; 10537 10538 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10539 } 10540 10541 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10542 const SCEV *RHS, 10543 const Value *FoundCondValue, bool Inverse, 10544 const Instruction *CtxI) { 10545 // False conditions implies anything. Do not bother analyzing it further. 10546 if (FoundCondValue == 10547 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10548 return true; 10549 10550 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10551 return false; 10552 10553 auto ClearOnExit = 10554 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10555 10556 // Recursively handle And and Or conditions. 10557 const Value *Op0, *Op1; 10558 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10559 if (!Inverse) 10560 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10561 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10562 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10563 if (Inverse) 10564 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10565 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10566 } 10567 10568 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10569 if (!ICI) return false; 10570 10571 // Now that we found a conditional branch that dominates the loop or controls 10572 // the loop latch. Check to see if it is the comparison we are looking for. 10573 ICmpInst::Predicate FoundPred; 10574 if (Inverse) 10575 FoundPred = ICI->getInversePredicate(); 10576 else 10577 FoundPred = ICI->getPredicate(); 10578 10579 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10580 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10581 10582 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10583 } 10584 10585 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10586 const SCEV *RHS, 10587 ICmpInst::Predicate FoundPred, 10588 const SCEV *FoundLHS, const SCEV *FoundRHS, 10589 const Instruction *CtxI) { 10590 // Balance the types. 10591 if (getTypeSizeInBits(LHS->getType()) < 10592 getTypeSizeInBits(FoundLHS->getType())) { 10593 // For unsigned and equality predicates, try to prove that both found 10594 // operands fit into narrow unsigned range. If so, try to prove facts in 10595 // narrow types. 10596 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10597 auto *NarrowType = LHS->getType(); 10598 auto *WideType = FoundLHS->getType(); 10599 auto BitWidth = getTypeSizeInBits(NarrowType); 10600 const SCEV *MaxValue = getZeroExtendExpr( 10601 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10602 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10603 MaxValue) && 10604 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10605 MaxValue)) { 10606 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10607 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10608 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10609 TruncFoundRHS, CtxI)) 10610 return true; 10611 } 10612 } 10613 10614 if (LHS->getType()->isPointerTy()) 10615 return false; 10616 if (CmpInst::isSigned(Pred)) { 10617 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10618 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10619 } else { 10620 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10621 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10622 } 10623 } else if (getTypeSizeInBits(LHS->getType()) > 10624 getTypeSizeInBits(FoundLHS->getType())) { 10625 if (FoundLHS->getType()->isPointerTy()) 10626 return false; 10627 if (CmpInst::isSigned(FoundPred)) { 10628 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10629 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10630 } else { 10631 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10632 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10633 } 10634 } 10635 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10636 FoundRHS, CtxI); 10637 } 10638 10639 bool ScalarEvolution::isImpliedCondBalancedTypes( 10640 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10641 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10642 const Instruction *CtxI) { 10643 assert(getTypeSizeInBits(LHS->getType()) == 10644 getTypeSizeInBits(FoundLHS->getType()) && 10645 "Types should be balanced!"); 10646 // Canonicalize the query to match the way instcombine will have 10647 // canonicalized the comparison. 10648 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10649 if (LHS == RHS) 10650 return CmpInst::isTrueWhenEqual(Pred); 10651 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10652 if (FoundLHS == FoundRHS) 10653 return CmpInst::isFalseWhenEqual(FoundPred); 10654 10655 // Check to see if we can make the LHS or RHS match. 10656 if (LHS == FoundRHS || RHS == FoundLHS) { 10657 if (isa<SCEVConstant>(RHS)) { 10658 std::swap(FoundLHS, FoundRHS); 10659 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10660 } else { 10661 std::swap(LHS, RHS); 10662 Pred = ICmpInst::getSwappedPredicate(Pred); 10663 } 10664 } 10665 10666 // Check whether the found predicate is the same as the desired predicate. 10667 if (FoundPred == Pred) 10668 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10669 10670 // Check whether swapping the found predicate makes it the same as the 10671 // desired predicate. 10672 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10673 // We can write the implication 10674 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10675 // using one of the following ways: 10676 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10677 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10678 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10679 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10680 // Forms 1. and 2. require swapping the operands of one condition. Don't 10681 // do this if it would break canonical constant/addrec ordering. 10682 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10683 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10684 CtxI); 10685 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10686 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 10687 10688 // There's no clear preference between forms 3. and 4., try both. Avoid 10689 // forming getNotSCEV of pointer values as the resulting subtract is 10690 // not legal. 10691 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 10692 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10693 FoundLHS, FoundRHS, CtxI)) 10694 return true; 10695 10696 if (!FoundLHS->getType()->isPointerTy() && 10697 !FoundRHS->getType()->isPointerTy() && 10698 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10699 getNotSCEV(FoundRHS), CtxI)) 10700 return true; 10701 10702 return false; 10703 } 10704 10705 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 10706 CmpInst::Predicate P2) { 10707 assert(P1 != P2 && "Handled earlier!"); 10708 return CmpInst::isRelational(P2) && 10709 P1 == CmpInst::getFlippedSignednessPredicate(P2); 10710 }; 10711 if (IsSignFlippedPredicate(Pred, FoundPred)) { 10712 // Unsigned comparison is the same as signed comparison when both the 10713 // operands are non-negative or negative. 10714 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 10715 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 10716 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10717 // Create local copies that we can freely swap and canonicalize our 10718 // conditions to "le/lt". 10719 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 10720 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 10721 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 10722 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 10723 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 10724 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 10725 std::swap(CanonicalLHS, CanonicalRHS); 10726 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 10727 } 10728 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 10729 "Must be!"); 10730 assert((ICmpInst::isLT(CanonicalFoundPred) || 10731 ICmpInst::isLE(CanonicalFoundPred)) && 10732 "Must be!"); 10733 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 10734 // Use implication: 10735 // x <u y && y >=s 0 --> x <s y. 10736 // If we can prove the left part, the right part is also proven. 10737 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10738 CanonicalRHS, CanonicalFoundLHS, 10739 CanonicalFoundRHS); 10740 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 10741 // Use implication: 10742 // x <s y && y <s 0 --> x <u y. 10743 // If we can prove the left part, the right part is also proven. 10744 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10745 CanonicalRHS, CanonicalFoundLHS, 10746 CanonicalFoundRHS); 10747 } 10748 10749 // Check if we can make progress by sharpening ranges. 10750 if (FoundPred == ICmpInst::ICMP_NE && 10751 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10752 10753 const SCEVConstant *C = nullptr; 10754 const SCEV *V = nullptr; 10755 10756 if (isa<SCEVConstant>(FoundLHS)) { 10757 C = cast<SCEVConstant>(FoundLHS); 10758 V = FoundRHS; 10759 } else { 10760 C = cast<SCEVConstant>(FoundRHS); 10761 V = FoundLHS; 10762 } 10763 10764 // The guarding predicate tells us that C != V. If the known range 10765 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10766 // range we consider has to correspond to same signedness as the 10767 // predicate we're interested in folding. 10768 10769 APInt Min = ICmpInst::isSigned(Pred) ? 10770 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10771 10772 if (Min == C->getAPInt()) { 10773 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10774 // This is true even if (Min + 1) wraps around -- in case of 10775 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10776 10777 APInt SharperMin = Min + 1; 10778 10779 switch (Pred) { 10780 case ICmpInst::ICMP_SGE: 10781 case ICmpInst::ICMP_UGE: 10782 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10783 // RHS, we're done. 10784 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10785 CtxI)) 10786 return true; 10787 LLVM_FALLTHROUGH; 10788 10789 case ICmpInst::ICMP_SGT: 10790 case ICmpInst::ICMP_UGT: 10791 // We know from the range information that (V `Pred` Min || 10792 // V == Min). We know from the guarding condition that !(V 10793 // == Min). This gives us 10794 // 10795 // V `Pred` Min || V == Min && !(V == Min) 10796 // => V `Pred` Min 10797 // 10798 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10799 10800 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 10801 return true; 10802 break; 10803 10804 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10805 case ICmpInst::ICMP_SLE: 10806 case ICmpInst::ICMP_ULE: 10807 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10808 LHS, V, getConstant(SharperMin), CtxI)) 10809 return true; 10810 LLVM_FALLTHROUGH; 10811 10812 case ICmpInst::ICMP_SLT: 10813 case ICmpInst::ICMP_ULT: 10814 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10815 LHS, V, getConstant(Min), CtxI)) 10816 return true; 10817 break; 10818 10819 default: 10820 // No change 10821 break; 10822 } 10823 } 10824 } 10825 10826 // Check whether the actual condition is beyond sufficient. 10827 if (FoundPred == ICmpInst::ICMP_EQ) 10828 if (ICmpInst::isTrueWhenEqual(Pred)) 10829 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10830 return true; 10831 if (Pred == ICmpInst::ICMP_NE) 10832 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10833 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10834 return true; 10835 10836 // Otherwise assume the worst. 10837 return false; 10838 } 10839 10840 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10841 const SCEV *&L, const SCEV *&R, 10842 SCEV::NoWrapFlags &Flags) { 10843 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10844 if (!AE || AE->getNumOperands() != 2) 10845 return false; 10846 10847 L = AE->getOperand(0); 10848 R = AE->getOperand(1); 10849 Flags = AE->getNoWrapFlags(); 10850 return true; 10851 } 10852 10853 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10854 const SCEV *Less) { 10855 // We avoid subtracting expressions here because this function is usually 10856 // fairly deep in the call stack (i.e. is called many times). 10857 10858 // X - X = 0. 10859 if (More == Less) 10860 return APInt(getTypeSizeInBits(More->getType()), 0); 10861 10862 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10863 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10864 const auto *MAR = cast<SCEVAddRecExpr>(More); 10865 10866 if (LAR->getLoop() != MAR->getLoop()) 10867 return None; 10868 10869 // We look at affine expressions only; not for correctness but to keep 10870 // getStepRecurrence cheap. 10871 if (!LAR->isAffine() || !MAR->isAffine()) 10872 return None; 10873 10874 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10875 return None; 10876 10877 Less = LAR->getStart(); 10878 More = MAR->getStart(); 10879 10880 // fall through 10881 } 10882 10883 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10884 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10885 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10886 return M - L; 10887 } 10888 10889 SCEV::NoWrapFlags Flags; 10890 const SCEV *LLess = nullptr, *RLess = nullptr; 10891 const SCEV *LMore = nullptr, *RMore = nullptr; 10892 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10893 // Compare (X + C1) vs X. 10894 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10895 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10896 if (RLess == More) 10897 return -(C1->getAPInt()); 10898 10899 // Compare X vs (X + C2). 10900 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10901 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10902 if (RMore == Less) 10903 return C2->getAPInt(); 10904 10905 // Compare (X + C1) vs (X + C2). 10906 if (C1 && C2 && RLess == RMore) 10907 return C2->getAPInt() - C1->getAPInt(); 10908 10909 return None; 10910 } 10911 10912 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10913 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10914 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 10915 // Try to recognize the following pattern: 10916 // 10917 // FoundRHS = ... 10918 // ... 10919 // loop: 10920 // FoundLHS = {Start,+,W} 10921 // context_bb: // Basic block from the same loop 10922 // known(Pred, FoundLHS, FoundRHS) 10923 // 10924 // If some predicate is known in the context of a loop, it is also known on 10925 // each iteration of this loop, including the first iteration. Therefore, in 10926 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10927 // prove the original pred using this fact. 10928 if (!CtxI) 10929 return false; 10930 const BasicBlock *ContextBB = CtxI->getParent(); 10931 // Make sure AR varies in the context block. 10932 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10933 const Loop *L = AR->getLoop(); 10934 // Make sure that context belongs to the loop and executes on 1st iteration 10935 // (if it ever executes at all). 10936 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10937 return false; 10938 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10939 return false; 10940 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10941 } 10942 10943 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10944 const Loop *L = AR->getLoop(); 10945 // Make sure that context belongs to the loop and executes on 1st iteration 10946 // (if it ever executes at all). 10947 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10948 return false; 10949 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10950 return false; 10951 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10952 } 10953 10954 return false; 10955 } 10956 10957 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10958 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10959 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10960 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10961 return false; 10962 10963 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10964 if (!AddRecLHS) 10965 return false; 10966 10967 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10968 if (!AddRecFoundLHS) 10969 return false; 10970 10971 // We'd like to let SCEV reason about control dependencies, so we constrain 10972 // both the inequalities to be about add recurrences on the same loop. This 10973 // way we can use isLoopEntryGuardedByCond later. 10974 10975 const Loop *L = AddRecFoundLHS->getLoop(); 10976 if (L != AddRecLHS->getLoop()) 10977 return false; 10978 10979 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10980 // 10981 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10982 // ... (2) 10983 // 10984 // Informal proof for (2), assuming (1) [*]: 10985 // 10986 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10987 // 10988 // Then 10989 // 10990 // FoundLHS s< FoundRHS s< INT_MIN - C 10991 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10992 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10993 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10994 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10995 // <=> FoundLHS + C s< FoundRHS + C 10996 // 10997 // [*]: (1) can be proved by ruling out overflow. 10998 // 10999 // [**]: This can be proved by analyzing all the four possibilities: 11000 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 11001 // (A s>= 0, B s>= 0). 11002 // 11003 // Note: 11004 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 11005 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 11006 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 11007 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 11008 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 11009 // C)". 11010 11011 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11012 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11013 if (!LDiff || !RDiff || *LDiff != *RDiff) 11014 return false; 11015 11016 if (LDiff->isMinValue()) 11017 return true; 11018 11019 APInt FoundRHSLimit; 11020 11021 if (Pred == CmpInst::ICMP_ULT) { 11022 FoundRHSLimit = -(*RDiff); 11023 } else { 11024 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11025 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11026 } 11027 11028 // Try to prove (1) or (2), as needed. 11029 return isAvailableAtLoopEntry(FoundRHS, L) && 11030 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11031 getConstant(FoundRHSLimit)); 11032 } 11033 11034 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11035 const SCEV *LHS, const SCEV *RHS, 11036 const SCEV *FoundLHS, 11037 const SCEV *FoundRHS, unsigned Depth) { 11038 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11039 11040 auto ClearOnExit = make_scope_exit([&]() { 11041 if (LPhi) { 11042 bool Erased = PendingMerges.erase(LPhi); 11043 assert(Erased && "Failed to erase LPhi!"); 11044 (void)Erased; 11045 } 11046 if (RPhi) { 11047 bool Erased = PendingMerges.erase(RPhi); 11048 assert(Erased && "Failed to erase RPhi!"); 11049 (void)Erased; 11050 } 11051 }); 11052 11053 // Find respective Phis and check that they are not being pending. 11054 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11055 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11056 if (!PendingMerges.insert(Phi).second) 11057 return false; 11058 LPhi = Phi; 11059 } 11060 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11061 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11062 // If we detect a loop of Phi nodes being processed by this method, for 11063 // example: 11064 // 11065 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11066 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11067 // 11068 // we don't want to deal with a case that complex, so return conservative 11069 // answer false. 11070 if (!PendingMerges.insert(Phi).second) 11071 return false; 11072 RPhi = Phi; 11073 } 11074 11075 // If none of LHS, RHS is a Phi, nothing to do here. 11076 if (!LPhi && !RPhi) 11077 return false; 11078 11079 // If there is a SCEVUnknown Phi we are interested in, make it left. 11080 if (!LPhi) { 11081 std::swap(LHS, RHS); 11082 std::swap(FoundLHS, FoundRHS); 11083 std::swap(LPhi, RPhi); 11084 Pred = ICmpInst::getSwappedPredicate(Pred); 11085 } 11086 11087 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11088 const BasicBlock *LBB = LPhi->getParent(); 11089 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11090 11091 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11092 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11093 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11094 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11095 }; 11096 11097 if (RPhi && RPhi->getParent() == LBB) { 11098 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11099 // If we compare two Phis from the same block, and for each entry block 11100 // the predicate is true for incoming values from this block, then the 11101 // predicate is also true for the Phis. 11102 for (const BasicBlock *IncBB : predecessors(LBB)) { 11103 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11104 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11105 if (!ProvedEasily(L, R)) 11106 return false; 11107 } 11108 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11109 // Case two: RHS is also a Phi from the same basic block, and it is an 11110 // AddRec. It means that there is a loop which has both AddRec and Unknown 11111 // PHIs, for it we can compare incoming values of AddRec from above the loop 11112 // and latch with their respective incoming values of LPhi. 11113 // TODO: Generalize to handle loops with many inputs in a header. 11114 if (LPhi->getNumIncomingValues() != 2) return false; 11115 11116 auto *RLoop = RAR->getLoop(); 11117 auto *Predecessor = RLoop->getLoopPredecessor(); 11118 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11119 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11120 if (!ProvedEasily(L1, RAR->getStart())) 11121 return false; 11122 auto *Latch = RLoop->getLoopLatch(); 11123 assert(Latch && "Loop with AddRec with no latch?"); 11124 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11125 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11126 return false; 11127 } else { 11128 // In all other cases go over inputs of LHS and compare each of them to RHS, 11129 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11130 // At this point RHS is either a non-Phi, or it is a Phi from some block 11131 // different from LBB. 11132 for (const BasicBlock *IncBB : predecessors(LBB)) { 11133 // Check that RHS is available in this block. 11134 if (!dominates(RHS, IncBB)) 11135 return false; 11136 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11137 // Make sure L does not refer to a value from a potentially previous 11138 // iteration of a loop. 11139 if (!properlyDominates(L, IncBB)) 11140 return false; 11141 if (!ProvedEasily(L, RHS)) 11142 return false; 11143 } 11144 } 11145 return true; 11146 } 11147 11148 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11149 const SCEV *LHS, const SCEV *RHS, 11150 const SCEV *FoundLHS, 11151 const SCEV *FoundRHS, 11152 const Instruction *CtxI) { 11153 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11154 return true; 11155 11156 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11157 return true; 11158 11159 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11160 CtxI)) 11161 return true; 11162 11163 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11164 FoundLHS, FoundRHS); 11165 } 11166 11167 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11168 template <typename MinMaxExprType> 11169 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11170 const SCEV *Candidate) { 11171 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11172 if (!MinMaxExpr) 11173 return false; 11174 11175 return is_contained(MinMaxExpr->operands(), Candidate); 11176 } 11177 11178 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11179 ICmpInst::Predicate Pred, 11180 const SCEV *LHS, const SCEV *RHS) { 11181 // If both sides are affine addrecs for the same loop, with equal 11182 // steps, and we know the recurrences don't wrap, then we only 11183 // need to check the predicate on the starting values. 11184 11185 if (!ICmpInst::isRelational(Pred)) 11186 return false; 11187 11188 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11189 if (!LAR) 11190 return false; 11191 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11192 if (!RAR) 11193 return false; 11194 if (LAR->getLoop() != RAR->getLoop()) 11195 return false; 11196 if (!LAR->isAffine() || !RAR->isAffine()) 11197 return false; 11198 11199 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11200 return false; 11201 11202 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11203 SCEV::FlagNSW : SCEV::FlagNUW; 11204 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11205 return false; 11206 11207 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11208 } 11209 11210 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11211 /// expression? 11212 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11213 ICmpInst::Predicate Pred, 11214 const SCEV *LHS, const SCEV *RHS) { 11215 switch (Pred) { 11216 default: 11217 return false; 11218 11219 case ICmpInst::ICMP_SGE: 11220 std::swap(LHS, RHS); 11221 LLVM_FALLTHROUGH; 11222 case ICmpInst::ICMP_SLE: 11223 return 11224 // min(A, ...) <= A 11225 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11226 // A <= max(A, ...) 11227 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11228 11229 case ICmpInst::ICMP_UGE: 11230 std::swap(LHS, RHS); 11231 LLVM_FALLTHROUGH; 11232 case ICmpInst::ICMP_ULE: 11233 return 11234 // min(A, ...) <= A 11235 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11236 // A <= max(A, ...) 11237 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11238 } 11239 11240 llvm_unreachable("covered switch fell through?!"); 11241 } 11242 11243 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11244 const SCEV *LHS, const SCEV *RHS, 11245 const SCEV *FoundLHS, 11246 const SCEV *FoundRHS, 11247 unsigned Depth) { 11248 assert(getTypeSizeInBits(LHS->getType()) == 11249 getTypeSizeInBits(RHS->getType()) && 11250 "LHS and RHS have different sizes?"); 11251 assert(getTypeSizeInBits(FoundLHS->getType()) == 11252 getTypeSizeInBits(FoundRHS->getType()) && 11253 "FoundLHS and FoundRHS have different sizes?"); 11254 // We want to avoid hurting the compile time with analysis of too big trees. 11255 if (Depth > MaxSCEVOperationsImplicationDepth) 11256 return false; 11257 11258 // We only want to work with GT comparison so far. 11259 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11260 Pred = CmpInst::getSwappedPredicate(Pred); 11261 std::swap(LHS, RHS); 11262 std::swap(FoundLHS, FoundRHS); 11263 } 11264 11265 // For unsigned, try to reduce it to corresponding signed comparison. 11266 if (Pred == ICmpInst::ICMP_UGT) 11267 // We can replace unsigned predicate with its signed counterpart if all 11268 // involved values are non-negative. 11269 // TODO: We could have better support for unsigned. 11270 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11271 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11272 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11273 // use this fact to prove that LHS and RHS are non-negative. 11274 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11275 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11276 FoundRHS) && 11277 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11278 FoundRHS)) 11279 Pred = ICmpInst::ICMP_SGT; 11280 } 11281 11282 if (Pred != ICmpInst::ICMP_SGT) 11283 return false; 11284 11285 auto GetOpFromSExt = [&](const SCEV *S) { 11286 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11287 return Ext->getOperand(); 11288 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11289 // the constant in some cases. 11290 return S; 11291 }; 11292 11293 // Acquire values from extensions. 11294 auto *OrigLHS = LHS; 11295 auto *OrigFoundLHS = FoundLHS; 11296 LHS = GetOpFromSExt(LHS); 11297 FoundLHS = GetOpFromSExt(FoundLHS); 11298 11299 // Is the SGT predicate can be proved trivially or using the found context. 11300 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11301 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11302 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11303 FoundRHS, Depth + 1); 11304 }; 11305 11306 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11307 // We want to avoid creation of any new non-constant SCEV. Since we are 11308 // going to compare the operands to RHS, we should be certain that we don't 11309 // need any size extensions for this. So let's decline all cases when the 11310 // sizes of types of LHS and RHS do not match. 11311 // TODO: Maybe try to get RHS from sext to catch more cases? 11312 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11313 return false; 11314 11315 // Should not overflow. 11316 if (!LHSAddExpr->hasNoSignedWrap()) 11317 return false; 11318 11319 auto *LL = LHSAddExpr->getOperand(0); 11320 auto *LR = LHSAddExpr->getOperand(1); 11321 auto *MinusOne = getMinusOne(RHS->getType()); 11322 11323 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11324 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11325 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11326 }; 11327 // Try to prove the following rule: 11328 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11329 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11330 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11331 return true; 11332 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11333 Value *LL, *LR; 11334 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11335 11336 using namespace llvm::PatternMatch; 11337 11338 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11339 // Rules for division. 11340 // We are going to perform some comparisons with Denominator and its 11341 // derivative expressions. In general case, creating a SCEV for it may 11342 // lead to a complex analysis of the entire graph, and in particular it 11343 // can request trip count recalculation for the same loop. This would 11344 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11345 // this, we only want to create SCEVs that are constants in this section. 11346 // So we bail if Denominator is not a constant. 11347 if (!isa<ConstantInt>(LR)) 11348 return false; 11349 11350 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11351 11352 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11353 // then a SCEV for the numerator already exists and matches with FoundLHS. 11354 auto *Numerator = getExistingSCEV(LL); 11355 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11356 return false; 11357 11358 // Make sure that the numerator matches with FoundLHS and the denominator 11359 // is positive. 11360 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11361 return false; 11362 11363 auto *DTy = Denominator->getType(); 11364 auto *FRHSTy = FoundRHS->getType(); 11365 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11366 // One of types is a pointer and another one is not. We cannot extend 11367 // them properly to a wider type, so let us just reject this case. 11368 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11369 // to avoid this check. 11370 return false; 11371 11372 // Given that: 11373 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11374 auto *WTy = getWiderType(DTy, FRHSTy); 11375 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11376 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11377 11378 // Try to prove the following rule: 11379 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11380 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11381 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11382 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11383 if (isKnownNonPositive(RHS) && 11384 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11385 return true; 11386 11387 // Try to prove the following rule: 11388 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11389 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11390 // If we divide it by Denominator > 2, then: 11391 // 1. If FoundLHS is negative, then the result is 0. 11392 // 2. If FoundLHS is non-negative, then the result is non-negative. 11393 // Anyways, the result is non-negative. 11394 auto *MinusOne = getMinusOne(WTy); 11395 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11396 if (isKnownNegative(RHS) && 11397 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11398 return true; 11399 } 11400 } 11401 11402 // If our expression contained SCEVUnknown Phis, and we split it down and now 11403 // need to prove something for them, try to prove the predicate for every 11404 // possible incoming values of those Phis. 11405 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11406 return true; 11407 11408 return false; 11409 } 11410 11411 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11412 const SCEV *LHS, const SCEV *RHS) { 11413 // zext x u<= sext x, sext x s<= zext x 11414 switch (Pred) { 11415 case ICmpInst::ICMP_SGE: 11416 std::swap(LHS, RHS); 11417 LLVM_FALLTHROUGH; 11418 case ICmpInst::ICMP_SLE: { 11419 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11420 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11421 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11422 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11423 return true; 11424 break; 11425 } 11426 case ICmpInst::ICMP_UGE: 11427 std::swap(LHS, RHS); 11428 LLVM_FALLTHROUGH; 11429 case ICmpInst::ICMP_ULE: { 11430 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11431 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11432 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11433 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11434 return true; 11435 break; 11436 } 11437 default: 11438 break; 11439 }; 11440 return false; 11441 } 11442 11443 bool 11444 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11445 const SCEV *LHS, const SCEV *RHS) { 11446 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11447 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11448 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11449 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11450 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11451 } 11452 11453 bool 11454 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11455 const SCEV *LHS, const SCEV *RHS, 11456 const SCEV *FoundLHS, 11457 const SCEV *FoundRHS) { 11458 switch (Pred) { 11459 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11460 case ICmpInst::ICMP_EQ: 11461 case ICmpInst::ICMP_NE: 11462 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11463 return true; 11464 break; 11465 case ICmpInst::ICMP_SLT: 11466 case ICmpInst::ICMP_SLE: 11467 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11468 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11469 return true; 11470 break; 11471 case ICmpInst::ICMP_SGT: 11472 case ICmpInst::ICMP_SGE: 11473 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11474 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11475 return true; 11476 break; 11477 case ICmpInst::ICMP_ULT: 11478 case ICmpInst::ICMP_ULE: 11479 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11480 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11481 return true; 11482 break; 11483 case ICmpInst::ICMP_UGT: 11484 case ICmpInst::ICMP_UGE: 11485 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11486 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11487 return true; 11488 break; 11489 } 11490 11491 // Maybe it can be proved via operations? 11492 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11493 return true; 11494 11495 return false; 11496 } 11497 11498 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11499 const SCEV *LHS, 11500 const SCEV *RHS, 11501 const SCEV *FoundLHS, 11502 const SCEV *FoundRHS) { 11503 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11504 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11505 // reduce the compile time impact of this optimization. 11506 return false; 11507 11508 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11509 if (!Addend) 11510 return false; 11511 11512 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11513 11514 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11515 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11516 ConstantRange FoundLHSRange = 11517 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11518 11519 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11520 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11521 11522 // We can also compute the range of values for `LHS` that satisfy the 11523 // consequent, "`LHS` `Pred` `RHS`": 11524 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11525 // The antecedent implies the consequent if every value of `LHS` that 11526 // satisfies the antecedent also satisfies the consequent. 11527 return LHSRange.icmp(Pred, ConstRHS); 11528 } 11529 11530 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11531 bool IsSigned) { 11532 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11533 11534 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11535 const SCEV *One = getOne(Stride->getType()); 11536 11537 if (IsSigned) { 11538 APInt MaxRHS = getSignedRangeMax(RHS); 11539 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11540 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11541 11542 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11543 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11544 } 11545 11546 APInt MaxRHS = getUnsignedRangeMax(RHS); 11547 APInt MaxValue = APInt::getMaxValue(BitWidth); 11548 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11549 11550 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11551 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11552 } 11553 11554 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11555 bool IsSigned) { 11556 11557 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11558 const SCEV *One = getOne(Stride->getType()); 11559 11560 if (IsSigned) { 11561 APInt MinRHS = getSignedRangeMin(RHS); 11562 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11563 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11564 11565 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11566 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11567 } 11568 11569 APInt MinRHS = getUnsignedRangeMin(RHS); 11570 APInt MinValue = APInt::getMinValue(BitWidth); 11571 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11572 11573 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11574 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11575 } 11576 11577 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11578 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11579 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11580 // expression fixes the case of N=0. 11581 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11582 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11583 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11584 } 11585 11586 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11587 const SCEV *Stride, 11588 const SCEV *End, 11589 unsigned BitWidth, 11590 bool IsSigned) { 11591 // The logic in this function assumes we can represent a positive stride. 11592 // If we can't, the backedge-taken count must be zero. 11593 if (IsSigned && BitWidth == 1) 11594 return getZero(Stride->getType()); 11595 11596 // This code has only been closely audited for negative strides in the 11597 // unsigned comparison case, it may be correct for signed comparison, but 11598 // that needs to be established. 11599 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11600 "Stride is expected strictly positive for signed case!"); 11601 11602 // Calculate the maximum backedge count based on the range of values 11603 // permitted by Start, End, and Stride. 11604 APInt MinStart = 11605 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11606 11607 APInt MinStride = 11608 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11609 11610 // We assume either the stride is positive, or the backedge-taken count 11611 // is zero. So force StrideForMaxBECount to be at least one. 11612 APInt One(BitWidth, 1); 11613 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11614 : APIntOps::umax(One, MinStride); 11615 11616 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11617 : APInt::getMaxValue(BitWidth); 11618 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11619 11620 // Although End can be a MAX expression we estimate MaxEnd considering only 11621 // the case End = RHS of the loop termination condition. This is safe because 11622 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11623 // taken count. 11624 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11625 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11626 11627 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11628 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11629 : APIntOps::umax(MaxEnd, MinStart); 11630 11631 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11632 getConstant(StrideForMaxBECount) /* Step */); 11633 } 11634 11635 ScalarEvolution::ExitLimit 11636 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11637 const Loop *L, bool IsSigned, 11638 bool ControlsExit, bool AllowPredicates) { 11639 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11640 11641 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11642 bool PredicatedIV = false; 11643 11644 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11645 // Can we prove this loop *must* be UB if overflow of IV occurs? 11646 // Reasoning goes as follows: 11647 // * Suppose the IV did self wrap. 11648 // * If Stride evenly divides the iteration space, then once wrap 11649 // occurs, the loop must revisit the same values. 11650 // * We know that RHS is invariant, and that none of those values 11651 // caused this exit to be taken previously. Thus, this exit is 11652 // dynamically dead. 11653 // * If this is the sole exit, then a dead exit implies the loop 11654 // must be infinite if there are no abnormal exits. 11655 // * If the loop were infinite, then it must either not be mustprogress 11656 // or have side effects. Otherwise, it must be UB. 11657 // * It can't (by assumption), be UB so we have contradicted our 11658 // premise and can conclude the IV did not in fact self-wrap. 11659 if (!isLoopInvariant(RHS, L)) 11660 return false; 11661 11662 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11663 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11664 return false; 11665 11666 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11667 return false; 11668 11669 return loopIsFiniteByAssumption(L); 11670 }; 11671 11672 if (!IV) { 11673 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11674 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11675 if (AR && AR->getLoop() == L && AR->isAffine()) { 11676 auto Flags = AR->getNoWrapFlags(); 11677 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11678 Flags = setFlags(Flags, SCEV::FlagNW); 11679 11680 SmallVector<const SCEV*> Operands{AR->operands()}; 11681 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11682 11683 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11684 } 11685 if (AR->hasNoUnsignedWrap()) { 11686 // Emulate what getZeroExtendExpr would have done during construction 11687 // if we'd been able to infer the fact just above at that time. 11688 const SCEV *Step = AR->getStepRecurrence(*this); 11689 Type *Ty = ZExt->getType(); 11690 auto *S = getAddRecExpr( 11691 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11692 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11693 IV = dyn_cast<SCEVAddRecExpr>(S); 11694 } 11695 } 11696 } 11697 } 11698 11699 11700 if (!IV && AllowPredicates) { 11701 // Try to make this an AddRec using runtime tests, in the first X 11702 // iterations of this loop, where X is the SCEV expression found by the 11703 // algorithm below. 11704 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11705 PredicatedIV = true; 11706 } 11707 11708 // Avoid weird loops 11709 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11710 return getCouldNotCompute(); 11711 11712 // A precondition of this method is that the condition being analyzed 11713 // reaches an exiting branch which dominates the latch. Given that, we can 11714 // assume that an increment which violates the nowrap specification and 11715 // produces poison must cause undefined behavior when the resulting poison 11716 // value is branched upon and thus we can conclude that the backedge is 11717 // taken no more often than would be required to produce that poison value. 11718 // Note that a well defined loop can exit on the iteration which violates 11719 // the nowrap specification if there is another exit (either explicit or 11720 // implicit/exceptional) which causes the loop to execute before the 11721 // exiting instruction we're analyzing would trigger UB. 11722 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11723 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11724 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11725 11726 const SCEV *Stride = IV->getStepRecurrence(*this); 11727 11728 bool PositiveStride = isKnownPositive(Stride); 11729 11730 // Avoid negative or zero stride values. 11731 if (!PositiveStride) { 11732 // We can compute the correct backedge taken count for loops with unknown 11733 // strides if we can prove that the loop is not an infinite loop with side 11734 // effects. Here's the loop structure we are trying to handle - 11735 // 11736 // i = start 11737 // do { 11738 // A[i] = i; 11739 // i += s; 11740 // } while (i < end); 11741 // 11742 // The backedge taken count for such loops is evaluated as - 11743 // (max(end, start + stride) - start - 1) /u stride 11744 // 11745 // The additional preconditions that we need to check to prove correctness 11746 // of the above formula is as follows - 11747 // 11748 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11749 // NoWrap flag). 11750 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11751 // no side effects within the loop) 11752 // c) loop has a single static exit (with no abnormal exits) 11753 // 11754 // Precondition a) implies that if the stride is negative, this is a single 11755 // trip loop. The backedge taken count formula reduces to zero in this case. 11756 // 11757 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11758 // then a zero stride means the backedge can't be taken without executing 11759 // undefined behavior. 11760 // 11761 // The positive stride case is the same as isKnownPositive(Stride) returning 11762 // true (original behavior of the function). 11763 // 11764 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 11765 !loopHasNoAbnormalExits(L)) 11766 return getCouldNotCompute(); 11767 11768 // This bailout is protecting the logic in computeMaxBECountForLT which 11769 // has not yet been sufficiently auditted or tested with negative strides. 11770 // We used to filter out all known-non-positive cases here, we're in the 11771 // process of being less restrictive bit by bit. 11772 if (IsSigned && isKnownNonPositive(Stride)) 11773 return getCouldNotCompute(); 11774 11775 if (!isKnownNonZero(Stride)) { 11776 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11777 // if it might eventually be greater than start and if so, on which 11778 // iteration. We can't even produce a useful upper bound. 11779 if (!isLoopInvariant(RHS, L)) 11780 return getCouldNotCompute(); 11781 11782 // We allow a potentially zero stride, but we need to divide by stride 11783 // below. Since the loop can't be infinite and this check must control 11784 // the sole exit, we can infer the exit must be taken on the first 11785 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11786 // we know the numerator in the divides below must be zero, so we can 11787 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11788 // and produce the right result. 11789 // FIXME: Handle the case where Stride is poison? 11790 auto wouldZeroStrideBeUB = [&]() { 11791 // Proof by contradiction. Suppose the stride were zero. If we can 11792 // prove that the backedge *is* taken on the first iteration, then since 11793 // we know this condition controls the sole exit, we must have an 11794 // infinite loop. We can't have a (well defined) infinite loop per 11795 // check just above. 11796 // Note: The (Start - Stride) term is used to get the start' term from 11797 // (start' + stride,+,stride). Remember that we only care about the 11798 // result of this expression when stride == 0 at runtime. 11799 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11800 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11801 }; 11802 if (!wouldZeroStrideBeUB()) { 11803 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11804 } 11805 } 11806 } else if (!Stride->isOne() && !NoWrap) { 11807 auto isUBOnWrap = [&]() { 11808 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11809 // follows trivially from the fact that every (un)signed-wrapped, but 11810 // not self-wrapped value must be LT than the last value before 11811 // (un)signed wrap. Since we know that last value didn't exit, nor 11812 // will any smaller one. 11813 return canAssumeNoSelfWrap(IV); 11814 }; 11815 11816 // Avoid proven overflow cases: this will ensure that the backedge taken 11817 // count will not generate any unsigned overflow. Relaxed no-overflow 11818 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11819 // undefined behaviors like the case of C language. 11820 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11821 return getCouldNotCompute(); 11822 } 11823 11824 // On all paths just preceeding, we established the following invariant: 11825 // IV can be assumed not to overflow up to and including the exiting 11826 // iteration. We proved this in one of two ways: 11827 // 1) We can show overflow doesn't occur before the exiting iteration 11828 // 1a) canIVOverflowOnLT, and b) step of one 11829 // 2) We can show that if overflow occurs, the loop must execute UB 11830 // before any possible exit. 11831 // Note that we have not yet proved RHS invariant (in general). 11832 11833 const SCEV *Start = IV->getStart(); 11834 11835 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11836 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 11837 // Use integer-typed versions for actual computation; we can't subtract 11838 // pointers in general. 11839 const SCEV *OrigStart = Start; 11840 const SCEV *OrigRHS = RHS; 11841 if (Start->getType()->isPointerTy()) { 11842 Start = getLosslessPtrToIntExpr(Start); 11843 if (isa<SCEVCouldNotCompute>(Start)) 11844 return Start; 11845 } 11846 if (RHS->getType()->isPointerTy()) { 11847 RHS = getLosslessPtrToIntExpr(RHS); 11848 if (isa<SCEVCouldNotCompute>(RHS)) 11849 return RHS; 11850 } 11851 11852 // When the RHS is not invariant, we do not know the end bound of the loop and 11853 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11854 // calculate the MaxBECount, given the start, stride and max value for the end 11855 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11856 // checked above). 11857 if (!isLoopInvariant(RHS, L)) { 11858 const SCEV *MaxBECount = computeMaxBECountForLT( 11859 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11860 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11861 false /*MaxOrZero*/, Predicates); 11862 } 11863 11864 // We use the expression (max(End,Start)-Start)/Stride to describe the 11865 // backedge count, as if the backedge is taken at least once max(End,Start) 11866 // is End and so the result is as above, and if not max(End,Start) is Start 11867 // so we get a backedge count of zero. 11868 const SCEV *BECount = nullptr; 11869 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 11870 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 11871 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 11872 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 11873 // Can we prove (max(RHS,Start) > Start - Stride? 11874 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 11875 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 11876 // In this case, we can use a refined formula for computing backedge taken 11877 // count. The general formula remains: 11878 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11879 // We want to use the alternate formula: 11880 // "((End - 1) - (Start - Stride)) /u Stride" 11881 // Let's do a quick case analysis to show these are equivalent under 11882 // our precondition that max(RHS,Start) > Start - Stride. 11883 // * For RHS <= Start, the backedge-taken count must be zero. 11884 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11885 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11886 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11887 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11888 // this to the stride of 1 case. 11889 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11890 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11891 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11892 // "((RHS - (Start - Stride) - 1) /u Stride". 11893 // Our preconditions trivially imply no overflow in that form. 11894 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11895 const SCEV *Numerator = 11896 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 11897 BECount = getUDivExpr(Numerator, Stride); 11898 } 11899 11900 const SCEV *BECountIfBackedgeTaken = nullptr; 11901 if (!BECount) { 11902 auto canProveRHSGreaterThanEqualStart = [&]() { 11903 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11904 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11905 return true; 11906 11907 // (RHS > Start - 1) implies RHS >= Start. 11908 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11909 // "Start - 1" doesn't overflow. 11910 // * For signed comparison, if Start - 1 does overflow, it's equal 11911 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11912 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11913 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11914 // 11915 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11916 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11917 auto *StartMinusOne = getAddExpr(OrigStart, 11918 getMinusOne(OrigStart->getType())); 11919 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11920 }; 11921 11922 // If we know that RHS >= Start in the context of loop, then we know that 11923 // max(RHS, Start) = RHS at this point. 11924 const SCEV *End; 11925 if (canProveRHSGreaterThanEqualStart()) { 11926 End = RHS; 11927 } else { 11928 // If RHS < Start, the backedge will be taken zero times. So in 11929 // general, we can write the backedge-taken count as: 11930 // 11931 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11932 // 11933 // We convert it to the following to make it more convenient for SCEV: 11934 // 11935 // ceil(max(RHS, Start) - Start) / Stride 11936 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11937 11938 // See what would happen if we assume the backedge is taken. This is 11939 // used to compute MaxBECount. 11940 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11941 } 11942 11943 // At this point, we know: 11944 // 11945 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11946 // 2. The index variable doesn't overflow. 11947 // 11948 // Therefore, we know N exists such that 11949 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11950 // doesn't overflow. 11951 // 11952 // Using this information, try to prove whether the addition in 11953 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11954 const SCEV *One = getOne(Stride->getType()); 11955 bool MayAddOverflow = [&] { 11956 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11957 if (StrideC->getAPInt().isPowerOf2()) { 11958 // Suppose Stride is a power of two, and Start/End are unsigned 11959 // integers. Let UMAX be the largest representable unsigned 11960 // integer. 11961 // 11962 // By the preconditions of this function, we know 11963 // "(Start + Stride * N) >= End", and this doesn't overflow. 11964 // As a formula: 11965 // 11966 // End <= (Start + Stride * N) <= UMAX 11967 // 11968 // Subtracting Start from all the terms: 11969 // 11970 // End - Start <= Stride * N <= UMAX - Start 11971 // 11972 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11973 // 11974 // End - Start <= Stride * N <= UMAX 11975 // 11976 // Stride * N is a multiple of Stride. Therefore, 11977 // 11978 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11979 // 11980 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11981 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11982 // 11983 // End - Start <= Stride * N <= UMAX - Stride - 1 11984 // 11985 // Dropping the middle term: 11986 // 11987 // End - Start <= UMAX - Stride - 1 11988 // 11989 // Adding Stride - 1 to both sides: 11990 // 11991 // (End - Start) + (Stride - 1) <= UMAX 11992 // 11993 // In other words, the addition doesn't have unsigned overflow. 11994 // 11995 // A similar proof works if we treat Start/End as signed values. 11996 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11997 // use signed max instead of unsigned max. Note that we're trying 11998 // to prove a lack of unsigned overflow in either case. 11999 return false; 12000 } 12001 } 12002 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 12003 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 12004 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 12005 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 12006 // 12007 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 12008 return false; 12009 } 12010 return true; 12011 }(); 12012 12013 const SCEV *Delta = getMinusSCEV(End, Start); 12014 if (!MayAddOverflow) { 12015 // floor((D + (S - 1)) / S) 12016 // We prefer this formulation if it's legal because it's fewer operations. 12017 BECount = 12018 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12019 } else { 12020 BECount = getUDivCeilSCEV(Delta, Stride); 12021 } 12022 } 12023 12024 const SCEV *MaxBECount; 12025 bool MaxOrZero = false; 12026 if (isa<SCEVConstant>(BECount)) { 12027 MaxBECount = BECount; 12028 } else if (BECountIfBackedgeTaken && 12029 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12030 // If we know exactly how many times the backedge will be taken if it's 12031 // taken at least once, then the backedge count will either be that or 12032 // zero. 12033 MaxBECount = BECountIfBackedgeTaken; 12034 MaxOrZero = true; 12035 } else { 12036 MaxBECount = computeMaxBECountForLT( 12037 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12038 } 12039 12040 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12041 !isa<SCEVCouldNotCompute>(BECount)) 12042 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12043 12044 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12045 } 12046 12047 ScalarEvolution::ExitLimit 12048 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12049 const Loop *L, bool IsSigned, 12050 bool ControlsExit, bool AllowPredicates) { 12051 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12052 // We handle only IV > Invariant 12053 if (!isLoopInvariant(RHS, L)) 12054 return getCouldNotCompute(); 12055 12056 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12057 if (!IV && AllowPredicates) 12058 // Try to make this an AddRec using runtime tests, in the first X 12059 // iterations of this loop, where X is the SCEV expression found by the 12060 // algorithm below. 12061 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12062 12063 // Avoid weird loops 12064 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12065 return getCouldNotCompute(); 12066 12067 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12068 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12069 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12070 12071 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12072 12073 // Avoid negative or zero stride values 12074 if (!isKnownPositive(Stride)) 12075 return getCouldNotCompute(); 12076 12077 // Avoid proven overflow cases: this will ensure that the backedge taken count 12078 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12079 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12080 // behaviors like the case of C language. 12081 if (!Stride->isOne() && !NoWrap) 12082 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12083 return getCouldNotCompute(); 12084 12085 const SCEV *Start = IV->getStart(); 12086 const SCEV *End = RHS; 12087 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12088 // If we know that Start >= RHS in the context of loop, then we know that 12089 // min(RHS, Start) = RHS at this point. 12090 if (isLoopEntryGuardedByCond( 12091 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12092 End = RHS; 12093 else 12094 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12095 } 12096 12097 if (Start->getType()->isPointerTy()) { 12098 Start = getLosslessPtrToIntExpr(Start); 12099 if (isa<SCEVCouldNotCompute>(Start)) 12100 return Start; 12101 } 12102 if (End->getType()->isPointerTy()) { 12103 End = getLosslessPtrToIntExpr(End); 12104 if (isa<SCEVCouldNotCompute>(End)) 12105 return End; 12106 } 12107 12108 // Compute ((Start - End) + (Stride - 1)) / Stride. 12109 // FIXME: This can overflow. Holding off on fixing this for now; 12110 // howManyGreaterThans will hopefully be gone soon. 12111 const SCEV *One = getOne(Stride->getType()); 12112 const SCEV *BECount = getUDivExpr( 12113 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12114 12115 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12116 : getUnsignedRangeMax(Start); 12117 12118 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12119 : getUnsignedRangeMin(Stride); 12120 12121 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12122 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12123 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12124 12125 // Although End can be a MIN expression we estimate MinEnd considering only 12126 // the case End = RHS. This is safe because in the other case (Start - End) 12127 // is zero, leading to a zero maximum backedge taken count. 12128 APInt MinEnd = 12129 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12130 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12131 12132 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12133 ? BECount 12134 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12135 getConstant(MinStride)); 12136 12137 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12138 MaxBECount = BECount; 12139 12140 return ExitLimit(BECount, MaxBECount, false, Predicates); 12141 } 12142 12143 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12144 ScalarEvolution &SE) const { 12145 if (Range.isFullSet()) // Infinite loop. 12146 return SE.getCouldNotCompute(); 12147 12148 // If the start is a non-zero constant, shift the range to simplify things. 12149 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12150 if (!SC->getValue()->isZero()) { 12151 SmallVector<const SCEV *, 4> Operands(operands()); 12152 Operands[0] = SE.getZero(SC->getType()); 12153 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12154 getNoWrapFlags(FlagNW)); 12155 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12156 return ShiftedAddRec->getNumIterationsInRange( 12157 Range.subtract(SC->getAPInt()), SE); 12158 // This is strange and shouldn't happen. 12159 return SE.getCouldNotCompute(); 12160 } 12161 12162 // The only time we can solve this is when we have all constant indices. 12163 // Otherwise, we cannot determine the overflow conditions. 12164 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12165 return SE.getCouldNotCompute(); 12166 12167 // Okay at this point we know that all elements of the chrec are constants and 12168 // that the start element is zero. 12169 12170 // First check to see if the range contains zero. If not, the first 12171 // iteration exits. 12172 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12173 if (!Range.contains(APInt(BitWidth, 0))) 12174 return SE.getZero(getType()); 12175 12176 if (isAffine()) { 12177 // If this is an affine expression then we have this situation: 12178 // Solve {0,+,A} in Range === Ax in Range 12179 12180 // We know that zero is in the range. If A is positive then we know that 12181 // the upper value of the range must be the first possible exit value. 12182 // If A is negative then the lower of the range is the last possible loop 12183 // value. Also note that we already checked for a full range. 12184 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12185 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12186 12187 // The exit value should be (End+A)/A. 12188 APInt ExitVal = (End + A).udiv(A); 12189 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12190 12191 // Evaluate at the exit value. If we really did fall out of the valid 12192 // range, then we computed our trip count, otherwise wrap around or other 12193 // things must have happened. 12194 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12195 if (Range.contains(Val->getValue())) 12196 return SE.getCouldNotCompute(); // Something strange happened 12197 12198 // Ensure that the previous value is in the range. This is a sanity check. 12199 assert(Range.contains( 12200 EvaluateConstantChrecAtConstant(this, 12201 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12202 "Linear scev computation is off in a bad way!"); 12203 return SE.getConstant(ExitValue); 12204 } 12205 12206 if (isQuadratic()) { 12207 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12208 return SE.getConstant(S.getValue()); 12209 } 12210 12211 return SE.getCouldNotCompute(); 12212 } 12213 12214 const SCEVAddRecExpr * 12215 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12216 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12217 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12218 // but in this case we cannot guarantee that the value returned will be an 12219 // AddRec because SCEV does not have a fixed point where it stops 12220 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12221 // may happen if we reach arithmetic depth limit while simplifying. So we 12222 // construct the returned value explicitly. 12223 SmallVector<const SCEV *, 3> Ops; 12224 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12225 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12226 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12227 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12228 // We know that the last operand is not a constant zero (otherwise it would 12229 // have been popped out earlier). This guarantees us that if the result has 12230 // the same last operand, then it will also not be popped out, meaning that 12231 // the returned value will be an AddRec. 12232 const SCEV *Last = getOperand(getNumOperands() - 1); 12233 assert(!Last->isZero() && "Recurrency with zero step?"); 12234 Ops.push_back(Last); 12235 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12236 SCEV::FlagAnyWrap)); 12237 } 12238 12239 // Return true when S contains at least an undef value. 12240 static inline bool containsUndefs(const SCEV *S) { 12241 return SCEVExprContains(S, [](const SCEV *S) { 12242 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12243 return isa<UndefValue>(SU->getValue()); 12244 return false; 12245 }); 12246 } 12247 12248 /// Return the size of an element read or written by Inst. 12249 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12250 Type *Ty; 12251 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12252 Ty = Store->getValueOperand()->getType(); 12253 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12254 Ty = Load->getType(); 12255 else 12256 return nullptr; 12257 12258 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12259 return getSizeOfExpr(ETy, Ty); 12260 } 12261 12262 //===----------------------------------------------------------------------===// 12263 // SCEVCallbackVH Class Implementation 12264 //===----------------------------------------------------------------------===// 12265 12266 void ScalarEvolution::SCEVCallbackVH::deleted() { 12267 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12268 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12269 SE->ConstantEvolutionLoopExitValue.erase(PN); 12270 SE->eraseValueFromMap(getValPtr()); 12271 // this now dangles! 12272 } 12273 12274 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12275 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12276 12277 // Forget all the expressions associated with users of the old value, 12278 // so that future queries will recompute the expressions using the new 12279 // value. 12280 Value *Old = getValPtr(); 12281 SmallVector<User *, 16> Worklist(Old->users()); 12282 SmallPtrSet<User *, 8> Visited; 12283 while (!Worklist.empty()) { 12284 User *U = Worklist.pop_back_val(); 12285 // Deleting the Old value will cause this to dangle. Postpone 12286 // that until everything else is done. 12287 if (U == Old) 12288 continue; 12289 if (!Visited.insert(U).second) 12290 continue; 12291 if (PHINode *PN = dyn_cast<PHINode>(U)) 12292 SE->ConstantEvolutionLoopExitValue.erase(PN); 12293 SE->eraseValueFromMap(U); 12294 llvm::append_range(Worklist, U->users()); 12295 } 12296 // Delete the Old value. 12297 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12298 SE->ConstantEvolutionLoopExitValue.erase(PN); 12299 SE->eraseValueFromMap(Old); 12300 // this now dangles! 12301 } 12302 12303 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12304 : CallbackVH(V), SE(se) {} 12305 12306 //===----------------------------------------------------------------------===// 12307 // ScalarEvolution Class Implementation 12308 //===----------------------------------------------------------------------===// 12309 12310 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12311 AssumptionCache &AC, DominatorTree &DT, 12312 LoopInfo &LI) 12313 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12314 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12315 LoopDispositions(64), BlockDispositions(64) { 12316 // To use guards for proving predicates, we need to scan every instruction in 12317 // relevant basic blocks, and not just terminators. Doing this is a waste of 12318 // time if the IR does not actually contain any calls to 12319 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12320 // 12321 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12322 // to _add_ guards to the module when there weren't any before, and wants 12323 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12324 // efficient in lieu of being smart in that rather obscure case. 12325 12326 auto *GuardDecl = F.getParent()->getFunction( 12327 Intrinsic::getName(Intrinsic::experimental_guard)); 12328 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12329 } 12330 12331 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12332 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12333 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12334 ValueExprMap(std::move(Arg.ValueExprMap)), 12335 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12336 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12337 PendingMerges(std::move(Arg.PendingMerges)), 12338 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12339 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12340 PredicatedBackedgeTakenCounts( 12341 std::move(Arg.PredicatedBackedgeTakenCounts)), 12342 ConstantEvolutionLoopExitValue( 12343 std::move(Arg.ConstantEvolutionLoopExitValue)), 12344 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12345 LoopDispositions(std::move(Arg.LoopDispositions)), 12346 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12347 BlockDispositions(std::move(Arg.BlockDispositions)), 12348 SCEVUsers(std::move(Arg.SCEVUsers)), 12349 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12350 SignedRanges(std::move(Arg.SignedRanges)), 12351 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12352 UniquePreds(std::move(Arg.UniquePreds)), 12353 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12354 LoopUsers(std::move(Arg.LoopUsers)), 12355 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12356 FirstUnknown(Arg.FirstUnknown) { 12357 Arg.FirstUnknown = nullptr; 12358 } 12359 12360 ScalarEvolution::~ScalarEvolution() { 12361 // Iterate through all the SCEVUnknown instances and call their 12362 // destructors, so that they release their references to their values. 12363 for (SCEVUnknown *U = FirstUnknown; U;) { 12364 SCEVUnknown *Tmp = U; 12365 U = U->Next; 12366 Tmp->~SCEVUnknown(); 12367 } 12368 FirstUnknown = nullptr; 12369 12370 ExprValueMap.clear(); 12371 ValueExprMap.clear(); 12372 HasRecMap.clear(); 12373 BackedgeTakenCounts.clear(); 12374 PredicatedBackedgeTakenCounts.clear(); 12375 12376 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12377 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12378 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12379 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12380 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12381 } 12382 12383 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12384 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12385 } 12386 12387 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12388 const Loop *L) { 12389 // Print all inner loops first 12390 for (Loop *I : *L) 12391 PrintLoopInfo(OS, SE, I); 12392 12393 OS << "Loop "; 12394 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12395 OS << ": "; 12396 12397 SmallVector<BasicBlock *, 8> ExitingBlocks; 12398 L->getExitingBlocks(ExitingBlocks); 12399 if (ExitingBlocks.size() != 1) 12400 OS << "<multiple exits> "; 12401 12402 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12403 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12404 else 12405 OS << "Unpredictable backedge-taken count.\n"; 12406 12407 if (ExitingBlocks.size() > 1) 12408 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12409 OS << " exit count for " << ExitingBlock->getName() << ": " 12410 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12411 } 12412 12413 OS << "Loop "; 12414 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12415 OS << ": "; 12416 12417 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12418 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12419 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12420 OS << ", actual taken count either this or zero."; 12421 } else { 12422 OS << "Unpredictable max backedge-taken count. "; 12423 } 12424 12425 OS << "\n" 12426 "Loop "; 12427 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12428 OS << ": "; 12429 12430 SCEVUnionPredicate Pred; 12431 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12432 if (!isa<SCEVCouldNotCompute>(PBT)) { 12433 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12434 OS << " Predicates:\n"; 12435 Pred.print(OS, 4); 12436 } else { 12437 OS << "Unpredictable predicated backedge-taken count. "; 12438 } 12439 OS << "\n"; 12440 12441 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12442 OS << "Loop "; 12443 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12444 OS << ": "; 12445 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12446 } 12447 } 12448 12449 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12450 switch (LD) { 12451 case ScalarEvolution::LoopVariant: 12452 return "Variant"; 12453 case ScalarEvolution::LoopInvariant: 12454 return "Invariant"; 12455 case ScalarEvolution::LoopComputable: 12456 return "Computable"; 12457 } 12458 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12459 } 12460 12461 void ScalarEvolution::print(raw_ostream &OS) const { 12462 // ScalarEvolution's implementation of the print method is to print 12463 // out SCEV values of all instructions that are interesting. Doing 12464 // this potentially causes it to create new SCEV objects though, 12465 // which technically conflicts with the const qualifier. This isn't 12466 // observable from outside the class though, so casting away the 12467 // const isn't dangerous. 12468 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12469 12470 if (ClassifyExpressions) { 12471 OS << "Classifying expressions for: "; 12472 F.printAsOperand(OS, /*PrintType=*/false); 12473 OS << "\n"; 12474 for (Instruction &I : instructions(F)) 12475 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12476 OS << I << '\n'; 12477 OS << " --> "; 12478 const SCEV *SV = SE.getSCEV(&I); 12479 SV->print(OS); 12480 if (!isa<SCEVCouldNotCompute>(SV)) { 12481 OS << " U: "; 12482 SE.getUnsignedRange(SV).print(OS); 12483 OS << " S: "; 12484 SE.getSignedRange(SV).print(OS); 12485 } 12486 12487 const Loop *L = LI.getLoopFor(I.getParent()); 12488 12489 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12490 if (AtUse != SV) { 12491 OS << " --> "; 12492 AtUse->print(OS); 12493 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12494 OS << " U: "; 12495 SE.getUnsignedRange(AtUse).print(OS); 12496 OS << " S: "; 12497 SE.getSignedRange(AtUse).print(OS); 12498 } 12499 } 12500 12501 if (L) { 12502 OS << "\t\t" "Exits: "; 12503 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12504 if (!SE.isLoopInvariant(ExitValue, L)) { 12505 OS << "<<Unknown>>"; 12506 } else { 12507 OS << *ExitValue; 12508 } 12509 12510 bool First = true; 12511 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12512 if (First) { 12513 OS << "\t\t" "LoopDispositions: { "; 12514 First = false; 12515 } else { 12516 OS << ", "; 12517 } 12518 12519 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12520 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12521 } 12522 12523 for (auto *InnerL : depth_first(L)) { 12524 if (InnerL == L) 12525 continue; 12526 if (First) { 12527 OS << "\t\t" "LoopDispositions: { "; 12528 First = false; 12529 } else { 12530 OS << ", "; 12531 } 12532 12533 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12534 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12535 } 12536 12537 OS << " }"; 12538 } 12539 12540 OS << "\n"; 12541 } 12542 } 12543 12544 OS << "Determining loop execution counts for: "; 12545 F.printAsOperand(OS, /*PrintType=*/false); 12546 OS << "\n"; 12547 for (Loop *I : LI) 12548 PrintLoopInfo(OS, &SE, I); 12549 } 12550 12551 ScalarEvolution::LoopDisposition 12552 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12553 auto &Values = LoopDispositions[S]; 12554 for (auto &V : Values) { 12555 if (V.getPointer() == L) 12556 return V.getInt(); 12557 } 12558 Values.emplace_back(L, LoopVariant); 12559 LoopDisposition D = computeLoopDisposition(S, L); 12560 auto &Values2 = LoopDispositions[S]; 12561 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12562 if (V.getPointer() == L) { 12563 V.setInt(D); 12564 break; 12565 } 12566 } 12567 return D; 12568 } 12569 12570 ScalarEvolution::LoopDisposition 12571 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12572 switch (S->getSCEVType()) { 12573 case scConstant: 12574 return LoopInvariant; 12575 case scPtrToInt: 12576 case scTruncate: 12577 case scZeroExtend: 12578 case scSignExtend: 12579 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12580 case scAddRecExpr: { 12581 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12582 12583 // If L is the addrec's loop, it's computable. 12584 if (AR->getLoop() == L) 12585 return LoopComputable; 12586 12587 // Add recurrences are never invariant in the function-body (null loop). 12588 if (!L) 12589 return LoopVariant; 12590 12591 // Everything that is not defined at loop entry is variant. 12592 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12593 return LoopVariant; 12594 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12595 " dominate the contained loop's header?"); 12596 12597 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12598 if (AR->getLoop()->contains(L)) 12599 return LoopInvariant; 12600 12601 // This recurrence is variant w.r.t. L if any of its operands 12602 // are variant. 12603 for (auto *Op : AR->operands()) 12604 if (!isLoopInvariant(Op, L)) 12605 return LoopVariant; 12606 12607 // Otherwise it's loop-invariant. 12608 return LoopInvariant; 12609 } 12610 case scAddExpr: 12611 case scMulExpr: 12612 case scUMaxExpr: 12613 case scSMaxExpr: 12614 case scUMinExpr: 12615 case scSMinExpr: { 12616 bool HasVarying = false; 12617 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12618 LoopDisposition D = getLoopDisposition(Op, L); 12619 if (D == LoopVariant) 12620 return LoopVariant; 12621 if (D == LoopComputable) 12622 HasVarying = true; 12623 } 12624 return HasVarying ? LoopComputable : LoopInvariant; 12625 } 12626 case scUDivExpr: { 12627 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12628 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12629 if (LD == LoopVariant) 12630 return LoopVariant; 12631 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12632 if (RD == LoopVariant) 12633 return LoopVariant; 12634 return (LD == LoopInvariant && RD == LoopInvariant) ? 12635 LoopInvariant : LoopComputable; 12636 } 12637 case scUnknown: 12638 // All non-instruction values are loop invariant. All instructions are loop 12639 // invariant if they are not contained in the specified loop. 12640 // Instructions are never considered invariant in the function body 12641 // (null loop) because they are defined within the "loop". 12642 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12643 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12644 return LoopInvariant; 12645 case scCouldNotCompute: 12646 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12647 } 12648 llvm_unreachable("Unknown SCEV kind!"); 12649 } 12650 12651 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12652 return getLoopDisposition(S, L) == LoopInvariant; 12653 } 12654 12655 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12656 return getLoopDisposition(S, L) == LoopComputable; 12657 } 12658 12659 ScalarEvolution::BlockDisposition 12660 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12661 auto &Values = BlockDispositions[S]; 12662 for (auto &V : Values) { 12663 if (V.getPointer() == BB) 12664 return V.getInt(); 12665 } 12666 Values.emplace_back(BB, DoesNotDominateBlock); 12667 BlockDisposition D = computeBlockDisposition(S, BB); 12668 auto &Values2 = BlockDispositions[S]; 12669 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12670 if (V.getPointer() == BB) { 12671 V.setInt(D); 12672 break; 12673 } 12674 } 12675 return D; 12676 } 12677 12678 ScalarEvolution::BlockDisposition 12679 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12680 switch (S->getSCEVType()) { 12681 case scConstant: 12682 return ProperlyDominatesBlock; 12683 case scPtrToInt: 12684 case scTruncate: 12685 case scZeroExtend: 12686 case scSignExtend: 12687 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12688 case scAddRecExpr: { 12689 // This uses a "dominates" query instead of "properly dominates" query 12690 // to test for proper dominance too, because the instruction which 12691 // produces the addrec's value is a PHI, and a PHI effectively properly 12692 // dominates its entire containing block. 12693 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12694 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12695 return DoesNotDominateBlock; 12696 12697 // Fall through into SCEVNAryExpr handling. 12698 LLVM_FALLTHROUGH; 12699 } 12700 case scAddExpr: 12701 case scMulExpr: 12702 case scUMaxExpr: 12703 case scSMaxExpr: 12704 case scUMinExpr: 12705 case scSMinExpr: { 12706 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12707 bool Proper = true; 12708 for (const SCEV *NAryOp : NAry->operands()) { 12709 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12710 if (D == DoesNotDominateBlock) 12711 return DoesNotDominateBlock; 12712 if (D == DominatesBlock) 12713 Proper = false; 12714 } 12715 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12716 } 12717 case scUDivExpr: { 12718 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12719 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12720 BlockDisposition LD = getBlockDisposition(LHS, BB); 12721 if (LD == DoesNotDominateBlock) 12722 return DoesNotDominateBlock; 12723 BlockDisposition RD = getBlockDisposition(RHS, BB); 12724 if (RD == DoesNotDominateBlock) 12725 return DoesNotDominateBlock; 12726 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12727 ProperlyDominatesBlock : DominatesBlock; 12728 } 12729 case scUnknown: 12730 if (Instruction *I = 12731 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12732 if (I->getParent() == BB) 12733 return DominatesBlock; 12734 if (DT.properlyDominates(I->getParent(), BB)) 12735 return ProperlyDominatesBlock; 12736 return DoesNotDominateBlock; 12737 } 12738 return ProperlyDominatesBlock; 12739 case scCouldNotCompute: 12740 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12741 } 12742 llvm_unreachable("Unknown SCEV kind!"); 12743 } 12744 12745 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12746 return getBlockDisposition(S, BB) >= DominatesBlock; 12747 } 12748 12749 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12750 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12751 } 12752 12753 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12754 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12755 } 12756 12757 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 12758 for (auto *S : SCEVs) 12759 forgetMemoizedResultsImpl(S); 12760 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 12761 for (auto I = PredicatedSCEVRewrites.begin(); 12762 I != PredicatedSCEVRewrites.end();) { 12763 std::pair<const SCEV *, const Loop *> Entry = I->first; 12764 if (ToForget.count(Entry.first)) 12765 PredicatedSCEVRewrites.erase(I++); 12766 else 12767 ++I; 12768 } 12769 12770 auto RemoveSCEVFromBackedgeMap = [&ToForget]( 12771 DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12772 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12773 BackedgeTakenInfo &BEInfo = I->second; 12774 if (any_of(ToForget, 12775 [&BEInfo](const SCEV *S) { return BEInfo.hasOperand(S); })) 12776 Map.erase(I++); 12777 else 12778 ++I; 12779 } 12780 }; 12781 12782 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12783 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12784 } 12785 12786 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 12787 ValuesAtScopes.erase(S); 12788 LoopDispositions.erase(S); 12789 BlockDispositions.erase(S); 12790 UnsignedRanges.erase(S); 12791 SignedRanges.erase(S); 12792 ExprValueMap.erase(S); 12793 HasRecMap.erase(S); 12794 MinTrailingZerosCache.erase(S); 12795 } 12796 12797 void 12798 ScalarEvolution::getUsedLoops(const SCEV *S, 12799 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12800 struct FindUsedLoops { 12801 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12802 : LoopsUsed(LoopsUsed) {} 12803 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12804 bool follow(const SCEV *S) { 12805 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12806 LoopsUsed.insert(AR->getLoop()); 12807 return true; 12808 } 12809 12810 bool isDone() const { return false; } 12811 }; 12812 12813 FindUsedLoops F(LoopsUsed); 12814 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12815 } 12816 12817 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12818 SmallPtrSet<const Loop *, 8> LoopsUsed; 12819 getUsedLoops(S, LoopsUsed); 12820 for (auto *L : LoopsUsed) 12821 LoopUsers[L].push_back(S); 12822 } 12823 12824 void ScalarEvolution::verify() const { 12825 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12826 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12827 12828 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12829 12830 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12831 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12832 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12833 12834 const SCEV *visitConstant(const SCEVConstant *Constant) { 12835 return SE.getConstant(Constant->getAPInt()); 12836 } 12837 12838 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12839 return SE.getUnknown(Expr->getValue()); 12840 } 12841 12842 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12843 return SE.getCouldNotCompute(); 12844 } 12845 }; 12846 12847 SCEVMapper SCM(SE2); 12848 12849 while (!LoopStack.empty()) { 12850 auto *L = LoopStack.pop_back_val(); 12851 llvm::append_range(LoopStack, *L); 12852 12853 auto *CurBECount = SCM.visit( 12854 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12855 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12856 12857 if (CurBECount == SE2.getCouldNotCompute() || 12858 NewBECount == SE2.getCouldNotCompute()) { 12859 // NB! This situation is legal, but is very suspicious -- whatever pass 12860 // change the loop to make a trip count go from could not compute to 12861 // computable or vice-versa *should have* invalidated SCEV. However, we 12862 // choose not to assert here (for now) since we don't want false 12863 // positives. 12864 continue; 12865 } 12866 12867 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12868 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12869 // not propagate undef aggressively). This means we can (and do) fail 12870 // verification in cases where a transform makes the trip count of a loop 12871 // go from "undef" to "undef+1" (say). The transform is fine, since in 12872 // both cases the loop iterates "undef" times, but SCEV thinks we 12873 // increased the trip count of the loop by 1 incorrectly. 12874 continue; 12875 } 12876 12877 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12878 SE.getTypeSizeInBits(NewBECount->getType())) 12879 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12880 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12881 SE.getTypeSizeInBits(NewBECount->getType())) 12882 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12883 12884 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12885 12886 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12887 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12888 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12889 dbgs() << "Old: " << *CurBECount << "\n"; 12890 dbgs() << "New: " << *NewBECount << "\n"; 12891 dbgs() << "Delta: " << *Delta << "\n"; 12892 std::abort(); 12893 } 12894 } 12895 12896 // Collect all valid loops currently in LoopInfo. 12897 SmallPtrSet<Loop *, 32> ValidLoops; 12898 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12899 while (!Worklist.empty()) { 12900 Loop *L = Worklist.pop_back_val(); 12901 if (ValidLoops.contains(L)) 12902 continue; 12903 ValidLoops.insert(L); 12904 Worklist.append(L->begin(), L->end()); 12905 } 12906 // Check for SCEV expressions referencing invalid/deleted loops. 12907 for (auto &KV : ValueExprMap) { 12908 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12909 if (!AR) 12910 continue; 12911 assert(ValidLoops.contains(AR->getLoop()) && 12912 "AddRec references invalid loop"); 12913 } 12914 } 12915 12916 bool ScalarEvolution::invalidate( 12917 Function &F, const PreservedAnalyses &PA, 12918 FunctionAnalysisManager::Invalidator &Inv) { 12919 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12920 // of its dependencies is invalidated. 12921 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12922 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12923 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12924 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12925 Inv.invalidate<LoopAnalysis>(F, PA); 12926 } 12927 12928 AnalysisKey ScalarEvolutionAnalysis::Key; 12929 12930 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12931 FunctionAnalysisManager &AM) { 12932 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12933 AM.getResult<AssumptionAnalysis>(F), 12934 AM.getResult<DominatorTreeAnalysis>(F), 12935 AM.getResult<LoopAnalysis>(F)); 12936 } 12937 12938 PreservedAnalyses 12939 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12940 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12941 return PreservedAnalyses::all(); 12942 } 12943 12944 PreservedAnalyses 12945 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12946 // For compatibility with opt's -analyze feature under legacy pass manager 12947 // which was not ported to NPM. This keeps tests using 12948 // update_analyze_test_checks.py working. 12949 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12950 << F.getName() << "':\n"; 12951 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12952 return PreservedAnalyses::all(); 12953 } 12954 12955 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12956 "Scalar Evolution Analysis", false, true) 12957 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12958 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12959 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12960 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12961 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12962 "Scalar Evolution Analysis", false, true) 12963 12964 char ScalarEvolutionWrapperPass::ID = 0; 12965 12966 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12967 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12968 } 12969 12970 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12971 SE.reset(new ScalarEvolution( 12972 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12973 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12974 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12975 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12976 return false; 12977 } 12978 12979 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12980 12981 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12982 SE->print(OS); 12983 } 12984 12985 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12986 if (!VerifySCEV) 12987 return; 12988 12989 SE->verify(); 12990 } 12991 12992 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12993 AU.setPreservesAll(); 12994 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12995 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12996 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12997 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12998 } 12999 13000 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13001 const SCEV *RHS) { 13002 FoldingSetNodeID ID; 13003 assert(LHS->getType() == RHS->getType() && 13004 "Type mismatch between LHS and RHS"); 13005 // Unique this node based on the arguments 13006 ID.AddInteger(SCEVPredicate::P_Equal); 13007 ID.AddPointer(LHS); 13008 ID.AddPointer(RHS); 13009 void *IP = nullptr; 13010 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13011 return S; 13012 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13013 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13014 UniquePreds.InsertNode(Eq, IP); 13015 return Eq; 13016 } 13017 13018 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13019 const SCEVAddRecExpr *AR, 13020 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13021 FoldingSetNodeID ID; 13022 // Unique this node based on the arguments 13023 ID.AddInteger(SCEVPredicate::P_Wrap); 13024 ID.AddPointer(AR); 13025 ID.AddInteger(AddedFlags); 13026 void *IP = nullptr; 13027 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13028 return S; 13029 auto *OF = new (SCEVAllocator) 13030 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13031 UniquePreds.InsertNode(OF, IP); 13032 return OF; 13033 } 13034 13035 namespace { 13036 13037 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13038 public: 13039 13040 /// Rewrites \p S in the context of a loop L and the SCEV predication 13041 /// infrastructure. 13042 /// 13043 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13044 /// equivalences present in \p Pred. 13045 /// 13046 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13047 /// \p NewPreds such that the result will be an AddRecExpr. 13048 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13049 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13050 SCEVUnionPredicate *Pred) { 13051 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13052 return Rewriter.visit(S); 13053 } 13054 13055 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13056 if (Pred) { 13057 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13058 for (auto *Pred : ExprPreds) 13059 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13060 if (IPred->getLHS() == Expr) 13061 return IPred->getRHS(); 13062 } 13063 return convertToAddRecWithPreds(Expr); 13064 } 13065 13066 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13067 const SCEV *Operand = visit(Expr->getOperand()); 13068 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13069 if (AR && AR->getLoop() == L && AR->isAffine()) { 13070 // This couldn't be folded because the operand didn't have the nuw 13071 // flag. Add the nusw flag as an assumption that we could make. 13072 const SCEV *Step = AR->getStepRecurrence(SE); 13073 Type *Ty = Expr->getType(); 13074 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13075 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13076 SE.getSignExtendExpr(Step, Ty), L, 13077 AR->getNoWrapFlags()); 13078 } 13079 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13080 } 13081 13082 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13083 const SCEV *Operand = visit(Expr->getOperand()); 13084 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13085 if (AR && AR->getLoop() == L && AR->isAffine()) { 13086 // This couldn't be folded because the operand didn't have the nsw 13087 // flag. Add the nssw flag as an assumption that we could make. 13088 const SCEV *Step = AR->getStepRecurrence(SE); 13089 Type *Ty = Expr->getType(); 13090 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13091 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13092 SE.getSignExtendExpr(Step, Ty), L, 13093 AR->getNoWrapFlags()); 13094 } 13095 return SE.getSignExtendExpr(Operand, Expr->getType()); 13096 } 13097 13098 private: 13099 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13100 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13101 SCEVUnionPredicate *Pred) 13102 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13103 13104 bool addOverflowAssumption(const SCEVPredicate *P) { 13105 if (!NewPreds) { 13106 // Check if we've already made this assumption. 13107 return Pred && Pred->implies(P); 13108 } 13109 NewPreds->insert(P); 13110 return true; 13111 } 13112 13113 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13114 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13115 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13116 return addOverflowAssumption(A); 13117 } 13118 13119 // If \p Expr represents a PHINode, we try to see if it can be represented 13120 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13121 // to add this predicate as a runtime overflow check, we return the AddRec. 13122 // If \p Expr does not meet these conditions (is not a PHI node, or we 13123 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13124 // return \p Expr. 13125 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13126 if (!isa<PHINode>(Expr->getValue())) 13127 return Expr; 13128 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13129 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13130 if (!PredicatedRewrite) 13131 return Expr; 13132 for (auto *P : PredicatedRewrite->second){ 13133 // Wrap predicates from outer loops are not supported. 13134 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13135 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13136 if (L != AR->getLoop()) 13137 return Expr; 13138 } 13139 if (!addOverflowAssumption(P)) 13140 return Expr; 13141 } 13142 return PredicatedRewrite->first; 13143 } 13144 13145 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13146 SCEVUnionPredicate *Pred; 13147 const Loop *L; 13148 }; 13149 13150 } // end anonymous namespace 13151 13152 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13153 SCEVUnionPredicate &Preds) { 13154 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13155 } 13156 13157 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13158 const SCEV *S, const Loop *L, 13159 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13160 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13161 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13162 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13163 13164 if (!AddRec) 13165 return nullptr; 13166 13167 // Since the transformation was successful, we can now transfer the SCEV 13168 // predicates. 13169 for (auto *P : TransformPreds) 13170 Preds.insert(P); 13171 13172 return AddRec; 13173 } 13174 13175 /// SCEV predicates 13176 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13177 SCEVPredicateKind Kind) 13178 : FastID(ID), Kind(Kind) {} 13179 13180 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13181 const SCEV *LHS, const SCEV *RHS) 13182 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13183 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13184 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13185 } 13186 13187 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13188 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13189 13190 if (!Op) 13191 return false; 13192 13193 return Op->LHS == LHS && Op->RHS == RHS; 13194 } 13195 13196 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13197 13198 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13199 13200 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13201 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13202 } 13203 13204 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13205 const SCEVAddRecExpr *AR, 13206 IncrementWrapFlags Flags) 13207 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13208 13209 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13210 13211 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13212 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13213 13214 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13215 } 13216 13217 bool SCEVWrapPredicate::isAlwaysTrue() const { 13218 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13219 IncrementWrapFlags IFlags = Flags; 13220 13221 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13222 IFlags = clearFlags(IFlags, IncrementNSSW); 13223 13224 return IFlags == IncrementAnyWrap; 13225 } 13226 13227 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13228 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13229 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13230 OS << "<nusw>"; 13231 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13232 OS << "<nssw>"; 13233 OS << "\n"; 13234 } 13235 13236 SCEVWrapPredicate::IncrementWrapFlags 13237 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13238 ScalarEvolution &SE) { 13239 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13240 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13241 13242 // We can safely transfer the NSW flag as NSSW. 13243 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13244 ImpliedFlags = IncrementNSSW; 13245 13246 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13247 // If the increment is positive, the SCEV NUW flag will also imply the 13248 // WrapPredicate NUSW flag. 13249 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13250 if (Step->getValue()->getValue().isNonNegative()) 13251 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13252 } 13253 13254 return ImpliedFlags; 13255 } 13256 13257 /// Union predicates don't get cached so create a dummy set ID for it. 13258 SCEVUnionPredicate::SCEVUnionPredicate() 13259 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13260 13261 bool SCEVUnionPredicate::isAlwaysTrue() const { 13262 return all_of(Preds, 13263 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13264 } 13265 13266 ArrayRef<const SCEVPredicate *> 13267 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13268 auto I = SCEVToPreds.find(Expr); 13269 if (I == SCEVToPreds.end()) 13270 return ArrayRef<const SCEVPredicate *>(); 13271 return I->second; 13272 } 13273 13274 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13275 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13276 return all_of(Set->Preds, 13277 [this](const SCEVPredicate *I) { return this->implies(I); }); 13278 13279 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13280 if (ScevPredsIt == SCEVToPreds.end()) 13281 return false; 13282 auto &SCEVPreds = ScevPredsIt->second; 13283 13284 return any_of(SCEVPreds, 13285 [N](const SCEVPredicate *I) { return I->implies(N); }); 13286 } 13287 13288 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13289 13290 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13291 for (auto Pred : Preds) 13292 Pred->print(OS, Depth); 13293 } 13294 13295 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13296 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13297 for (auto Pred : Set->Preds) 13298 add(Pred); 13299 return; 13300 } 13301 13302 if (implies(N)) 13303 return; 13304 13305 const SCEV *Key = N->getExpr(); 13306 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13307 " associated expression!"); 13308 13309 SCEVToPreds[Key].push_back(N); 13310 Preds.push_back(N); 13311 } 13312 13313 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13314 Loop &L) 13315 : SE(SE), L(L) {} 13316 13317 void ScalarEvolution::registerUser(const SCEV *User, 13318 ArrayRef<const SCEV *> Ops) { 13319 for (auto *Op : Ops) 13320 // We do not expect that forgetting cached data for SCEVConstants will ever 13321 // open any prospects for sharpening or introduce any correctness issues, 13322 // so we don't bother storing their dependencies. 13323 if (!isa<SCEVConstant>(Op)) 13324 SCEVUsers[Op].insert(User); 13325 } 13326 13327 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13328 const SCEV *Expr = SE.getSCEV(V); 13329 RewriteEntry &Entry = RewriteMap[Expr]; 13330 13331 // If we already have an entry and the version matches, return it. 13332 if (Entry.second && Generation == Entry.first) 13333 return Entry.second; 13334 13335 // We found an entry but it's stale. Rewrite the stale entry 13336 // according to the current predicate. 13337 if (Entry.second) 13338 Expr = Entry.second; 13339 13340 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13341 Entry = {Generation, NewSCEV}; 13342 13343 return NewSCEV; 13344 } 13345 13346 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13347 if (!BackedgeCount) { 13348 SCEVUnionPredicate BackedgePred; 13349 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13350 addPredicate(BackedgePred); 13351 } 13352 return BackedgeCount; 13353 } 13354 13355 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13356 if (Preds.implies(&Pred)) 13357 return; 13358 Preds.add(&Pred); 13359 updateGeneration(); 13360 } 13361 13362 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13363 return Preds; 13364 } 13365 13366 void PredicatedScalarEvolution::updateGeneration() { 13367 // If the generation number wrapped recompute everything. 13368 if (++Generation == 0) { 13369 for (auto &II : RewriteMap) { 13370 const SCEV *Rewritten = II.second.second; 13371 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13372 } 13373 } 13374 } 13375 13376 void PredicatedScalarEvolution::setNoOverflow( 13377 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13378 const SCEV *Expr = getSCEV(V); 13379 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13380 13381 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13382 13383 // Clear the statically implied flags. 13384 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13385 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13386 13387 auto II = FlagsMap.insert({V, Flags}); 13388 if (!II.second) 13389 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13390 } 13391 13392 bool PredicatedScalarEvolution::hasNoOverflow( 13393 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13394 const SCEV *Expr = getSCEV(V); 13395 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13396 13397 Flags = SCEVWrapPredicate::clearFlags( 13398 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13399 13400 auto II = FlagsMap.find(V); 13401 13402 if (II != FlagsMap.end()) 13403 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13404 13405 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13406 } 13407 13408 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13409 const SCEV *Expr = this->getSCEV(V); 13410 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13411 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13412 13413 if (!New) 13414 return nullptr; 13415 13416 for (auto *P : NewPreds) 13417 Preds.add(P); 13418 13419 updateGeneration(); 13420 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13421 return New; 13422 } 13423 13424 PredicatedScalarEvolution::PredicatedScalarEvolution( 13425 const PredicatedScalarEvolution &Init) 13426 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13427 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13428 for (auto I : Init.FlagsMap) 13429 FlagsMap.insert(I); 13430 } 13431 13432 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13433 // For each block. 13434 for (auto *BB : L.getBlocks()) 13435 for (auto &I : *BB) { 13436 if (!SE.isSCEVable(I.getType())) 13437 continue; 13438 13439 auto *Expr = SE.getSCEV(&I); 13440 auto II = RewriteMap.find(Expr); 13441 13442 if (II == RewriteMap.end()) 13443 continue; 13444 13445 // Don't print things that are not interesting. 13446 if (II->second.second == Expr) 13447 continue; 13448 13449 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13450 OS.indent(Depth + 2) << *Expr << "\n"; 13451 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13452 } 13453 } 13454 13455 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13456 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13457 // for URem with constant power-of-2 second operands. 13458 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13459 // 4, A / B becomes X / 8). 13460 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13461 const SCEV *&RHS) { 13462 // Try to match 'zext (trunc A to iB) to iY', which is used 13463 // for URem with constant power-of-2 second operands. Make sure the size of 13464 // the operand A matches the size of the whole expressions. 13465 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13466 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13467 LHS = Trunc->getOperand(); 13468 // Bail out if the type of the LHS is larger than the type of the 13469 // expression for now. 13470 if (getTypeSizeInBits(LHS->getType()) > 13471 getTypeSizeInBits(Expr->getType())) 13472 return false; 13473 if (LHS->getType() != Expr->getType()) 13474 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13475 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13476 << getTypeSizeInBits(Trunc->getType())); 13477 return true; 13478 } 13479 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13480 if (Add == nullptr || Add->getNumOperands() != 2) 13481 return false; 13482 13483 const SCEV *A = Add->getOperand(1); 13484 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13485 13486 if (Mul == nullptr) 13487 return false; 13488 13489 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13490 // (SomeExpr + (-(SomeExpr / B) * B)). 13491 if (Expr == getURemExpr(A, B)) { 13492 LHS = A; 13493 RHS = B; 13494 return true; 13495 } 13496 return false; 13497 }; 13498 13499 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13500 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13501 return MatchURemWithDivisor(Mul->getOperand(1)) || 13502 MatchURemWithDivisor(Mul->getOperand(2)); 13503 13504 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13505 if (Mul->getNumOperands() == 2) 13506 return MatchURemWithDivisor(Mul->getOperand(1)) || 13507 MatchURemWithDivisor(Mul->getOperand(0)) || 13508 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13509 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13510 return false; 13511 } 13512 13513 const SCEV * 13514 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13515 SmallVector<BasicBlock*, 16> ExitingBlocks; 13516 L->getExitingBlocks(ExitingBlocks); 13517 13518 // Form an expression for the maximum exit count possible for this loop. We 13519 // merge the max and exact information to approximate a version of 13520 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13521 SmallVector<const SCEV*, 4> ExitCounts; 13522 for (BasicBlock *ExitingBB : ExitingBlocks) { 13523 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13524 if (isa<SCEVCouldNotCompute>(ExitCount)) 13525 ExitCount = getExitCount(L, ExitingBB, 13526 ScalarEvolution::ConstantMaximum); 13527 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13528 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13529 "We should only have known counts for exiting blocks that " 13530 "dominate latch!"); 13531 ExitCounts.push_back(ExitCount); 13532 } 13533 } 13534 if (ExitCounts.empty()) 13535 return getCouldNotCompute(); 13536 return getUMinFromMismatchedTypes(ExitCounts); 13537 } 13538 13539 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13540 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13541 /// we cannot guarantee that the replacement is loop invariant in the loop of 13542 /// the AddRec. 13543 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13544 ValueToSCEVMapTy ⤅ 13545 13546 public: 13547 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13548 : SCEVRewriteVisitor(SE), Map(M) {} 13549 13550 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13551 13552 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13553 auto I = Map.find(Expr->getValue()); 13554 if (I == Map.end()) 13555 return Expr; 13556 return I->second; 13557 } 13558 }; 13559 13560 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13561 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13562 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13563 // WARNING: It is generally unsound to apply any wrap flags to the proposed 13564 // replacement SCEV which isn't directly implied by the structure of that 13565 // SCEV. In particular, using contextual facts to imply flags is *NOT* 13566 // legal. See the scoping rules for flags in the header to understand why. 13567 13568 // If we have LHS == 0, check if LHS is computing a property of some unknown 13569 // SCEV %v which we can rewrite %v to express explicitly. 13570 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13571 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13572 RHSC->getValue()->isNullValue()) { 13573 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13574 // explicitly express that. 13575 const SCEV *URemLHS = nullptr; 13576 const SCEV *URemRHS = nullptr; 13577 if (matchURem(LHS, URemLHS, URemRHS)) { 13578 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13579 Value *V = LHSUnknown->getValue(); 13580 RewriteMap[V] = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 13581 return; 13582 } 13583 } 13584 } 13585 13586 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13587 std::swap(LHS, RHS); 13588 Predicate = CmpInst::getSwappedPredicate(Predicate); 13589 } 13590 13591 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13592 // create this form when combining two checks of the form (X u< C2 + C1) and 13593 // (X >=u C1). 13594 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13595 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13596 if (!AddExpr || AddExpr->getNumOperands() != 2) 13597 return false; 13598 13599 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13600 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13601 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13602 if (!C1 || !C2 || !LHSUnknown) 13603 return false; 13604 13605 auto ExactRegion = 13606 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13607 .sub(C1->getAPInt()); 13608 13609 // Bail out, unless we have a non-wrapping, monotonic range. 13610 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13611 return false; 13612 auto I = RewriteMap.find(LHSUnknown->getValue()); 13613 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13614 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13615 getConstant(ExactRegion.getUnsignedMin()), 13616 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13617 return true; 13618 }; 13619 if (MatchRangeCheckIdiom()) 13620 return; 13621 13622 // For now, limit to conditions that provide information about unknown 13623 // expressions. RHS also cannot contain add recurrences. 13624 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13625 if (!LHSUnknown || containsAddRecurrence(RHS)) 13626 return; 13627 13628 // Check whether LHS has already been rewritten. In that case we want to 13629 // chain further rewrites onto the already rewritten value. 13630 auto I = RewriteMap.find(LHSUnknown->getValue()); 13631 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13632 const SCEV *RewrittenRHS = nullptr; 13633 switch (Predicate) { 13634 case CmpInst::ICMP_ULT: 13635 RewrittenRHS = 13636 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13637 break; 13638 case CmpInst::ICMP_SLT: 13639 RewrittenRHS = 13640 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13641 break; 13642 case CmpInst::ICMP_ULE: 13643 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13644 break; 13645 case CmpInst::ICMP_SLE: 13646 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13647 break; 13648 case CmpInst::ICMP_UGT: 13649 RewrittenRHS = 13650 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13651 break; 13652 case CmpInst::ICMP_SGT: 13653 RewrittenRHS = 13654 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13655 break; 13656 case CmpInst::ICMP_UGE: 13657 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13658 break; 13659 case CmpInst::ICMP_SGE: 13660 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13661 break; 13662 case CmpInst::ICMP_EQ: 13663 if (isa<SCEVConstant>(RHS)) 13664 RewrittenRHS = RHS; 13665 break; 13666 case CmpInst::ICMP_NE: 13667 if (isa<SCEVConstant>(RHS) && 13668 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13669 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13670 break; 13671 default: 13672 break; 13673 } 13674 13675 if (RewrittenRHS) 13676 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13677 }; 13678 // Starting at the loop predecessor, climb up the predecessor chain, as long 13679 // as there are predecessors that can be found that have unique successors 13680 // leading to the original header. 13681 // TODO: share this logic with isLoopEntryGuardedByCond. 13682 ValueToSCEVMapTy RewriteMap; 13683 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13684 L->getLoopPredecessor(), L->getHeader()); 13685 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13686 13687 const BranchInst *LoopEntryPredicate = 13688 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13689 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13690 continue; 13691 13692 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13693 SmallVector<Value *, 8> Worklist; 13694 SmallPtrSet<Value *, 8> Visited; 13695 Worklist.push_back(LoopEntryPredicate->getCondition()); 13696 while (!Worklist.empty()) { 13697 Value *Cond = Worklist.pop_back_val(); 13698 if (!Visited.insert(Cond).second) 13699 continue; 13700 13701 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13702 auto Predicate = 13703 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13704 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13705 getSCEV(Cmp->getOperand(1)), RewriteMap); 13706 continue; 13707 } 13708 13709 Value *L, *R; 13710 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13711 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13712 Worklist.push_back(L); 13713 Worklist.push_back(R); 13714 } 13715 } 13716 } 13717 13718 // Also collect information from assumptions dominating the loop. 13719 for (auto &AssumeVH : AC.assumptions()) { 13720 if (!AssumeVH) 13721 continue; 13722 auto *AssumeI = cast<CallInst>(AssumeVH); 13723 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13724 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13725 continue; 13726 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13727 getSCEV(Cmp->getOperand(1)), RewriteMap); 13728 } 13729 13730 if (RewriteMap.empty()) 13731 return Expr; 13732 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13733 return Rewriter.visit(Expr); 13734 } 13735