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 registerUser(S, Op); 1102 return S; 1103 } 1104 1105 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1106 "non-SCEVUnknown's."); 1107 1108 // Otherwise, we've got some expression that is more complex than just a 1109 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1110 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1111 // only, and the expressions must otherwise be integer-typed. 1112 // So sink the cast down to the SCEVUnknown's. 1113 1114 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1115 /// which computes a pointer-typed value, and rewrites the whole expression 1116 /// tree so that *all* the computations are done on integers, and the only 1117 /// pointer-typed operands in the expression are SCEVUnknown. 1118 class SCEVPtrToIntSinkingRewriter 1119 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1120 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1121 1122 public: 1123 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1124 1125 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1126 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1127 return Rewriter.visit(Scev); 1128 } 1129 1130 const SCEV *visit(const SCEV *S) { 1131 Type *STy = S->getType(); 1132 // If the expression is not pointer-typed, just keep it as-is. 1133 if (!STy->isPointerTy()) 1134 return S; 1135 // Else, recursively sink the cast down into it. 1136 return Base::visit(S); 1137 } 1138 1139 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1140 SmallVector<const SCEV *, 2> Operands; 1141 bool Changed = false; 1142 for (auto *Op : Expr->operands()) { 1143 Operands.push_back(visit(Op)); 1144 Changed |= Op != Operands.back(); 1145 } 1146 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1147 } 1148 1149 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1150 SmallVector<const SCEV *, 2> Operands; 1151 bool Changed = false; 1152 for (auto *Op : Expr->operands()) { 1153 Operands.push_back(visit(Op)); 1154 Changed |= Op != Operands.back(); 1155 } 1156 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1157 } 1158 1159 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1160 assert(Expr->getType()->isPointerTy() && 1161 "Should only reach pointer-typed SCEVUnknown's."); 1162 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1163 } 1164 }; 1165 1166 // And actually perform the cast sinking. 1167 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1168 assert(IntOp->getType()->isIntegerTy() && 1169 "We must have succeeded in sinking the cast, " 1170 "and ending up with an integer-typed expression!"); 1171 return IntOp; 1172 } 1173 1174 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1175 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1176 1177 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1178 if (isa<SCEVCouldNotCompute>(IntOp)) 1179 return IntOp; 1180 1181 return getTruncateOrZeroExtend(IntOp, Ty); 1182 } 1183 1184 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1185 unsigned Depth) { 1186 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1187 "This is not a truncating conversion!"); 1188 assert(isSCEVable(Ty) && 1189 "This is not a conversion to a SCEVable type!"); 1190 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1191 Ty = getEffectiveSCEVType(Ty); 1192 1193 FoldingSetNodeID ID; 1194 ID.AddInteger(scTruncate); 1195 ID.AddPointer(Op); 1196 ID.AddPointer(Ty); 1197 void *IP = nullptr; 1198 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1199 1200 // Fold if the operand is constant. 1201 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1202 return getConstant( 1203 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1204 1205 // trunc(trunc(x)) --> trunc(x) 1206 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1207 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1208 1209 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1210 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1211 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1212 1213 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1214 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1215 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1216 1217 if (Depth > MaxCastDepth) { 1218 SCEV *S = 1219 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1220 UniqueSCEVs.InsertNode(S, IP); 1221 registerUser(S, Op); 1222 return S; 1223 } 1224 1225 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1226 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1227 // if after transforming we have at most one truncate, not counting truncates 1228 // that replace other casts. 1229 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1230 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1231 SmallVector<const SCEV *, 4> Operands; 1232 unsigned numTruncs = 0; 1233 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1234 ++i) { 1235 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1236 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1237 isa<SCEVTruncateExpr>(S)) 1238 numTruncs++; 1239 Operands.push_back(S); 1240 } 1241 if (numTruncs < 2) { 1242 if (isa<SCEVAddExpr>(Op)) 1243 return getAddExpr(Operands); 1244 else if (isa<SCEVMulExpr>(Op)) 1245 return getMulExpr(Operands); 1246 else 1247 llvm_unreachable("Unexpected SCEV type for Op."); 1248 } 1249 // Although we checked in the beginning that ID is not in the cache, it is 1250 // possible that during recursion and different modification ID was inserted 1251 // into the cache. So if we find it, just return it. 1252 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1253 return S; 1254 } 1255 1256 // If the input value is a chrec scev, truncate the chrec's operands. 1257 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1258 SmallVector<const SCEV *, 4> Operands; 1259 for (const SCEV *Op : AddRec->operands()) 1260 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1261 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1262 } 1263 1264 // Return zero if truncating to known zeros. 1265 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1266 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1267 return getZero(Ty); 1268 1269 // The cast wasn't folded; create an explicit cast node. We can reuse 1270 // the existing insert position since if we get here, we won't have 1271 // made any changes which would invalidate it. 1272 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1273 Op, Ty); 1274 UniqueSCEVs.InsertNode(S, IP); 1275 registerUser(S, Op); 1276 return S; 1277 } 1278 1279 // Get the limit of a recurrence such that incrementing by Step cannot cause 1280 // signed overflow as long as the value of the recurrence within the 1281 // loop does not exceed this limit before incrementing. 1282 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1283 ICmpInst::Predicate *Pred, 1284 ScalarEvolution *SE) { 1285 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1286 if (SE->isKnownPositive(Step)) { 1287 *Pred = ICmpInst::ICMP_SLT; 1288 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1289 SE->getSignedRangeMax(Step)); 1290 } 1291 if (SE->isKnownNegative(Step)) { 1292 *Pred = ICmpInst::ICMP_SGT; 1293 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1294 SE->getSignedRangeMin(Step)); 1295 } 1296 return nullptr; 1297 } 1298 1299 // Get the limit of a recurrence such that incrementing by Step cannot cause 1300 // unsigned overflow as long as the value of the recurrence within the loop does 1301 // not exceed this limit before incrementing. 1302 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1303 ICmpInst::Predicate *Pred, 1304 ScalarEvolution *SE) { 1305 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1306 *Pred = ICmpInst::ICMP_ULT; 1307 1308 return SE->getConstant(APInt::getMinValue(BitWidth) - 1309 SE->getUnsignedRangeMax(Step)); 1310 } 1311 1312 namespace { 1313 1314 struct ExtendOpTraitsBase { 1315 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1316 unsigned); 1317 }; 1318 1319 // Used to make code generic over signed and unsigned overflow. 1320 template <typename ExtendOp> struct ExtendOpTraits { 1321 // Members present: 1322 // 1323 // static const SCEV::NoWrapFlags WrapType; 1324 // 1325 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1326 // 1327 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1328 // ICmpInst::Predicate *Pred, 1329 // ScalarEvolution *SE); 1330 }; 1331 1332 template <> 1333 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1334 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1335 1336 static const GetExtendExprTy GetExtendExpr; 1337 1338 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1339 ICmpInst::Predicate *Pred, 1340 ScalarEvolution *SE) { 1341 return getSignedOverflowLimitForStep(Step, Pred, SE); 1342 } 1343 }; 1344 1345 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1346 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1347 1348 template <> 1349 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1350 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1351 1352 static const GetExtendExprTy GetExtendExpr; 1353 1354 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1355 ICmpInst::Predicate *Pred, 1356 ScalarEvolution *SE) { 1357 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1358 } 1359 }; 1360 1361 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1362 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1363 1364 } // end anonymous namespace 1365 1366 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1367 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1368 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1369 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1370 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1371 // expression "Step + sext/zext(PreIncAR)" is congruent with 1372 // "sext/zext(PostIncAR)" 1373 template <typename ExtendOpTy> 1374 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1375 ScalarEvolution *SE, unsigned Depth) { 1376 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1377 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1378 1379 const Loop *L = AR->getLoop(); 1380 const SCEV *Start = AR->getStart(); 1381 const SCEV *Step = AR->getStepRecurrence(*SE); 1382 1383 // Check for a simple looking step prior to loop entry. 1384 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1385 if (!SA) 1386 return nullptr; 1387 1388 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1389 // subtraction is expensive. For this purpose, perform a quick and dirty 1390 // difference, by checking for Step in the operand list. 1391 SmallVector<const SCEV *, 4> DiffOps; 1392 for (const SCEV *Op : SA->operands()) 1393 if (Op != Step) 1394 DiffOps.push_back(Op); 1395 1396 if (DiffOps.size() == SA->getNumOperands()) 1397 return nullptr; 1398 1399 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1400 // `Step`: 1401 1402 // 1. NSW/NUW flags on the step increment. 1403 auto PreStartFlags = 1404 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1405 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1406 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1407 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1408 1409 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1410 // "S+X does not sign/unsign-overflow". 1411 // 1412 1413 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1414 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1415 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1416 return PreStart; 1417 1418 // 2. Direct overflow check on the step operation's expression. 1419 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1420 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1421 const SCEV *OperandExtendedStart = 1422 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1423 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1424 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1425 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1426 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1427 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1428 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1429 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1430 } 1431 return PreStart; 1432 } 1433 1434 // 3. Loop precondition. 1435 ICmpInst::Predicate Pred; 1436 const SCEV *OverflowLimit = 1437 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1438 1439 if (OverflowLimit && 1440 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1441 return PreStart; 1442 1443 return nullptr; 1444 } 1445 1446 // Get the normalized zero or sign extended expression for this AddRec's Start. 1447 template <typename ExtendOpTy> 1448 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1449 ScalarEvolution *SE, 1450 unsigned Depth) { 1451 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1452 1453 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1454 if (!PreStart) 1455 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1456 1457 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1458 Depth), 1459 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1460 } 1461 1462 // Try to prove away overflow by looking at "nearby" add recurrences. A 1463 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1464 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1465 // 1466 // Formally: 1467 // 1468 // {S,+,X} == {S-T,+,X} + T 1469 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1470 // 1471 // If ({S-T,+,X} + T) does not overflow ... (1) 1472 // 1473 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1474 // 1475 // If {S-T,+,X} does not overflow ... (2) 1476 // 1477 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1478 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1479 // 1480 // If (S-T)+T does not overflow ... (3) 1481 // 1482 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1483 // == {Ext(S),+,Ext(X)} == LHS 1484 // 1485 // Thus, if (1), (2) and (3) are true for some T, then 1486 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1487 // 1488 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1489 // does not overflow" restricted to the 0th iteration. Therefore we only need 1490 // to check for (1) and (2). 1491 // 1492 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1493 // is `Delta` (defined below). 1494 template <typename ExtendOpTy> 1495 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1496 const SCEV *Step, 1497 const Loop *L) { 1498 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1499 1500 // We restrict `Start` to a constant to prevent SCEV from spending too much 1501 // time here. It is correct (but more expensive) to continue with a 1502 // non-constant `Start` and do a general SCEV subtraction to compute 1503 // `PreStart` below. 1504 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1505 if (!StartC) 1506 return false; 1507 1508 APInt StartAI = StartC->getAPInt(); 1509 1510 for (unsigned Delta : {-2, -1, 1, 2}) { 1511 const SCEV *PreStart = getConstant(StartAI - Delta); 1512 1513 FoldingSetNodeID ID; 1514 ID.AddInteger(scAddRecExpr); 1515 ID.AddPointer(PreStart); 1516 ID.AddPointer(Step); 1517 ID.AddPointer(L); 1518 void *IP = nullptr; 1519 const auto *PreAR = 1520 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1521 1522 // Give up if we don't already have the add recurrence we need because 1523 // actually constructing an add recurrence is relatively expensive. 1524 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1525 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1526 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1527 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1528 DeltaS, &Pred, this); 1529 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1530 return true; 1531 } 1532 } 1533 1534 return false; 1535 } 1536 1537 // Finds an integer D for an expression (C + x + y + ...) such that the top 1538 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1539 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1540 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1541 // the (C + x + y + ...) expression is \p WholeAddExpr. 1542 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1543 const SCEVConstant *ConstantTerm, 1544 const SCEVAddExpr *WholeAddExpr) { 1545 const APInt &C = ConstantTerm->getAPInt(); 1546 const unsigned BitWidth = C.getBitWidth(); 1547 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1548 uint32_t TZ = BitWidth; 1549 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1550 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1551 if (TZ) { 1552 // Set D to be as many least significant bits of C as possible while still 1553 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1554 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1555 } 1556 return APInt(BitWidth, 0); 1557 } 1558 1559 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1560 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1561 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1562 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1563 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1564 const APInt &ConstantStart, 1565 const SCEV *Step) { 1566 const unsigned BitWidth = ConstantStart.getBitWidth(); 1567 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1568 if (TZ) 1569 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1570 : ConstantStart; 1571 return APInt(BitWidth, 0); 1572 } 1573 1574 const SCEV * 1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1576 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1577 "This is not an extending conversion!"); 1578 assert(isSCEVable(Ty) && 1579 "This is not a conversion to a SCEVable type!"); 1580 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1581 Ty = getEffectiveSCEVType(Ty); 1582 1583 // Fold if the operand is constant. 1584 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1585 return getConstant( 1586 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1587 1588 // zext(zext(x)) --> zext(x) 1589 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1590 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1591 1592 // Before doing any expensive analysis, check to see if we've already 1593 // computed a SCEV for this Op and Ty. 1594 FoldingSetNodeID ID; 1595 ID.AddInteger(scZeroExtend); 1596 ID.AddPointer(Op); 1597 ID.AddPointer(Ty); 1598 void *IP = nullptr; 1599 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1600 if (Depth > MaxCastDepth) { 1601 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1602 Op, Ty); 1603 UniqueSCEVs.InsertNode(S, IP); 1604 registerUser(S, Op); 1605 return S; 1606 } 1607 1608 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1609 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1610 // It's possible the bits taken off by the truncate were all zero bits. If 1611 // so, we should be able to simplify this further. 1612 const SCEV *X = ST->getOperand(); 1613 ConstantRange CR = getUnsignedRange(X); 1614 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1615 unsigned NewBits = getTypeSizeInBits(Ty); 1616 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1617 CR.zextOrTrunc(NewBits))) 1618 return getTruncateOrZeroExtend(X, Ty, Depth); 1619 } 1620 1621 // If the input value is a chrec scev, and we can prove that the value 1622 // did not overflow the old, smaller, value, we can zero extend all of the 1623 // operands (often constants). This allows analysis of something like 1624 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1625 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1626 if (AR->isAffine()) { 1627 const SCEV *Start = AR->getStart(); 1628 const SCEV *Step = AR->getStepRecurrence(*this); 1629 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1630 const Loop *L = AR->getLoop(); 1631 1632 if (!AR->hasNoUnsignedWrap()) { 1633 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1634 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1635 } 1636 1637 // If we have special knowledge that this addrec won't overflow, 1638 // we don't need to do any further analysis. 1639 if (AR->hasNoUnsignedWrap()) 1640 return getAddRecExpr( 1641 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1642 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1643 1644 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1645 // Note that this serves two purposes: It filters out loops that are 1646 // simply not analyzable, and it covers the case where this code is 1647 // being called from within backedge-taken count analysis, such that 1648 // attempting to ask for the backedge-taken count would likely result 1649 // in infinite recursion. In the later case, the analysis code will 1650 // cope with a conservative value, and it will take care to purge 1651 // that value once it has finished. 1652 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1653 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1654 // Manually compute the final value for AR, checking for overflow. 1655 1656 // Check whether the backedge-taken count can be losslessly casted to 1657 // the addrec's type. The count is always unsigned. 1658 const SCEV *CastedMaxBECount = 1659 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1660 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1661 CastedMaxBECount, MaxBECount->getType(), Depth); 1662 if (MaxBECount == RecastedMaxBECount) { 1663 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1664 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1665 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1666 SCEV::FlagAnyWrap, Depth + 1); 1667 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1668 SCEV::FlagAnyWrap, 1669 Depth + 1), 1670 WideTy, Depth + 1); 1671 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1672 const SCEV *WideMaxBECount = 1673 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1674 const SCEV *OperandExtendedAdd = 1675 getAddExpr(WideStart, 1676 getMulExpr(WideMaxBECount, 1677 getZeroExtendExpr(Step, WideTy, Depth + 1), 1678 SCEV::FlagAnyWrap, Depth + 1), 1679 SCEV::FlagAnyWrap, Depth + 1); 1680 if (ZAdd == OperandExtendedAdd) { 1681 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1682 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1683 // Return the expression with the addrec on the outside. 1684 return getAddRecExpr( 1685 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1686 Depth + 1), 1687 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1688 AR->getNoWrapFlags()); 1689 } 1690 // Similar to above, only this time treat the step value as signed. 1691 // This covers loops that count down. 1692 OperandExtendedAdd = 1693 getAddExpr(WideStart, 1694 getMulExpr(WideMaxBECount, 1695 getSignExtendExpr(Step, WideTy, Depth + 1), 1696 SCEV::FlagAnyWrap, Depth + 1), 1697 SCEV::FlagAnyWrap, Depth + 1); 1698 if (ZAdd == OperandExtendedAdd) { 1699 // Cache knowledge of AR NW, which is propagated to this AddRec. 1700 // Negative step causes unsigned wrap, but it still can't self-wrap. 1701 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1702 // Return the expression with the addrec on the outside. 1703 return getAddRecExpr( 1704 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1705 Depth + 1), 1706 getSignExtendExpr(Step, Ty, Depth + 1), L, 1707 AR->getNoWrapFlags()); 1708 } 1709 } 1710 } 1711 1712 // Normally, in the cases we can prove no-overflow via a 1713 // backedge guarding condition, we can also compute a backedge 1714 // taken count for the loop. The exceptions are assumptions and 1715 // guards present in the loop -- SCEV is not great at exploiting 1716 // these to compute max backedge taken counts, but can still use 1717 // these to prove lack of overflow. Use this fact to avoid 1718 // doing extra work that may not pay off. 1719 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1720 !AC.assumptions().empty()) { 1721 1722 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1723 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1724 if (AR->hasNoUnsignedWrap()) { 1725 // Same as nuw case above - duplicated here to avoid a compile time 1726 // issue. It's not clear that the order of checks does matter, but 1727 // it's one of two issue possible causes for a change which was 1728 // reverted. Be conservative for the moment. 1729 return getAddRecExpr( 1730 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1731 Depth + 1), 1732 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1733 AR->getNoWrapFlags()); 1734 } 1735 1736 // For a negative step, we can extend the operands iff doing so only 1737 // traverses values in the range zext([0,UINT_MAX]). 1738 if (isKnownNegative(Step)) { 1739 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1740 getSignedRangeMin(Step)); 1741 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1742 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1743 // Cache knowledge of AR NW, which is propagated to this 1744 // AddRec. Negative step causes unsigned wrap, but it 1745 // still can't self-wrap. 1746 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1747 // Return the expression with the addrec on the outside. 1748 return getAddRecExpr( 1749 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1750 Depth + 1), 1751 getSignExtendExpr(Step, Ty, Depth + 1), L, 1752 AR->getNoWrapFlags()); 1753 } 1754 } 1755 } 1756 1757 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1758 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1759 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1760 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1761 const APInt &C = SC->getAPInt(); 1762 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1763 if (D != 0) { 1764 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1765 const SCEV *SResidual = 1766 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1767 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1768 return getAddExpr(SZExtD, SZExtR, 1769 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1770 Depth + 1); 1771 } 1772 } 1773 1774 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1775 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1776 return getAddRecExpr( 1777 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1778 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1779 } 1780 } 1781 1782 // zext(A % B) --> zext(A) % zext(B) 1783 { 1784 const SCEV *LHS; 1785 const SCEV *RHS; 1786 if (matchURem(Op, LHS, RHS)) 1787 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1788 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1789 } 1790 1791 // zext(A / B) --> zext(A) / zext(B). 1792 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1793 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1794 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1795 1796 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1797 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1798 if (SA->hasNoUnsignedWrap()) { 1799 // If the addition does not unsign overflow then we can, by definition, 1800 // commute the zero extension with the addition operation. 1801 SmallVector<const SCEV *, 4> Ops; 1802 for (const auto *Op : SA->operands()) 1803 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1804 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1805 } 1806 1807 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1808 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1809 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1810 // 1811 // Often address arithmetics contain expressions like 1812 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1813 // This transformation is useful while proving that such expressions are 1814 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1815 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1816 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1817 if (D != 0) { 1818 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1819 const SCEV *SResidual = 1820 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1821 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1822 return getAddExpr(SZExtD, SZExtR, 1823 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1824 Depth + 1); 1825 } 1826 } 1827 } 1828 1829 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1830 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1831 if (SM->hasNoUnsignedWrap()) { 1832 // If the multiply does not unsign overflow then we can, by definition, 1833 // commute the zero extension with the multiply operation. 1834 SmallVector<const SCEV *, 4> Ops; 1835 for (const auto *Op : SM->operands()) 1836 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1837 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1838 } 1839 1840 // zext(2^K * (trunc X to iN)) to iM -> 1841 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1842 // 1843 // Proof: 1844 // 1845 // zext(2^K * (trunc X to iN)) to iM 1846 // = zext((trunc X to iN) << K) to iM 1847 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1848 // (because shl removes the top K bits) 1849 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1850 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1851 // 1852 if (SM->getNumOperands() == 2) 1853 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1854 if (MulLHS->getAPInt().isPowerOf2()) 1855 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1856 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1857 MulLHS->getAPInt().logBase2(); 1858 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1859 return getMulExpr( 1860 getZeroExtendExpr(MulLHS, Ty), 1861 getZeroExtendExpr( 1862 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1863 SCEV::FlagNUW, Depth + 1); 1864 } 1865 } 1866 1867 // The cast wasn't folded; create an explicit cast node. 1868 // Recompute the insert position, as it may have been invalidated. 1869 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1870 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1871 Op, Ty); 1872 UniqueSCEVs.InsertNode(S, IP); 1873 registerUser(S, Op); 1874 return S; 1875 } 1876 1877 const SCEV * 1878 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1879 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1880 "This is not an extending conversion!"); 1881 assert(isSCEVable(Ty) && 1882 "This is not a conversion to a SCEVable type!"); 1883 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1884 Ty = getEffectiveSCEVType(Ty); 1885 1886 // Fold if the operand is constant. 1887 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1888 return getConstant( 1889 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1890 1891 // sext(sext(x)) --> sext(x) 1892 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1893 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1894 1895 // sext(zext(x)) --> zext(x) 1896 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1897 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1898 1899 // Before doing any expensive analysis, check to see if we've already 1900 // computed a SCEV for this Op and Ty. 1901 FoldingSetNodeID ID; 1902 ID.AddInteger(scSignExtend); 1903 ID.AddPointer(Op); 1904 ID.AddPointer(Ty); 1905 void *IP = nullptr; 1906 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1907 // Limit recursion depth. 1908 if (Depth > MaxCastDepth) { 1909 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1910 Op, Ty); 1911 UniqueSCEVs.InsertNode(S, IP); 1912 registerUser(S, Op); 1913 return S; 1914 } 1915 1916 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1917 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1918 // It's possible the bits taken off by the truncate were all sign bits. If 1919 // so, we should be able to simplify this further. 1920 const SCEV *X = ST->getOperand(); 1921 ConstantRange CR = getSignedRange(X); 1922 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1923 unsigned NewBits = getTypeSizeInBits(Ty); 1924 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1925 CR.sextOrTrunc(NewBits))) 1926 return getTruncateOrSignExtend(X, Ty, Depth); 1927 } 1928 1929 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1930 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1931 if (SA->hasNoSignedWrap()) { 1932 // If the addition does not sign overflow then we can, by definition, 1933 // commute the sign extension with the addition operation. 1934 SmallVector<const SCEV *, 4> Ops; 1935 for (const auto *Op : SA->operands()) 1936 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1937 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1938 } 1939 1940 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1941 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1942 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1943 // 1944 // For instance, this will bring two seemingly different expressions: 1945 // 1 + sext(5 + 20 * %x + 24 * %y) and 1946 // sext(6 + 20 * %x + 24 * %y) 1947 // to the same form: 1948 // 2 + sext(4 + 20 * %x + 24 * %y) 1949 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1950 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1951 if (D != 0) { 1952 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1953 const SCEV *SResidual = 1954 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1955 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1956 return getAddExpr(SSExtD, SSExtR, 1957 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1958 Depth + 1); 1959 } 1960 } 1961 } 1962 // If the input value is a chrec scev, and we can prove that the value 1963 // did not overflow the old, smaller, value, we can sign extend all of the 1964 // operands (often constants). This allows analysis of something like 1965 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1966 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1967 if (AR->isAffine()) { 1968 const SCEV *Start = AR->getStart(); 1969 const SCEV *Step = AR->getStepRecurrence(*this); 1970 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1971 const Loop *L = AR->getLoop(); 1972 1973 if (!AR->hasNoSignedWrap()) { 1974 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1975 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1976 } 1977 1978 // If we have special knowledge that this addrec won't overflow, 1979 // we don't need to do any further analysis. 1980 if (AR->hasNoSignedWrap()) 1981 return getAddRecExpr( 1982 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1983 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1984 1985 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1986 // Note that this serves two purposes: It filters out loops that are 1987 // simply not analyzable, and it covers the case where this code is 1988 // being called from within backedge-taken count analysis, such that 1989 // attempting to ask for the backedge-taken count would likely result 1990 // in infinite recursion. In the later case, the analysis code will 1991 // cope with a conservative value, and it will take care to purge 1992 // that value once it has finished. 1993 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1994 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1995 // Manually compute the final value for AR, checking for 1996 // overflow. 1997 1998 // Check whether the backedge-taken count can be losslessly casted to 1999 // the addrec's type. The count is always unsigned. 2000 const SCEV *CastedMaxBECount = 2001 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2002 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2003 CastedMaxBECount, MaxBECount->getType(), Depth); 2004 if (MaxBECount == RecastedMaxBECount) { 2005 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2006 // Check whether Start+Step*MaxBECount has no signed overflow. 2007 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2008 SCEV::FlagAnyWrap, Depth + 1); 2009 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2010 SCEV::FlagAnyWrap, 2011 Depth + 1), 2012 WideTy, Depth + 1); 2013 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2014 const SCEV *WideMaxBECount = 2015 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2016 const SCEV *OperandExtendedAdd = 2017 getAddExpr(WideStart, 2018 getMulExpr(WideMaxBECount, 2019 getSignExtendExpr(Step, WideTy, Depth + 1), 2020 SCEV::FlagAnyWrap, Depth + 1), 2021 SCEV::FlagAnyWrap, Depth + 1); 2022 if (SAdd == OperandExtendedAdd) { 2023 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2024 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2025 // Return the expression with the addrec on the outside. 2026 return getAddRecExpr( 2027 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2028 Depth + 1), 2029 getSignExtendExpr(Step, Ty, Depth + 1), L, 2030 AR->getNoWrapFlags()); 2031 } 2032 // Similar to above, only this time treat the step value as unsigned. 2033 // This covers loops that count up with an unsigned step. 2034 OperandExtendedAdd = 2035 getAddExpr(WideStart, 2036 getMulExpr(WideMaxBECount, 2037 getZeroExtendExpr(Step, WideTy, Depth + 1), 2038 SCEV::FlagAnyWrap, Depth + 1), 2039 SCEV::FlagAnyWrap, Depth + 1); 2040 if (SAdd == OperandExtendedAdd) { 2041 // If AR wraps around then 2042 // 2043 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2044 // => SAdd != OperandExtendedAdd 2045 // 2046 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2047 // (SAdd == OperandExtendedAdd => AR is NW) 2048 2049 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2050 2051 // Return the expression with the addrec on the outside. 2052 return getAddRecExpr( 2053 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2054 Depth + 1), 2055 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2056 AR->getNoWrapFlags()); 2057 } 2058 } 2059 } 2060 2061 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2062 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2063 if (AR->hasNoSignedWrap()) { 2064 // Same as nsw case above - duplicated here to avoid a compile time 2065 // issue. It's not clear that the order of checks does matter, but 2066 // it's one of two issue possible causes for a change which was 2067 // reverted. Be conservative for the moment. 2068 return getAddRecExpr( 2069 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2070 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2071 } 2072 2073 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2074 // if D + (C - D + Step * n) could be proven to not signed wrap 2075 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2076 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2077 const APInt &C = SC->getAPInt(); 2078 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2079 if (D != 0) { 2080 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2081 const SCEV *SResidual = 2082 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2083 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2084 return getAddExpr(SSExtD, SSExtR, 2085 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2086 Depth + 1); 2087 } 2088 } 2089 2090 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2091 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2092 return getAddRecExpr( 2093 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2094 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2095 } 2096 } 2097 2098 // If the input value is provably positive and we could not simplify 2099 // away the sext build a zext instead. 2100 if (isKnownNonNegative(Op)) 2101 return getZeroExtendExpr(Op, Ty, Depth + 1); 2102 2103 // The cast wasn't folded; create an explicit cast node. 2104 // Recompute the insert position, as it may have been invalidated. 2105 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2106 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2107 Op, Ty); 2108 UniqueSCEVs.InsertNode(S, IP); 2109 registerUser(S, { Op }); 2110 return S; 2111 } 2112 2113 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2114 /// unspecified bits out to the given type. 2115 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2116 Type *Ty) { 2117 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2118 "This is not an extending conversion!"); 2119 assert(isSCEVable(Ty) && 2120 "This is not a conversion to a SCEVable type!"); 2121 Ty = getEffectiveSCEVType(Ty); 2122 2123 // Sign-extend negative constants. 2124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2125 if (SC->getAPInt().isNegative()) 2126 return getSignExtendExpr(Op, Ty); 2127 2128 // Peel off a truncate cast. 2129 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2130 const SCEV *NewOp = T->getOperand(); 2131 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2132 return getAnyExtendExpr(NewOp, Ty); 2133 return getTruncateOrNoop(NewOp, Ty); 2134 } 2135 2136 // Next try a zext cast. If the cast is folded, use it. 2137 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2138 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2139 return ZExt; 2140 2141 // Next try a sext cast. If the cast is folded, use it. 2142 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2143 if (!isa<SCEVSignExtendExpr>(SExt)) 2144 return SExt; 2145 2146 // Force the cast to be folded into the operands of an addrec. 2147 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2148 SmallVector<const SCEV *, 4> Ops; 2149 for (const SCEV *Op : AR->operands()) 2150 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2151 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2152 } 2153 2154 // If the expression is obviously signed, use the sext cast value. 2155 if (isa<SCEVSMaxExpr>(Op)) 2156 return SExt; 2157 2158 // Absent any other information, use the zext cast value. 2159 return ZExt; 2160 } 2161 2162 /// Process the given Ops list, which is a list of operands to be added under 2163 /// the given scale, update the given map. This is a helper function for 2164 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2165 /// that would form an add expression like this: 2166 /// 2167 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2168 /// 2169 /// where A and B are constants, update the map with these values: 2170 /// 2171 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2172 /// 2173 /// and add 13 + A*B*29 to AccumulatedConstant. 2174 /// This will allow getAddRecExpr to produce this: 2175 /// 2176 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2177 /// 2178 /// This form often exposes folding opportunities that are hidden in 2179 /// the original operand list. 2180 /// 2181 /// Return true iff it appears that any interesting folding opportunities 2182 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2183 /// the common case where no interesting opportunities are present, and 2184 /// is also used as a check to avoid infinite recursion. 2185 static bool 2186 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2187 SmallVectorImpl<const SCEV *> &NewOps, 2188 APInt &AccumulatedConstant, 2189 const SCEV *const *Ops, size_t NumOperands, 2190 const APInt &Scale, 2191 ScalarEvolution &SE) { 2192 bool Interesting = false; 2193 2194 // Iterate over the add operands. They are sorted, with constants first. 2195 unsigned i = 0; 2196 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2197 ++i; 2198 // Pull a buried constant out to the outside. 2199 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2200 Interesting = true; 2201 AccumulatedConstant += Scale * C->getAPInt(); 2202 } 2203 2204 // Next comes everything else. We're especially interested in multiplies 2205 // here, but they're in the middle, so just visit the rest with one loop. 2206 for (; i != NumOperands; ++i) { 2207 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2208 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2209 APInt NewScale = 2210 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2211 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2212 // A multiplication of a constant with another add; recurse. 2213 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2214 Interesting |= 2215 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2216 Add->op_begin(), Add->getNumOperands(), 2217 NewScale, SE); 2218 } else { 2219 // A multiplication of a constant with some other value. Update 2220 // the map. 2221 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2222 const SCEV *Key = SE.getMulExpr(MulOps); 2223 auto Pair = M.insert({Key, NewScale}); 2224 if (Pair.second) { 2225 NewOps.push_back(Pair.first->first); 2226 } else { 2227 Pair.first->second += NewScale; 2228 // The map already had an entry for this value, which may indicate 2229 // a folding opportunity. 2230 Interesting = true; 2231 } 2232 } 2233 } else { 2234 // An ordinary operand. Update the map. 2235 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2236 M.insert({Ops[i], Scale}); 2237 if (Pair.second) { 2238 NewOps.push_back(Pair.first->first); 2239 } else { 2240 Pair.first->second += Scale; 2241 // The map already had an entry for this value, which may indicate 2242 // a folding opportunity. 2243 Interesting = true; 2244 } 2245 } 2246 } 2247 2248 return Interesting; 2249 } 2250 2251 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2252 const SCEV *LHS, const SCEV *RHS) { 2253 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2254 SCEV::NoWrapFlags, unsigned); 2255 switch (BinOp) { 2256 default: 2257 llvm_unreachable("Unsupported binary op"); 2258 case Instruction::Add: 2259 Operation = &ScalarEvolution::getAddExpr; 2260 break; 2261 case Instruction::Sub: 2262 Operation = &ScalarEvolution::getMinusSCEV; 2263 break; 2264 case Instruction::Mul: 2265 Operation = &ScalarEvolution::getMulExpr; 2266 break; 2267 } 2268 2269 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2270 Signed ? &ScalarEvolution::getSignExtendExpr 2271 : &ScalarEvolution::getZeroExtendExpr; 2272 2273 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2274 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2275 auto *WideTy = 2276 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2277 2278 const SCEV *A = (this->*Extension)( 2279 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2280 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2281 (this->*Extension)(RHS, WideTy, 0), 2282 SCEV::FlagAnyWrap, 0); 2283 return A == B; 2284 } 2285 2286 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2287 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2288 const OverflowingBinaryOperator *OBO) { 2289 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2290 2291 if (OBO->hasNoUnsignedWrap()) 2292 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2293 if (OBO->hasNoSignedWrap()) 2294 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2295 2296 bool Deduced = false; 2297 2298 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2299 return {Flags, Deduced}; 2300 2301 if (OBO->getOpcode() != Instruction::Add && 2302 OBO->getOpcode() != Instruction::Sub && 2303 OBO->getOpcode() != Instruction::Mul) 2304 return {Flags, Deduced}; 2305 2306 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2307 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2308 2309 if (!OBO->hasNoUnsignedWrap() && 2310 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2311 /* Signed */ false, LHS, RHS)) { 2312 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2313 Deduced = true; 2314 } 2315 2316 if (!OBO->hasNoSignedWrap() && 2317 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2318 /* Signed */ true, LHS, RHS)) { 2319 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2320 Deduced = true; 2321 } 2322 2323 return {Flags, Deduced}; 2324 } 2325 2326 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2327 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2328 // can't-overflow flags for the operation if possible. 2329 static SCEV::NoWrapFlags 2330 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2331 const ArrayRef<const SCEV *> Ops, 2332 SCEV::NoWrapFlags Flags) { 2333 using namespace std::placeholders; 2334 2335 using OBO = OverflowingBinaryOperator; 2336 2337 bool CanAnalyze = 2338 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2339 (void)CanAnalyze; 2340 assert(CanAnalyze && "don't call from other places!"); 2341 2342 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2343 SCEV::NoWrapFlags SignOrUnsignWrap = 2344 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2345 2346 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2347 auto IsKnownNonNegative = [&](const SCEV *S) { 2348 return SE->isKnownNonNegative(S); 2349 }; 2350 2351 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2352 Flags = 2353 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2354 2355 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2356 2357 if (SignOrUnsignWrap != SignOrUnsignMask && 2358 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2359 isa<SCEVConstant>(Ops[0])) { 2360 2361 auto Opcode = [&] { 2362 switch (Type) { 2363 case scAddExpr: 2364 return Instruction::Add; 2365 case scMulExpr: 2366 return Instruction::Mul; 2367 default: 2368 llvm_unreachable("Unexpected SCEV op."); 2369 } 2370 }(); 2371 2372 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2373 2374 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2375 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2376 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2377 Opcode, C, OBO::NoSignedWrap); 2378 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2379 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2380 } 2381 2382 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2383 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2384 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2385 Opcode, C, OBO::NoUnsignedWrap); 2386 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2387 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2388 } 2389 } 2390 2391 // <0,+,nonnegative><nw> is also nuw 2392 // TODO: Add corresponding nsw case 2393 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2394 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2395 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2396 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2397 2398 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2399 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2400 Ops.size() == 2) { 2401 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2402 if (UDiv->getOperand(1) == Ops[1]) 2403 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2404 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2405 if (UDiv->getOperand(1) == Ops[0]) 2406 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2407 } 2408 2409 return Flags; 2410 } 2411 2412 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2413 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2414 } 2415 2416 /// Get a canonical add expression, or something simpler if possible. 2417 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2418 SCEV::NoWrapFlags OrigFlags, 2419 unsigned Depth) { 2420 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2421 "only nuw or nsw allowed"); 2422 assert(!Ops.empty() && "Cannot get empty add!"); 2423 if (Ops.size() == 1) return Ops[0]; 2424 #ifndef NDEBUG 2425 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2426 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2427 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2428 "SCEVAddExpr operand types don't match!"); 2429 unsigned NumPtrs = count_if( 2430 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2431 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2432 #endif 2433 2434 // Sort by complexity, this groups all similar expression types together. 2435 GroupByComplexity(Ops, &LI, DT); 2436 2437 // If there are any constants, fold them together. 2438 unsigned Idx = 0; 2439 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2440 ++Idx; 2441 assert(Idx < Ops.size()); 2442 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2443 // We found two constants, fold them together! 2444 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2445 if (Ops.size() == 2) return Ops[0]; 2446 Ops.erase(Ops.begin()+1); // Erase the folded element 2447 LHSC = cast<SCEVConstant>(Ops[0]); 2448 } 2449 2450 // If we are left with a constant zero being added, strip it off. 2451 if (LHSC->getValue()->isZero()) { 2452 Ops.erase(Ops.begin()); 2453 --Idx; 2454 } 2455 2456 if (Ops.size() == 1) return Ops[0]; 2457 } 2458 2459 // Delay expensive flag strengthening until necessary. 2460 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2461 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2462 }; 2463 2464 // Limit recursion calls depth. 2465 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2466 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2467 2468 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2469 // Don't strengthen flags if we have no new information. 2470 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2471 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2472 Add->setNoWrapFlags(ComputeFlags(Ops)); 2473 return S; 2474 } 2475 2476 // Okay, check to see if the same value occurs in the operand list more than 2477 // once. If so, merge them together into an multiply expression. Since we 2478 // sorted the list, these values are required to be adjacent. 2479 Type *Ty = Ops[0]->getType(); 2480 bool FoundMatch = false; 2481 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2482 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2483 // Scan ahead to count how many equal operands there are. 2484 unsigned Count = 2; 2485 while (i+Count != e && Ops[i+Count] == Ops[i]) 2486 ++Count; 2487 // Merge the values into a multiply. 2488 const SCEV *Scale = getConstant(Ty, Count); 2489 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2490 if (Ops.size() == Count) 2491 return Mul; 2492 Ops[i] = Mul; 2493 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2494 --i; e -= Count - 1; 2495 FoundMatch = true; 2496 } 2497 if (FoundMatch) 2498 return getAddExpr(Ops, OrigFlags, Depth + 1); 2499 2500 // Check for truncates. If all the operands are truncated from the same 2501 // type, see if factoring out the truncate would permit the result to be 2502 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2503 // if the contents of the resulting outer trunc fold to something simple. 2504 auto FindTruncSrcType = [&]() -> Type * { 2505 // We're ultimately looking to fold an addrec of truncs and muls of only 2506 // constants and truncs, so if we find any other types of SCEV 2507 // as operands of the addrec then we bail and return nullptr here. 2508 // Otherwise, we return the type of the operand of a trunc that we find. 2509 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2510 return T->getOperand()->getType(); 2511 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2512 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2513 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2514 return T->getOperand()->getType(); 2515 } 2516 return nullptr; 2517 }; 2518 if (auto *SrcType = FindTruncSrcType()) { 2519 SmallVector<const SCEV *, 8> LargeOps; 2520 bool Ok = true; 2521 // Check all the operands to see if they can be represented in the 2522 // source type of the truncate. 2523 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2524 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2525 if (T->getOperand()->getType() != SrcType) { 2526 Ok = false; 2527 break; 2528 } 2529 LargeOps.push_back(T->getOperand()); 2530 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2531 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2532 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2533 SmallVector<const SCEV *, 8> LargeMulOps; 2534 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2535 if (const SCEVTruncateExpr *T = 2536 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2537 if (T->getOperand()->getType() != SrcType) { 2538 Ok = false; 2539 break; 2540 } 2541 LargeMulOps.push_back(T->getOperand()); 2542 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2543 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2544 } else { 2545 Ok = false; 2546 break; 2547 } 2548 } 2549 if (Ok) 2550 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2551 } else { 2552 Ok = false; 2553 break; 2554 } 2555 } 2556 if (Ok) { 2557 // Evaluate the expression in the larger type. 2558 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2559 // If it folds to something simple, use it. Otherwise, don't. 2560 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2561 return getTruncateExpr(Fold, Ty); 2562 } 2563 } 2564 2565 if (Ops.size() == 2) { 2566 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2567 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2568 // C1). 2569 const SCEV *A = Ops[0]; 2570 const SCEV *B = Ops[1]; 2571 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2572 auto *C = dyn_cast<SCEVConstant>(A); 2573 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2574 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2575 auto C2 = C->getAPInt(); 2576 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2577 2578 APInt ConstAdd = C1 + C2; 2579 auto AddFlags = AddExpr->getNoWrapFlags(); 2580 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2581 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2582 ConstAdd.ule(C1)) { 2583 PreservedFlags = 2584 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2585 } 2586 2587 // Adding a constant with the same sign and small magnitude is NSW, if the 2588 // original AddExpr was NSW. 2589 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2590 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2591 ConstAdd.abs().ule(C1.abs())) { 2592 PreservedFlags = 2593 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2594 } 2595 2596 if (PreservedFlags != SCEV::FlagAnyWrap) { 2597 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2598 NewOps[0] = getConstant(ConstAdd); 2599 return getAddExpr(NewOps, PreservedFlags); 2600 } 2601 } 2602 } 2603 2604 // Skip past any other cast SCEVs. 2605 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2606 ++Idx; 2607 2608 // If there are add operands they would be next. 2609 if (Idx < Ops.size()) { 2610 bool DeletedAdd = false; 2611 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2612 // common NUW flag for expression after inlining. Other flags cannot be 2613 // preserved, because they may depend on the original order of operations. 2614 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2615 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2616 if (Ops.size() > AddOpsInlineThreshold || 2617 Add->getNumOperands() > AddOpsInlineThreshold) 2618 break; 2619 // If we have an add, expand the add operands onto the end of the operands 2620 // list. 2621 Ops.erase(Ops.begin()+Idx); 2622 Ops.append(Add->op_begin(), Add->op_end()); 2623 DeletedAdd = true; 2624 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2625 } 2626 2627 // If we deleted at least one add, we added operands to the end of the list, 2628 // and they are not necessarily sorted. Recurse to resort and resimplify 2629 // any operands we just acquired. 2630 if (DeletedAdd) 2631 return getAddExpr(Ops, CommonFlags, Depth + 1); 2632 } 2633 2634 // Skip over the add expression until we get to a multiply. 2635 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2636 ++Idx; 2637 2638 // Check to see if there are any folding opportunities present with 2639 // operands multiplied by constant values. 2640 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2641 uint64_t BitWidth = getTypeSizeInBits(Ty); 2642 DenseMap<const SCEV *, APInt> M; 2643 SmallVector<const SCEV *, 8> NewOps; 2644 APInt AccumulatedConstant(BitWidth, 0); 2645 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2646 Ops.data(), Ops.size(), 2647 APInt(BitWidth, 1), *this)) { 2648 struct APIntCompare { 2649 bool operator()(const APInt &LHS, const APInt &RHS) const { 2650 return LHS.ult(RHS); 2651 } 2652 }; 2653 2654 // Some interesting folding opportunity is present, so its worthwhile to 2655 // re-generate the operands list. Group the operands by constant scale, 2656 // to avoid multiplying by the same constant scale multiple times. 2657 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2658 for (const SCEV *NewOp : NewOps) 2659 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2660 // Re-generate the operands list. 2661 Ops.clear(); 2662 if (AccumulatedConstant != 0) 2663 Ops.push_back(getConstant(AccumulatedConstant)); 2664 for (auto &MulOp : MulOpLists) { 2665 if (MulOp.first == 1) { 2666 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2667 } else if (MulOp.first != 0) { 2668 Ops.push_back(getMulExpr( 2669 getConstant(MulOp.first), 2670 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2671 SCEV::FlagAnyWrap, Depth + 1)); 2672 } 2673 } 2674 if (Ops.empty()) 2675 return getZero(Ty); 2676 if (Ops.size() == 1) 2677 return Ops[0]; 2678 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2679 } 2680 } 2681 2682 // If we are adding something to a multiply expression, make sure the 2683 // something is not already an operand of the multiply. If so, merge it into 2684 // the multiply. 2685 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2686 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2687 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2688 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2689 if (isa<SCEVConstant>(MulOpSCEV)) 2690 continue; 2691 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2692 if (MulOpSCEV == Ops[AddOp]) { 2693 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2694 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2695 if (Mul->getNumOperands() != 2) { 2696 // If the multiply has more than two operands, we must get the 2697 // Y*Z term. 2698 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2699 Mul->op_begin()+MulOp); 2700 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2701 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2702 } 2703 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2704 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2705 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2706 SCEV::FlagAnyWrap, Depth + 1); 2707 if (Ops.size() == 2) return OuterMul; 2708 if (AddOp < Idx) { 2709 Ops.erase(Ops.begin()+AddOp); 2710 Ops.erase(Ops.begin()+Idx-1); 2711 } else { 2712 Ops.erase(Ops.begin()+Idx); 2713 Ops.erase(Ops.begin()+AddOp-1); 2714 } 2715 Ops.push_back(OuterMul); 2716 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2717 } 2718 2719 // Check this multiply against other multiplies being added together. 2720 for (unsigned OtherMulIdx = Idx+1; 2721 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2722 ++OtherMulIdx) { 2723 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2724 // If MulOp occurs in OtherMul, we can fold the two multiplies 2725 // together. 2726 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2727 OMulOp != e; ++OMulOp) 2728 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2729 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2730 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2731 if (Mul->getNumOperands() != 2) { 2732 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2733 Mul->op_begin()+MulOp); 2734 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2735 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2736 } 2737 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2738 if (OtherMul->getNumOperands() != 2) { 2739 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2740 OtherMul->op_begin()+OMulOp); 2741 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2742 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2743 } 2744 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2745 const SCEV *InnerMulSum = 2746 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2747 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2748 SCEV::FlagAnyWrap, Depth + 1); 2749 if (Ops.size() == 2) return OuterMul; 2750 Ops.erase(Ops.begin()+Idx); 2751 Ops.erase(Ops.begin()+OtherMulIdx-1); 2752 Ops.push_back(OuterMul); 2753 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2754 } 2755 } 2756 } 2757 } 2758 2759 // If there are any add recurrences in the operands list, see if any other 2760 // added values are loop invariant. If so, we can fold them into the 2761 // recurrence. 2762 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2763 ++Idx; 2764 2765 // Scan over all recurrences, trying to fold loop invariants into them. 2766 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2767 // Scan all of the other operands to this add and add them to the vector if 2768 // they are loop invariant w.r.t. the recurrence. 2769 SmallVector<const SCEV *, 8> LIOps; 2770 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2771 const Loop *AddRecLoop = AddRec->getLoop(); 2772 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2773 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2774 LIOps.push_back(Ops[i]); 2775 Ops.erase(Ops.begin()+i); 2776 --i; --e; 2777 } 2778 2779 // If we found some loop invariants, fold them into the recurrence. 2780 if (!LIOps.empty()) { 2781 // Compute nowrap flags for the addition of the loop-invariant ops and 2782 // the addrec. Temporarily push it as an operand for that purpose. These 2783 // flags are valid in the scope of the addrec only. 2784 LIOps.push_back(AddRec); 2785 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2786 LIOps.pop_back(); 2787 2788 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2789 LIOps.push_back(AddRec->getStart()); 2790 2791 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2792 2793 // It is not in general safe to propagate flags valid on an add within 2794 // the addrec scope to one outside it. We must prove that the inner 2795 // scope is guaranteed to execute if the outer one does to be able to 2796 // safely propagate. We know the program is undefined if poison is 2797 // produced on the inner scoped addrec. We also know that *for this use* 2798 // the outer scoped add can't overflow (because of the flags we just 2799 // computed for the inner scoped add) without the program being undefined. 2800 // Proving that entry to the outer scope neccesitates entry to the inner 2801 // scope, thus proves the program undefined if the flags would be violated 2802 // in the outer scope. 2803 SCEV::NoWrapFlags AddFlags = Flags; 2804 if (AddFlags != SCEV::FlagAnyWrap) { 2805 auto *DefI = getDefiningScopeBound(LIOps); 2806 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2807 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2808 AddFlags = SCEV::FlagAnyWrap; 2809 } 2810 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2811 2812 // Build the new addrec. Propagate the NUW and NSW flags if both the 2813 // outer add and the inner addrec are guaranteed to have no overflow. 2814 // Always propagate NW. 2815 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2816 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2817 2818 // If all of the other operands were loop invariant, we are done. 2819 if (Ops.size() == 1) return NewRec; 2820 2821 // Otherwise, add the folded AddRec by the non-invariant parts. 2822 for (unsigned i = 0;; ++i) 2823 if (Ops[i] == AddRec) { 2824 Ops[i] = NewRec; 2825 break; 2826 } 2827 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2828 } 2829 2830 // Okay, if there weren't any loop invariants to be folded, check to see if 2831 // there are multiple AddRec's with the same loop induction variable being 2832 // added together. If so, we can fold them. 2833 for (unsigned OtherIdx = Idx+1; 2834 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2835 ++OtherIdx) { 2836 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2837 // so that the 1st found AddRecExpr is dominated by all others. 2838 assert(DT.dominates( 2839 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2840 AddRec->getLoop()->getHeader()) && 2841 "AddRecExprs are not sorted in reverse dominance order?"); 2842 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2843 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2844 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2845 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2846 ++OtherIdx) { 2847 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2848 if (OtherAddRec->getLoop() == AddRecLoop) { 2849 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2850 i != e; ++i) { 2851 if (i >= AddRecOps.size()) { 2852 AddRecOps.append(OtherAddRec->op_begin()+i, 2853 OtherAddRec->op_end()); 2854 break; 2855 } 2856 SmallVector<const SCEV *, 2> TwoOps = { 2857 AddRecOps[i], OtherAddRec->getOperand(i)}; 2858 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2859 } 2860 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2861 } 2862 } 2863 // Step size has changed, so we cannot guarantee no self-wraparound. 2864 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2865 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2866 } 2867 } 2868 2869 // Otherwise couldn't fold anything into this recurrence. Move onto the 2870 // next one. 2871 } 2872 2873 // Okay, it looks like we really DO need an add expr. Check to see if we 2874 // already have one, otherwise create a new one. 2875 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2876 } 2877 2878 const SCEV * 2879 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2880 SCEV::NoWrapFlags Flags) { 2881 FoldingSetNodeID ID; 2882 ID.AddInteger(scAddExpr); 2883 for (const SCEV *Op : Ops) 2884 ID.AddPointer(Op); 2885 void *IP = nullptr; 2886 SCEVAddExpr *S = 2887 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2888 if (!S) { 2889 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2890 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2891 S = new (SCEVAllocator) 2892 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2893 UniqueSCEVs.InsertNode(S, IP); 2894 registerUser(S, Ops); 2895 } 2896 S->setNoWrapFlags(Flags); 2897 return S; 2898 } 2899 2900 const SCEV * 2901 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2902 const Loop *L, SCEV::NoWrapFlags Flags) { 2903 FoldingSetNodeID ID; 2904 ID.AddInteger(scAddRecExpr); 2905 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2906 ID.AddPointer(Ops[i]); 2907 ID.AddPointer(L); 2908 void *IP = nullptr; 2909 SCEVAddRecExpr *S = 2910 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2911 if (!S) { 2912 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2913 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2914 S = new (SCEVAllocator) 2915 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2916 UniqueSCEVs.InsertNode(S, IP); 2917 LoopUsers[L].push_back(S); 2918 registerUser(S, Ops); 2919 } 2920 setNoWrapFlags(S, Flags); 2921 return S; 2922 } 2923 2924 const SCEV * 2925 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2926 SCEV::NoWrapFlags Flags) { 2927 FoldingSetNodeID ID; 2928 ID.AddInteger(scMulExpr); 2929 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2930 ID.AddPointer(Ops[i]); 2931 void *IP = nullptr; 2932 SCEVMulExpr *S = 2933 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2934 if (!S) { 2935 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2936 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2937 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2938 O, Ops.size()); 2939 UniqueSCEVs.InsertNode(S, IP); 2940 registerUser(S, Ops); 2941 } 2942 S->setNoWrapFlags(Flags); 2943 return S; 2944 } 2945 2946 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2947 uint64_t k = i*j; 2948 if (j > 1 && k / j != i) Overflow = true; 2949 return k; 2950 } 2951 2952 /// Compute the result of "n choose k", the binomial coefficient. If an 2953 /// intermediate computation overflows, Overflow will be set and the return will 2954 /// be garbage. Overflow is not cleared on absence of overflow. 2955 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2956 // We use the multiplicative formula: 2957 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2958 // At each iteration, we take the n-th term of the numeral and divide by the 2959 // (k-n)th term of the denominator. This division will always produce an 2960 // integral result, and helps reduce the chance of overflow in the 2961 // intermediate computations. However, we can still overflow even when the 2962 // final result would fit. 2963 2964 if (n == 0 || n == k) return 1; 2965 if (k > n) return 0; 2966 2967 if (k > n/2) 2968 k = n-k; 2969 2970 uint64_t r = 1; 2971 for (uint64_t i = 1; i <= k; ++i) { 2972 r = umul_ov(r, n-(i-1), Overflow); 2973 r /= i; 2974 } 2975 return r; 2976 } 2977 2978 /// Determine if any of the operands in this SCEV are a constant or if 2979 /// any of the add or multiply expressions in this SCEV contain a constant. 2980 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2981 struct FindConstantInAddMulChain { 2982 bool FoundConstant = false; 2983 2984 bool follow(const SCEV *S) { 2985 FoundConstant |= isa<SCEVConstant>(S); 2986 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2987 } 2988 2989 bool isDone() const { 2990 return FoundConstant; 2991 } 2992 }; 2993 2994 FindConstantInAddMulChain F; 2995 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2996 ST.visitAll(StartExpr); 2997 return F.FoundConstant; 2998 } 2999 3000 /// Get a canonical multiply expression, or something simpler if possible. 3001 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3002 SCEV::NoWrapFlags OrigFlags, 3003 unsigned Depth) { 3004 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3005 "only nuw or nsw allowed"); 3006 assert(!Ops.empty() && "Cannot get empty mul!"); 3007 if (Ops.size() == 1) return Ops[0]; 3008 #ifndef NDEBUG 3009 Type *ETy = Ops[0]->getType(); 3010 assert(!ETy->isPointerTy()); 3011 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3012 assert(Ops[i]->getType() == ETy && 3013 "SCEVMulExpr operand types don't match!"); 3014 #endif 3015 3016 // Sort by complexity, this groups all similar expression types together. 3017 GroupByComplexity(Ops, &LI, DT); 3018 3019 // If there are any constants, fold them together. 3020 unsigned Idx = 0; 3021 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3022 ++Idx; 3023 assert(Idx < Ops.size()); 3024 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3025 // We found two constants, fold them together! 3026 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3027 if (Ops.size() == 2) return Ops[0]; 3028 Ops.erase(Ops.begin()+1); // Erase the folded element 3029 LHSC = cast<SCEVConstant>(Ops[0]); 3030 } 3031 3032 // If we have a multiply of zero, it will always be zero. 3033 if (LHSC->getValue()->isZero()) 3034 return LHSC; 3035 3036 // If we are left with a constant one being multiplied, strip it off. 3037 if (LHSC->getValue()->isOne()) { 3038 Ops.erase(Ops.begin()); 3039 --Idx; 3040 } 3041 3042 if (Ops.size() == 1) 3043 return Ops[0]; 3044 } 3045 3046 // Delay expensive flag strengthening until necessary. 3047 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3048 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3049 }; 3050 3051 // Limit recursion calls depth. 3052 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3053 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3054 3055 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3056 // Don't strengthen flags if we have no new information. 3057 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3058 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3059 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3060 return S; 3061 } 3062 3063 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3064 if (Ops.size() == 2) { 3065 // C1*(C2+V) -> C1*C2 + C1*V 3066 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3067 // If any of Add's ops are Adds or Muls with a constant, apply this 3068 // transformation as well. 3069 // 3070 // TODO: There are some cases where this transformation is not 3071 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3072 // this transformation should be narrowed down. 3073 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3074 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3075 SCEV::FlagAnyWrap, Depth + 1), 3076 getMulExpr(LHSC, Add->getOperand(1), 3077 SCEV::FlagAnyWrap, Depth + 1), 3078 SCEV::FlagAnyWrap, Depth + 1); 3079 3080 if (Ops[0]->isAllOnesValue()) { 3081 // If we have a mul by -1 of an add, try distributing the -1 among the 3082 // add operands. 3083 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3084 SmallVector<const SCEV *, 4> NewOps; 3085 bool AnyFolded = false; 3086 for (const SCEV *AddOp : Add->operands()) { 3087 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3088 Depth + 1); 3089 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3090 NewOps.push_back(Mul); 3091 } 3092 if (AnyFolded) 3093 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3094 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3095 // Negation preserves a recurrence's no self-wrap property. 3096 SmallVector<const SCEV *, 4> Operands; 3097 for (const SCEV *AddRecOp : AddRec->operands()) 3098 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3099 Depth + 1)); 3100 3101 return getAddRecExpr(Operands, AddRec->getLoop(), 3102 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3103 } 3104 } 3105 } 3106 } 3107 3108 // Skip over the add expression until we get to a multiply. 3109 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3110 ++Idx; 3111 3112 // If there are mul operands inline them all into this expression. 3113 if (Idx < Ops.size()) { 3114 bool DeletedMul = false; 3115 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3116 if (Ops.size() > MulOpsInlineThreshold) 3117 break; 3118 // If we have an mul, expand the mul operands onto the end of the 3119 // operands list. 3120 Ops.erase(Ops.begin()+Idx); 3121 Ops.append(Mul->op_begin(), Mul->op_end()); 3122 DeletedMul = true; 3123 } 3124 3125 // If we deleted at least one mul, we added operands to the end of the 3126 // list, and they are not necessarily sorted. Recurse to resort and 3127 // resimplify any operands we just acquired. 3128 if (DeletedMul) 3129 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3130 } 3131 3132 // If there are any add recurrences in the operands list, see if any other 3133 // added values are loop invariant. If so, we can fold them into the 3134 // recurrence. 3135 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3136 ++Idx; 3137 3138 // Scan over all recurrences, trying to fold loop invariants into them. 3139 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3140 // Scan all of the other operands to this mul and add them to the vector 3141 // if they are loop invariant w.r.t. the recurrence. 3142 SmallVector<const SCEV *, 8> LIOps; 3143 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3144 const Loop *AddRecLoop = AddRec->getLoop(); 3145 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3146 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3147 LIOps.push_back(Ops[i]); 3148 Ops.erase(Ops.begin()+i); 3149 --i; --e; 3150 } 3151 3152 // If we found some loop invariants, fold them into the recurrence. 3153 if (!LIOps.empty()) { 3154 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3155 SmallVector<const SCEV *, 4> NewOps; 3156 NewOps.reserve(AddRec->getNumOperands()); 3157 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3158 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3159 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3160 SCEV::FlagAnyWrap, Depth + 1)); 3161 3162 // Build the new addrec. Propagate the NUW and NSW flags if both the 3163 // outer mul and the inner addrec are guaranteed to have no overflow. 3164 // 3165 // No self-wrap cannot be guaranteed after changing the step size, but 3166 // will be inferred if either NUW or NSW is true. 3167 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3168 const SCEV *NewRec = getAddRecExpr( 3169 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3170 3171 // If all of the other operands were loop invariant, we are done. 3172 if (Ops.size() == 1) return NewRec; 3173 3174 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3175 for (unsigned i = 0;; ++i) 3176 if (Ops[i] == AddRec) { 3177 Ops[i] = NewRec; 3178 break; 3179 } 3180 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3181 } 3182 3183 // Okay, if there weren't any loop invariants to be folded, check to see 3184 // if there are multiple AddRec's with the same loop induction variable 3185 // being multiplied together. If so, we can fold them. 3186 3187 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3188 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3189 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3190 // ]]],+,...up to x=2n}. 3191 // Note that the arguments to choose() are always integers with values 3192 // known at compile time, never SCEV objects. 3193 // 3194 // The implementation avoids pointless extra computations when the two 3195 // addrec's are of different length (mathematically, it's equivalent to 3196 // an infinite stream of zeros on the right). 3197 bool OpsModified = false; 3198 for (unsigned OtherIdx = Idx+1; 3199 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3200 ++OtherIdx) { 3201 const SCEVAddRecExpr *OtherAddRec = 3202 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3203 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3204 continue; 3205 3206 // Limit max number of arguments to avoid creation of unreasonably big 3207 // SCEVAddRecs with very complex operands. 3208 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3209 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3210 continue; 3211 3212 bool Overflow = false; 3213 Type *Ty = AddRec->getType(); 3214 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3215 SmallVector<const SCEV*, 7> AddRecOps; 3216 for (int x = 0, xe = AddRec->getNumOperands() + 3217 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3218 SmallVector <const SCEV *, 7> SumOps; 3219 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3220 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3221 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3222 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3223 z < ze && !Overflow; ++z) { 3224 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3225 uint64_t Coeff; 3226 if (LargerThan64Bits) 3227 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3228 else 3229 Coeff = Coeff1*Coeff2; 3230 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3231 const SCEV *Term1 = AddRec->getOperand(y-z); 3232 const SCEV *Term2 = OtherAddRec->getOperand(z); 3233 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3234 SCEV::FlagAnyWrap, Depth + 1)); 3235 } 3236 } 3237 if (SumOps.empty()) 3238 SumOps.push_back(getZero(Ty)); 3239 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3240 } 3241 if (!Overflow) { 3242 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3243 SCEV::FlagAnyWrap); 3244 if (Ops.size() == 2) return NewAddRec; 3245 Ops[Idx] = NewAddRec; 3246 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3247 OpsModified = true; 3248 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3249 if (!AddRec) 3250 break; 3251 } 3252 } 3253 if (OpsModified) 3254 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3255 3256 // Otherwise couldn't fold anything into this recurrence. Move onto the 3257 // next one. 3258 } 3259 3260 // Okay, it looks like we really DO need an mul expr. Check to see if we 3261 // already have one, otherwise create a new one. 3262 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3263 } 3264 3265 /// Represents an unsigned remainder expression based on unsigned division. 3266 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3267 const SCEV *RHS) { 3268 assert(getEffectiveSCEVType(LHS->getType()) == 3269 getEffectiveSCEVType(RHS->getType()) && 3270 "SCEVURemExpr operand types don't match!"); 3271 3272 // Short-circuit easy cases 3273 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3274 // If constant is one, the result is trivial 3275 if (RHSC->getValue()->isOne()) 3276 return getZero(LHS->getType()); // X urem 1 --> 0 3277 3278 // If constant is a power of two, fold into a zext(trunc(LHS)). 3279 if (RHSC->getAPInt().isPowerOf2()) { 3280 Type *FullTy = LHS->getType(); 3281 Type *TruncTy = 3282 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3283 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3284 } 3285 } 3286 3287 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3288 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3289 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3290 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3291 } 3292 3293 /// Get a canonical unsigned division expression, or something simpler if 3294 /// possible. 3295 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3296 const SCEV *RHS) { 3297 assert(!LHS->getType()->isPointerTy() && 3298 "SCEVUDivExpr operand can't be pointer!"); 3299 assert(LHS->getType() == RHS->getType() && 3300 "SCEVUDivExpr operand types don't match!"); 3301 3302 FoldingSetNodeID ID; 3303 ID.AddInteger(scUDivExpr); 3304 ID.AddPointer(LHS); 3305 ID.AddPointer(RHS); 3306 void *IP = nullptr; 3307 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3308 return S; 3309 3310 // 0 udiv Y == 0 3311 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3312 if (LHSC->getValue()->isZero()) 3313 return LHS; 3314 3315 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3316 if (RHSC->getValue()->isOne()) 3317 return LHS; // X udiv 1 --> x 3318 // If the denominator is zero, the result of the udiv is undefined. Don't 3319 // try to analyze it, because the resolution chosen here may differ from 3320 // the resolution chosen in other parts of the compiler. 3321 if (!RHSC->getValue()->isZero()) { 3322 // Determine if the division can be folded into the operands of 3323 // its operands. 3324 // TODO: Generalize this to non-constants by using known-bits information. 3325 Type *Ty = LHS->getType(); 3326 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3327 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3328 // For non-power-of-two values, effectively round the value up to the 3329 // nearest power of two. 3330 if (!RHSC->getAPInt().isPowerOf2()) 3331 ++MaxShiftAmt; 3332 IntegerType *ExtTy = 3333 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3334 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3335 if (const SCEVConstant *Step = 3336 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3337 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3338 const APInt &StepInt = Step->getAPInt(); 3339 const APInt &DivInt = RHSC->getAPInt(); 3340 if (!StepInt.urem(DivInt) && 3341 getZeroExtendExpr(AR, ExtTy) == 3342 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3343 getZeroExtendExpr(Step, ExtTy), 3344 AR->getLoop(), SCEV::FlagAnyWrap)) { 3345 SmallVector<const SCEV *, 4> Operands; 3346 for (const SCEV *Op : AR->operands()) 3347 Operands.push_back(getUDivExpr(Op, RHS)); 3348 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3349 } 3350 /// Get a canonical UDivExpr for a recurrence. 3351 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3352 // We can currently only fold X%N if X is constant. 3353 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3354 if (StartC && !DivInt.urem(StepInt) && 3355 getZeroExtendExpr(AR, ExtTy) == 3356 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3357 getZeroExtendExpr(Step, ExtTy), 3358 AR->getLoop(), SCEV::FlagAnyWrap)) { 3359 const APInt &StartInt = StartC->getAPInt(); 3360 const APInt &StartRem = StartInt.urem(StepInt); 3361 if (StartRem != 0) { 3362 const SCEV *NewLHS = 3363 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3364 AR->getLoop(), SCEV::FlagNW); 3365 if (LHS != NewLHS) { 3366 LHS = NewLHS; 3367 3368 // Reset the ID to include the new LHS, and check if it is 3369 // already cached. 3370 ID.clear(); 3371 ID.AddInteger(scUDivExpr); 3372 ID.AddPointer(LHS); 3373 ID.AddPointer(RHS); 3374 IP = nullptr; 3375 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3376 return S; 3377 } 3378 } 3379 } 3380 } 3381 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3382 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3383 SmallVector<const SCEV *, 4> Operands; 3384 for (const SCEV *Op : M->operands()) 3385 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3386 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3387 // Find an operand that's safely divisible. 3388 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3389 const SCEV *Op = M->getOperand(i); 3390 const SCEV *Div = getUDivExpr(Op, RHSC); 3391 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3392 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3393 Operands[i] = Div; 3394 return getMulExpr(Operands); 3395 } 3396 } 3397 } 3398 3399 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3400 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3401 if (auto *DivisorConstant = 3402 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3403 bool Overflow = false; 3404 APInt NewRHS = 3405 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3406 if (Overflow) { 3407 return getConstant(RHSC->getType(), 0, false); 3408 } 3409 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3410 } 3411 } 3412 3413 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3414 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3415 SmallVector<const SCEV *, 4> Operands; 3416 for (const SCEV *Op : A->operands()) 3417 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3418 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3419 Operands.clear(); 3420 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3421 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3422 if (isa<SCEVUDivExpr>(Op) || 3423 getMulExpr(Op, RHS) != A->getOperand(i)) 3424 break; 3425 Operands.push_back(Op); 3426 } 3427 if (Operands.size() == A->getNumOperands()) 3428 return getAddExpr(Operands); 3429 } 3430 } 3431 3432 // Fold if both operands are constant. 3433 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3434 Constant *LHSCV = LHSC->getValue(); 3435 Constant *RHSCV = RHSC->getValue(); 3436 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3437 RHSCV))); 3438 } 3439 } 3440 } 3441 3442 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3443 // changes). Make sure we get a new one. 3444 IP = nullptr; 3445 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3446 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3447 LHS, RHS); 3448 UniqueSCEVs.InsertNode(S, IP); 3449 registerUser(S, {LHS, RHS}); 3450 return S; 3451 } 3452 3453 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3454 APInt A = C1->getAPInt().abs(); 3455 APInt B = C2->getAPInt().abs(); 3456 uint32_t ABW = A.getBitWidth(); 3457 uint32_t BBW = B.getBitWidth(); 3458 3459 if (ABW > BBW) 3460 B = B.zext(ABW); 3461 else if (ABW < BBW) 3462 A = A.zext(BBW); 3463 3464 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3465 } 3466 3467 /// Get a canonical unsigned division expression, or something simpler if 3468 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3469 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3470 /// it's not exact because the udiv may be clearing bits. 3471 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3472 const SCEV *RHS) { 3473 // TODO: we could try to find factors in all sorts of things, but for now we 3474 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3475 // end of this file for inspiration. 3476 3477 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3478 if (!Mul || !Mul->hasNoUnsignedWrap()) 3479 return getUDivExpr(LHS, RHS); 3480 3481 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3482 // If the mulexpr multiplies by a constant, then that constant must be the 3483 // first element of the mulexpr. 3484 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3485 if (LHSCst == RHSCst) { 3486 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3487 return getMulExpr(Operands); 3488 } 3489 3490 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3491 // that there's a factor provided by one of the other terms. We need to 3492 // check. 3493 APInt Factor = gcd(LHSCst, RHSCst); 3494 if (!Factor.isIntN(1)) { 3495 LHSCst = 3496 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3497 RHSCst = 3498 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3499 SmallVector<const SCEV *, 2> Operands; 3500 Operands.push_back(LHSCst); 3501 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3502 LHS = getMulExpr(Operands); 3503 RHS = RHSCst; 3504 Mul = dyn_cast<SCEVMulExpr>(LHS); 3505 if (!Mul) 3506 return getUDivExactExpr(LHS, RHS); 3507 } 3508 } 3509 } 3510 3511 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3512 if (Mul->getOperand(i) == RHS) { 3513 SmallVector<const SCEV *, 2> Operands; 3514 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3515 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3516 return getMulExpr(Operands); 3517 } 3518 } 3519 3520 return getUDivExpr(LHS, RHS); 3521 } 3522 3523 /// Get an add recurrence expression for the specified loop. Simplify the 3524 /// expression as much as possible. 3525 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3526 const Loop *L, 3527 SCEV::NoWrapFlags Flags) { 3528 SmallVector<const SCEV *, 4> Operands; 3529 Operands.push_back(Start); 3530 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3531 if (StepChrec->getLoop() == L) { 3532 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3533 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3534 } 3535 3536 Operands.push_back(Step); 3537 return getAddRecExpr(Operands, L, Flags); 3538 } 3539 3540 /// Get an add recurrence expression for the specified loop. Simplify the 3541 /// expression as much as possible. 3542 const SCEV * 3543 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3544 const Loop *L, SCEV::NoWrapFlags Flags) { 3545 if (Operands.size() == 1) return Operands[0]; 3546 #ifndef NDEBUG 3547 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3548 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3549 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3550 "SCEVAddRecExpr operand types don't match!"); 3551 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3552 } 3553 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3554 assert(isLoopInvariant(Operands[i], L) && 3555 "SCEVAddRecExpr operand is not loop-invariant!"); 3556 #endif 3557 3558 if (Operands.back()->isZero()) { 3559 Operands.pop_back(); 3560 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3561 } 3562 3563 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3564 // use that information to infer NUW and NSW flags. However, computing a 3565 // BE count requires calling getAddRecExpr, so we may not yet have a 3566 // meaningful BE count at this point (and if we don't, we'd be stuck 3567 // with a SCEVCouldNotCompute as the cached BE count). 3568 3569 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3570 3571 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3572 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3573 const Loop *NestedLoop = NestedAR->getLoop(); 3574 if (L->contains(NestedLoop) 3575 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3576 : (!NestedLoop->contains(L) && 3577 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3578 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3579 Operands[0] = NestedAR->getStart(); 3580 // AddRecs require their operands be loop-invariant with respect to their 3581 // loops. Don't perform this transformation if it would break this 3582 // requirement. 3583 bool AllInvariant = all_of( 3584 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3585 3586 if (AllInvariant) { 3587 // Create a recurrence for the outer loop with the same step size. 3588 // 3589 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3590 // inner recurrence has the same property. 3591 SCEV::NoWrapFlags OuterFlags = 3592 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3593 3594 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3595 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3596 return isLoopInvariant(Op, NestedLoop); 3597 }); 3598 3599 if (AllInvariant) { 3600 // Ok, both add recurrences are valid after the transformation. 3601 // 3602 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3603 // the outer recurrence has the same property. 3604 SCEV::NoWrapFlags InnerFlags = 3605 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3606 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3607 } 3608 } 3609 // Reset Operands to its original state. 3610 Operands[0] = NestedAR; 3611 } 3612 } 3613 3614 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3615 // already have one, otherwise create a new one. 3616 return getOrCreateAddRecExpr(Operands, L, Flags); 3617 } 3618 3619 const SCEV * 3620 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3621 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3622 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3623 // getSCEV(Base)->getType() has the same address space as Base->getType() 3624 // because SCEV::getType() preserves the address space. 3625 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3626 const bool AssumeInBoundsFlags = [&]() { 3627 if (!GEP->isInBounds()) 3628 return false; 3629 3630 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3631 // but to do that, we have to ensure that said flag is valid in the entire 3632 // defined scope of the SCEV. 3633 auto *GEPI = dyn_cast<Instruction>(GEP); 3634 // TODO: non-instructions have global scope. We might be able to prove 3635 // some global scope cases 3636 return GEPI && isSCEVExprNeverPoison(GEPI); 3637 }(); 3638 3639 SCEV::NoWrapFlags OffsetWrap = 3640 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3641 3642 Type *CurTy = GEP->getType(); 3643 bool FirstIter = true; 3644 SmallVector<const SCEV *, 4> Offsets; 3645 for (const SCEV *IndexExpr : IndexExprs) { 3646 // Compute the (potentially symbolic) offset in bytes for this index. 3647 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3648 // For a struct, add the member offset. 3649 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3650 unsigned FieldNo = Index->getZExtValue(); 3651 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3652 Offsets.push_back(FieldOffset); 3653 3654 // Update CurTy to the type of the field at Index. 3655 CurTy = STy->getTypeAtIndex(Index); 3656 } else { 3657 // Update CurTy to its element type. 3658 if (FirstIter) { 3659 assert(isa<PointerType>(CurTy) && 3660 "The first index of a GEP indexes a pointer"); 3661 CurTy = GEP->getSourceElementType(); 3662 FirstIter = false; 3663 } else { 3664 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3665 } 3666 // For an array, add the element offset, explicitly scaled. 3667 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3668 // Getelementptr indices are signed. 3669 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3670 3671 // Multiply the index by the element size to compute the element offset. 3672 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3673 Offsets.push_back(LocalOffset); 3674 } 3675 } 3676 3677 // Handle degenerate case of GEP without offsets. 3678 if (Offsets.empty()) 3679 return BaseExpr; 3680 3681 // Add the offsets together, assuming nsw if inbounds. 3682 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3683 // Add the base address and the offset. We cannot use the nsw flag, as the 3684 // base address is unsigned. However, if we know that the offset is 3685 // non-negative, we can use nuw. 3686 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3687 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3688 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3689 assert(BaseExpr->getType() == GEPExpr->getType() && 3690 "GEP should not change type mid-flight."); 3691 return GEPExpr; 3692 } 3693 3694 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3695 ArrayRef<const SCEV *> Ops) { 3696 FoldingSetNodeID ID; 3697 ID.AddInteger(SCEVType); 3698 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3699 ID.AddPointer(Ops[i]); 3700 void *IP = nullptr; 3701 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3702 } 3703 3704 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3705 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3706 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3707 } 3708 3709 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3710 SmallVectorImpl<const SCEV *> &Ops) { 3711 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3712 if (Ops.size() == 1) return Ops[0]; 3713 #ifndef NDEBUG 3714 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3715 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3716 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3717 "Operand types don't match!"); 3718 assert(Ops[0]->getType()->isPointerTy() == 3719 Ops[i]->getType()->isPointerTy() && 3720 "min/max should be consistently pointerish"); 3721 } 3722 #endif 3723 3724 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3725 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3726 3727 // Sort by complexity, this groups all similar expression types together. 3728 GroupByComplexity(Ops, &LI, DT); 3729 3730 // Check if we have created the same expression before. 3731 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3732 return S; 3733 } 3734 3735 // If there are any constants, fold them together. 3736 unsigned Idx = 0; 3737 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3738 ++Idx; 3739 assert(Idx < Ops.size()); 3740 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3741 if (Kind == scSMaxExpr) 3742 return APIntOps::smax(LHS, RHS); 3743 else if (Kind == scSMinExpr) 3744 return APIntOps::smin(LHS, RHS); 3745 else if (Kind == scUMaxExpr) 3746 return APIntOps::umax(LHS, RHS); 3747 else if (Kind == scUMinExpr) 3748 return APIntOps::umin(LHS, RHS); 3749 llvm_unreachable("Unknown SCEV min/max opcode"); 3750 }; 3751 3752 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3753 // We found two constants, fold them together! 3754 ConstantInt *Fold = ConstantInt::get( 3755 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3756 Ops[0] = getConstant(Fold); 3757 Ops.erase(Ops.begin()+1); // Erase the folded element 3758 if (Ops.size() == 1) return Ops[0]; 3759 LHSC = cast<SCEVConstant>(Ops[0]); 3760 } 3761 3762 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3763 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3764 3765 if (IsMax ? IsMinV : IsMaxV) { 3766 // If we are left with a constant minimum(/maximum)-int, strip it off. 3767 Ops.erase(Ops.begin()); 3768 --Idx; 3769 } else if (IsMax ? IsMaxV : IsMinV) { 3770 // If we have a max(/min) with a constant maximum(/minimum)-int, 3771 // it will always be the extremum. 3772 return LHSC; 3773 } 3774 3775 if (Ops.size() == 1) return Ops[0]; 3776 } 3777 3778 // Find the first operation of the same kind 3779 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3780 ++Idx; 3781 3782 // Check to see if one of the operands is of the same kind. If so, expand its 3783 // operands onto our operand list, and recurse to simplify. 3784 if (Idx < Ops.size()) { 3785 bool DeletedAny = false; 3786 while (Ops[Idx]->getSCEVType() == Kind) { 3787 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3788 Ops.erase(Ops.begin()+Idx); 3789 Ops.append(SMME->op_begin(), SMME->op_end()); 3790 DeletedAny = true; 3791 } 3792 3793 if (DeletedAny) 3794 return getMinMaxExpr(Kind, Ops); 3795 } 3796 3797 // Okay, check to see if the same value occurs in the operand list twice. If 3798 // so, delete one. Since we sorted the list, these values are required to 3799 // be adjacent. 3800 llvm::CmpInst::Predicate GEPred = 3801 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3802 llvm::CmpInst::Predicate LEPred = 3803 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3804 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3805 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3806 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3807 if (Ops[i] == Ops[i + 1] || 3808 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3809 // X op Y op Y --> X op Y 3810 // X op Y --> X, if we know X, Y are ordered appropriately 3811 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3812 --i; 3813 --e; 3814 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3815 Ops[i + 1])) { 3816 // X op Y --> Y, if we know X, Y are ordered appropriately 3817 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3818 --i; 3819 --e; 3820 } 3821 } 3822 3823 if (Ops.size() == 1) return Ops[0]; 3824 3825 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3826 3827 // Okay, it looks like we really DO need an expr. Check to see if we 3828 // already have one, otherwise create a new one. 3829 FoldingSetNodeID ID; 3830 ID.AddInteger(Kind); 3831 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3832 ID.AddPointer(Ops[i]); 3833 void *IP = nullptr; 3834 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3835 if (ExistingSCEV) 3836 return ExistingSCEV; 3837 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3838 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3839 SCEV *S = new (SCEVAllocator) 3840 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3841 3842 UniqueSCEVs.InsertNode(S, IP); 3843 registerUser(S, Ops); 3844 return S; 3845 } 3846 3847 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3848 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3849 return getSMaxExpr(Ops); 3850 } 3851 3852 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3853 return getMinMaxExpr(scSMaxExpr, Ops); 3854 } 3855 3856 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3857 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3858 return getUMaxExpr(Ops); 3859 } 3860 3861 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3862 return getMinMaxExpr(scUMaxExpr, Ops); 3863 } 3864 3865 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3866 const SCEV *RHS) { 3867 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3868 return getSMinExpr(Ops); 3869 } 3870 3871 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3872 return getMinMaxExpr(scSMinExpr, Ops); 3873 } 3874 3875 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3876 const SCEV *RHS) { 3877 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3878 return getUMinExpr(Ops); 3879 } 3880 3881 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3882 return getMinMaxExpr(scUMinExpr, Ops); 3883 } 3884 3885 const SCEV * 3886 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3887 ScalableVectorType *ScalableTy) { 3888 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3889 Constant *One = ConstantInt::get(IntTy, 1); 3890 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3891 // Note that the expression we created is the final expression, we don't 3892 // want to simplify it any further Also, if we call a normal getSCEV(), 3893 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3894 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3895 } 3896 3897 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3898 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3899 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3900 // We can bypass creating a target-independent constant expression and then 3901 // folding it back into a ConstantInt. This is just a compile-time 3902 // optimization. 3903 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3904 } 3905 3906 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3907 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3908 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3909 // We can bypass creating a target-independent constant expression and then 3910 // folding it back into a ConstantInt. This is just a compile-time 3911 // optimization. 3912 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3913 } 3914 3915 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3916 StructType *STy, 3917 unsigned FieldNo) { 3918 // We can bypass creating a target-independent constant expression and then 3919 // folding it back into a ConstantInt. This is just a compile-time 3920 // optimization. 3921 return getConstant( 3922 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3923 } 3924 3925 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3926 // Don't attempt to do anything other than create a SCEVUnknown object 3927 // here. createSCEV only calls getUnknown after checking for all other 3928 // interesting possibilities, and any other code that calls getUnknown 3929 // is doing so in order to hide a value from SCEV canonicalization. 3930 3931 FoldingSetNodeID ID; 3932 ID.AddInteger(scUnknown); 3933 ID.AddPointer(V); 3934 void *IP = nullptr; 3935 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3936 assert(cast<SCEVUnknown>(S)->getValue() == V && 3937 "Stale SCEVUnknown in uniquing map!"); 3938 return S; 3939 } 3940 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3941 FirstUnknown); 3942 FirstUnknown = cast<SCEVUnknown>(S); 3943 UniqueSCEVs.InsertNode(S, IP); 3944 return S; 3945 } 3946 3947 //===----------------------------------------------------------------------===// 3948 // Basic SCEV Analysis and PHI Idiom Recognition Code 3949 // 3950 3951 /// Test if values of the given type are analyzable within the SCEV 3952 /// framework. This primarily includes integer types, and it can optionally 3953 /// include pointer types if the ScalarEvolution class has access to 3954 /// target-specific information. 3955 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3956 // Integers and pointers are always SCEVable. 3957 return Ty->isIntOrPtrTy(); 3958 } 3959 3960 /// Return the size in bits of the specified type, for which isSCEVable must 3961 /// return true. 3962 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3963 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3964 if (Ty->isPointerTy()) 3965 return getDataLayout().getIndexTypeSizeInBits(Ty); 3966 return getDataLayout().getTypeSizeInBits(Ty); 3967 } 3968 3969 /// Return a type with the same bitwidth as the given type and which represents 3970 /// how SCEV will treat the given type, for which isSCEVable must return 3971 /// true. For pointer types, this is the pointer index sized integer type. 3972 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3973 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3974 3975 if (Ty->isIntegerTy()) 3976 return Ty; 3977 3978 // The only other support type is pointer. 3979 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3980 return getDataLayout().getIndexType(Ty); 3981 } 3982 3983 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3984 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3985 } 3986 3987 const SCEV *ScalarEvolution::getCouldNotCompute() { 3988 return CouldNotCompute.get(); 3989 } 3990 3991 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3992 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3993 auto *SU = dyn_cast<SCEVUnknown>(S); 3994 return SU && SU->getValue() == nullptr; 3995 }); 3996 3997 return !ContainsNulls; 3998 } 3999 4000 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4001 HasRecMapType::iterator I = HasRecMap.find(S); 4002 if (I != HasRecMap.end()) 4003 return I->second; 4004 4005 bool FoundAddRec = 4006 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4007 HasRecMap.insert({S, FoundAddRec}); 4008 return FoundAddRec; 4009 } 4010 4011 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 4012 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 4013 /// offset I, then return {S', I}, else return {\p S, nullptr}. 4014 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4015 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4016 if (!Add) 4017 return {S, nullptr}; 4018 4019 if (Add->getNumOperands() != 2) 4020 return {S, nullptr}; 4021 4022 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4023 if (!ConstOp) 4024 return {S, nullptr}; 4025 4026 return {Add->getOperand(1), ConstOp->getValue()}; 4027 } 4028 4029 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4030 /// by the value and offset from any ValueOffsetPair in the set. 4031 ScalarEvolution::ValueOffsetPairSetVector * 4032 ScalarEvolution::getSCEVValues(const SCEV *S) { 4033 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4034 if (SI == ExprValueMap.end()) 4035 return nullptr; 4036 #ifndef NDEBUG 4037 if (VerifySCEVMap) { 4038 // Check there is no dangling Value in the set returned. 4039 for (const auto &VE : SI->second) 4040 assert(ValueExprMap.count(VE.first)); 4041 } 4042 #endif 4043 return &SI->second; 4044 } 4045 4046 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4047 /// cannot be used separately. eraseValueFromMap should be used to remove 4048 /// V from ValueExprMap and ExprValueMap at the same time. 4049 void ScalarEvolution::eraseValueFromMap(Value *V) { 4050 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4051 if (I != ValueExprMap.end()) { 4052 const SCEV *S = I->second; 4053 // Remove {V, 0} from the set of ExprValueMap[S] 4054 if (auto *SV = getSCEVValues(S)) 4055 SV->remove({V, nullptr}); 4056 4057 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4058 const SCEV *Stripped; 4059 ConstantInt *Offset; 4060 std::tie(Stripped, Offset) = splitAddExpr(S); 4061 if (Offset != nullptr) { 4062 if (auto *SV = getSCEVValues(Stripped)) 4063 SV->remove({V, Offset}); 4064 } 4065 ValueExprMap.erase(V); 4066 } 4067 } 4068 4069 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4070 /// create a new one. 4071 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4072 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4073 4074 const SCEV *S = getExistingSCEV(V); 4075 if (S == nullptr) { 4076 S = createSCEV(V); 4077 // During PHI resolution, it is possible to create two SCEVs for the same 4078 // V, so it is needed to double check whether V->S is inserted into 4079 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4080 std::pair<ValueExprMapType::iterator, bool> Pair = 4081 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4082 if (Pair.second) { 4083 ExprValueMap[S].insert({V, nullptr}); 4084 4085 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4086 // ExprValueMap. 4087 const SCEV *Stripped = S; 4088 ConstantInt *Offset = nullptr; 4089 std::tie(Stripped, Offset) = splitAddExpr(S); 4090 // If stripped is SCEVUnknown, don't bother to save 4091 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4092 // increase the complexity of the expansion code. 4093 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4094 // because it may generate add/sub instead of GEP in SCEV expansion. 4095 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4096 !isa<GetElementPtrInst>(V)) 4097 ExprValueMap[Stripped].insert({V, Offset}); 4098 } 4099 } 4100 return S; 4101 } 4102 4103 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4104 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4105 4106 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4107 if (I != ValueExprMap.end()) { 4108 const SCEV *S = I->second; 4109 if (checkValidity(S)) 4110 return S; 4111 eraseValueFromMap(V); 4112 forgetMemoizedResults(S); 4113 } 4114 return nullptr; 4115 } 4116 4117 /// Return a SCEV corresponding to -V = -1*V 4118 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4119 SCEV::NoWrapFlags Flags) { 4120 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4121 return getConstant( 4122 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4123 4124 Type *Ty = V->getType(); 4125 Ty = getEffectiveSCEVType(Ty); 4126 return getMulExpr(V, getMinusOne(Ty), Flags); 4127 } 4128 4129 /// If Expr computes ~A, return A else return nullptr 4130 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4131 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4132 if (!Add || Add->getNumOperands() != 2 || 4133 !Add->getOperand(0)->isAllOnesValue()) 4134 return nullptr; 4135 4136 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4137 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4138 !AddRHS->getOperand(0)->isAllOnesValue()) 4139 return nullptr; 4140 4141 return AddRHS->getOperand(1); 4142 } 4143 4144 /// Return a SCEV corresponding to ~V = -1-V 4145 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4146 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4147 4148 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4149 return getConstant( 4150 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4151 4152 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4153 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4154 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4155 SmallVector<const SCEV *, 2> MatchedOperands; 4156 for (const SCEV *Operand : MME->operands()) { 4157 const SCEV *Matched = MatchNotExpr(Operand); 4158 if (!Matched) 4159 return (const SCEV *)nullptr; 4160 MatchedOperands.push_back(Matched); 4161 } 4162 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4163 MatchedOperands); 4164 }; 4165 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4166 return Replaced; 4167 } 4168 4169 Type *Ty = V->getType(); 4170 Ty = getEffectiveSCEVType(Ty); 4171 return getMinusSCEV(getMinusOne(Ty), V); 4172 } 4173 4174 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4175 assert(P->getType()->isPointerTy()); 4176 4177 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4178 // The base of an AddRec is the first operand. 4179 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4180 Ops[0] = removePointerBase(Ops[0]); 4181 // Don't try to transfer nowrap flags for now. We could in some cases 4182 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4183 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4184 } 4185 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4186 // The base of an Add is the pointer operand. 4187 SmallVector<const SCEV *> Ops{Add->operands()}; 4188 const SCEV **PtrOp = nullptr; 4189 for (const SCEV *&AddOp : Ops) { 4190 if (AddOp->getType()->isPointerTy()) { 4191 assert(!PtrOp && "Cannot have multiple pointer ops"); 4192 PtrOp = &AddOp; 4193 } 4194 } 4195 *PtrOp = removePointerBase(*PtrOp); 4196 // Don't try to transfer nowrap flags for now. We could in some cases 4197 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4198 return getAddExpr(Ops); 4199 } 4200 // Any other expression must be a pointer base. 4201 return getZero(P->getType()); 4202 } 4203 4204 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4205 SCEV::NoWrapFlags Flags, 4206 unsigned Depth) { 4207 // Fast path: X - X --> 0. 4208 if (LHS == RHS) 4209 return getZero(LHS->getType()); 4210 4211 // If we subtract two pointers with different pointer bases, bail. 4212 // Eventually, we're going to add an assertion to getMulExpr that we 4213 // can't multiply by a pointer. 4214 if (RHS->getType()->isPointerTy()) { 4215 if (!LHS->getType()->isPointerTy() || 4216 getPointerBase(LHS) != getPointerBase(RHS)) 4217 return getCouldNotCompute(); 4218 LHS = removePointerBase(LHS); 4219 RHS = removePointerBase(RHS); 4220 } 4221 4222 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4223 // makes it so that we cannot make much use of NUW. 4224 auto AddFlags = SCEV::FlagAnyWrap; 4225 const bool RHSIsNotMinSigned = 4226 !getSignedRangeMin(RHS).isMinSignedValue(); 4227 if (hasFlags(Flags, SCEV::FlagNSW)) { 4228 // Let M be the minimum representable signed value. Then (-1)*RHS 4229 // signed-wraps if and only if RHS is M. That can happen even for 4230 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4231 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4232 // (-1)*RHS, we need to prove that RHS != M. 4233 // 4234 // If LHS is non-negative and we know that LHS - RHS does not 4235 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4236 // either by proving that RHS > M or that LHS >= 0. 4237 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4238 AddFlags = SCEV::FlagNSW; 4239 } 4240 } 4241 4242 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4243 // RHS is NSW and LHS >= 0. 4244 // 4245 // The difficulty here is that the NSW flag may have been proven 4246 // relative to a loop that is to be found in a recurrence in LHS and 4247 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4248 // larger scope than intended. 4249 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4250 4251 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4252 } 4253 4254 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4255 unsigned Depth) { 4256 Type *SrcTy = V->getType(); 4257 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4258 "Cannot truncate or zero extend with non-integer arguments!"); 4259 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4260 return V; // No conversion 4261 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4262 return getTruncateExpr(V, Ty, Depth); 4263 return getZeroExtendExpr(V, Ty, Depth); 4264 } 4265 4266 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4267 unsigned Depth) { 4268 Type *SrcTy = V->getType(); 4269 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4270 "Cannot truncate or zero extend with non-integer arguments!"); 4271 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4272 return V; // No conversion 4273 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4274 return getTruncateExpr(V, Ty, Depth); 4275 return getSignExtendExpr(V, Ty, Depth); 4276 } 4277 4278 const SCEV * 4279 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4280 Type *SrcTy = V->getType(); 4281 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4282 "Cannot noop or zero extend with non-integer arguments!"); 4283 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4284 "getNoopOrZeroExtend cannot truncate!"); 4285 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4286 return V; // No conversion 4287 return getZeroExtendExpr(V, Ty); 4288 } 4289 4290 const SCEV * 4291 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4292 Type *SrcTy = V->getType(); 4293 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4294 "Cannot noop or sign extend with non-integer arguments!"); 4295 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4296 "getNoopOrSignExtend cannot truncate!"); 4297 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4298 return V; // No conversion 4299 return getSignExtendExpr(V, Ty); 4300 } 4301 4302 const SCEV * 4303 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4304 Type *SrcTy = V->getType(); 4305 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4306 "Cannot noop or any extend with non-integer arguments!"); 4307 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4308 "getNoopOrAnyExtend cannot truncate!"); 4309 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4310 return V; // No conversion 4311 return getAnyExtendExpr(V, Ty); 4312 } 4313 4314 const SCEV * 4315 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4316 Type *SrcTy = V->getType(); 4317 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4318 "Cannot truncate or noop with non-integer arguments!"); 4319 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4320 "getTruncateOrNoop cannot extend!"); 4321 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4322 return V; // No conversion 4323 return getTruncateExpr(V, Ty); 4324 } 4325 4326 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4327 const SCEV *RHS) { 4328 const SCEV *PromotedLHS = LHS; 4329 const SCEV *PromotedRHS = RHS; 4330 4331 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4332 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4333 else 4334 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4335 4336 return getUMaxExpr(PromotedLHS, PromotedRHS); 4337 } 4338 4339 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4340 const SCEV *RHS) { 4341 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4342 return getUMinFromMismatchedTypes(Ops); 4343 } 4344 4345 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4346 SmallVectorImpl<const SCEV *> &Ops) { 4347 assert(!Ops.empty() && "At least one operand must be!"); 4348 // Trivial case. 4349 if (Ops.size() == 1) 4350 return Ops[0]; 4351 4352 // Find the max type first. 4353 Type *MaxType = nullptr; 4354 for (auto *S : Ops) 4355 if (MaxType) 4356 MaxType = getWiderType(MaxType, S->getType()); 4357 else 4358 MaxType = S->getType(); 4359 assert(MaxType && "Failed to find maximum type!"); 4360 4361 // Extend all ops to max type. 4362 SmallVector<const SCEV *, 2> PromotedOps; 4363 for (auto *S : Ops) 4364 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4365 4366 // Generate umin. 4367 return getUMinExpr(PromotedOps); 4368 } 4369 4370 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4371 // A pointer operand may evaluate to a nonpointer expression, such as null. 4372 if (!V->getType()->isPointerTy()) 4373 return V; 4374 4375 while (true) { 4376 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4377 V = AddRec->getStart(); 4378 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4379 const SCEV *PtrOp = nullptr; 4380 for (const SCEV *AddOp : Add->operands()) { 4381 if (AddOp->getType()->isPointerTy()) { 4382 assert(!PtrOp && "Cannot have multiple pointer ops"); 4383 PtrOp = AddOp; 4384 } 4385 } 4386 assert(PtrOp && "Must have pointer op"); 4387 V = PtrOp; 4388 } else // Not something we can look further into. 4389 return V; 4390 } 4391 } 4392 4393 /// Push users of the given Instruction onto the given Worklist. 4394 static void PushDefUseChildren(Instruction *I, 4395 SmallVectorImpl<Instruction *> &Worklist, 4396 SmallPtrSetImpl<Instruction *> &Visited) { 4397 // Push the def-use children onto the Worklist stack. 4398 for (User *U : I->users()) { 4399 auto *UserInsn = cast<Instruction>(U); 4400 if (Visited.insert(UserInsn).second) 4401 Worklist.push_back(UserInsn); 4402 } 4403 } 4404 4405 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4406 SmallVector<Instruction *, 16> Worklist; 4407 SmallPtrSet<Instruction *, 8> Visited; 4408 SmallVector<const SCEV *, 8> ToForget; 4409 Visited.insert(PN); 4410 Worklist.push_back(PN); 4411 while (!Worklist.empty()) { 4412 Instruction *I = Worklist.pop_back_val(); 4413 4414 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4415 if (It != ValueExprMap.end()) { 4416 const SCEV *Old = It->second; 4417 4418 // Short-circuit the def-use traversal if the symbolic name 4419 // ceases to appear in expressions. 4420 if (Old != SymName && !hasOperand(Old, SymName)) 4421 continue; 4422 4423 // SCEVUnknown for a PHI either means that it has an unrecognized 4424 // structure, it's a PHI that's in the progress of being computed 4425 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4426 // additional loop trip count information isn't going to change anything. 4427 // In the second case, createNodeForPHI will perform the necessary 4428 // updates on its own when it gets to that point. In the third, we do 4429 // want to forget the SCEVUnknown. 4430 if (!isa<PHINode>(I) || 4431 !isa<SCEVUnknown>(Old) || 4432 (I != PN && Old == SymName)) { 4433 eraseValueFromMap(It->first); 4434 ToForget.push_back(Old); 4435 } 4436 } 4437 4438 PushDefUseChildren(I, Worklist, Visited); 4439 } 4440 forgetMemoizedResults(ToForget); 4441 } 4442 4443 namespace { 4444 4445 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4446 /// expression in case its Loop is L. If it is not L then 4447 /// if IgnoreOtherLoops is true then use AddRec itself 4448 /// otherwise rewrite cannot be done. 4449 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4450 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4451 public: 4452 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4453 bool IgnoreOtherLoops = true) { 4454 SCEVInitRewriter Rewriter(L, SE); 4455 const SCEV *Result = Rewriter.visit(S); 4456 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4457 return SE.getCouldNotCompute(); 4458 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4459 ? SE.getCouldNotCompute() 4460 : Result; 4461 } 4462 4463 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4464 if (!SE.isLoopInvariant(Expr, L)) 4465 SeenLoopVariantSCEVUnknown = true; 4466 return Expr; 4467 } 4468 4469 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4470 // Only re-write AddRecExprs for this loop. 4471 if (Expr->getLoop() == L) 4472 return Expr->getStart(); 4473 SeenOtherLoops = true; 4474 return Expr; 4475 } 4476 4477 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4478 4479 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4480 4481 private: 4482 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4483 : SCEVRewriteVisitor(SE), L(L) {} 4484 4485 const Loop *L; 4486 bool SeenLoopVariantSCEVUnknown = false; 4487 bool SeenOtherLoops = false; 4488 }; 4489 4490 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4491 /// increment expression in case its Loop is L. If it is not L then 4492 /// use AddRec itself. 4493 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4494 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4495 public: 4496 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4497 SCEVPostIncRewriter Rewriter(L, SE); 4498 const SCEV *Result = Rewriter.visit(S); 4499 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4500 ? SE.getCouldNotCompute() 4501 : Result; 4502 } 4503 4504 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4505 if (!SE.isLoopInvariant(Expr, L)) 4506 SeenLoopVariantSCEVUnknown = true; 4507 return Expr; 4508 } 4509 4510 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4511 // Only re-write AddRecExprs for this loop. 4512 if (Expr->getLoop() == L) 4513 return Expr->getPostIncExpr(SE); 4514 SeenOtherLoops = true; 4515 return Expr; 4516 } 4517 4518 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4519 4520 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4521 4522 private: 4523 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4524 : SCEVRewriteVisitor(SE), L(L) {} 4525 4526 const Loop *L; 4527 bool SeenLoopVariantSCEVUnknown = false; 4528 bool SeenOtherLoops = false; 4529 }; 4530 4531 /// This class evaluates the compare condition by matching it against the 4532 /// condition of loop latch. If there is a match we assume a true value 4533 /// for the condition while building SCEV nodes. 4534 class SCEVBackedgeConditionFolder 4535 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4536 public: 4537 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4538 ScalarEvolution &SE) { 4539 bool IsPosBECond = false; 4540 Value *BECond = nullptr; 4541 if (BasicBlock *Latch = L->getLoopLatch()) { 4542 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4543 if (BI && BI->isConditional()) { 4544 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4545 "Both outgoing branches should not target same header!"); 4546 BECond = BI->getCondition(); 4547 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4548 } else { 4549 return S; 4550 } 4551 } 4552 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4553 return Rewriter.visit(S); 4554 } 4555 4556 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4557 const SCEV *Result = Expr; 4558 bool InvariantF = SE.isLoopInvariant(Expr, L); 4559 4560 if (!InvariantF) { 4561 Instruction *I = cast<Instruction>(Expr->getValue()); 4562 switch (I->getOpcode()) { 4563 case Instruction::Select: { 4564 SelectInst *SI = cast<SelectInst>(I); 4565 Optional<const SCEV *> Res = 4566 compareWithBackedgeCondition(SI->getCondition()); 4567 if (Res.hasValue()) { 4568 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4569 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4570 } 4571 break; 4572 } 4573 default: { 4574 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4575 if (Res.hasValue()) 4576 Result = Res.getValue(); 4577 break; 4578 } 4579 } 4580 } 4581 return Result; 4582 } 4583 4584 private: 4585 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4586 bool IsPosBECond, ScalarEvolution &SE) 4587 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4588 IsPositiveBECond(IsPosBECond) {} 4589 4590 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4591 4592 const Loop *L; 4593 /// Loop back condition. 4594 Value *BackedgeCond = nullptr; 4595 /// Set to true if loop back is on positive branch condition. 4596 bool IsPositiveBECond; 4597 }; 4598 4599 Optional<const SCEV *> 4600 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4601 4602 // If value matches the backedge condition for loop latch, 4603 // then return a constant evolution node based on loopback 4604 // branch taken. 4605 if (BackedgeCond == IC) 4606 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4607 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4608 return None; 4609 } 4610 4611 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4612 public: 4613 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4614 ScalarEvolution &SE) { 4615 SCEVShiftRewriter Rewriter(L, SE); 4616 const SCEV *Result = Rewriter.visit(S); 4617 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4618 } 4619 4620 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4621 // Only allow AddRecExprs for this loop. 4622 if (!SE.isLoopInvariant(Expr, L)) 4623 Valid = false; 4624 return Expr; 4625 } 4626 4627 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4628 if (Expr->getLoop() == L && Expr->isAffine()) 4629 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4630 Valid = false; 4631 return Expr; 4632 } 4633 4634 bool isValid() { return Valid; } 4635 4636 private: 4637 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4638 : SCEVRewriteVisitor(SE), L(L) {} 4639 4640 const Loop *L; 4641 bool Valid = true; 4642 }; 4643 4644 } // end anonymous namespace 4645 4646 SCEV::NoWrapFlags 4647 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4648 if (!AR->isAffine()) 4649 return SCEV::FlagAnyWrap; 4650 4651 using OBO = OverflowingBinaryOperator; 4652 4653 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4654 4655 if (!AR->hasNoSignedWrap()) { 4656 ConstantRange AddRecRange = getSignedRange(AR); 4657 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4658 4659 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4660 Instruction::Add, IncRange, OBO::NoSignedWrap); 4661 if (NSWRegion.contains(AddRecRange)) 4662 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4663 } 4664 4665 if (!AR->hasNoUnsignedWrap()) { 4666 ConstantRange AddRecRange = getUnsignedRange(AR); 4667 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4668 4669 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4670 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4671 if (NUWRegion.contains(AddRecRange)) 4672 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4673 } 4674 4675 return Result; 4676 } 4677 4678 SCEV::NoWrapFlags 4679 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4680 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4681 4682 if (AR->hasNoSignedWrap()) 4683 return Result; 4684 4685 if (!AR->isAffine()) 4686 return Result; 4687 4688 const SCEV *Step = AR->getStepRecurrence(*this); 4689 const Loop *L = AR->getLoop(); 4690 4691 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4692 // Note that this serves two purposes: It filters out loops that are 4693 // simply not analyzable, and it covers the case where this code is 4694 // being called from within backedge-taken count analysis, such that 4695 // attempting to ask for the backedge-taken count would likely result 4696 // in infinite recursion. In the later case, the analysis code will 4697 // cope with a conservative value, and it will take care to purge 4698 // that value once it has finished. 4699 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4700 4701 // Normally, in the cases we can prove no-overflow via a 4702 // backedge guarding condition, we can also compute a backedge 4703 // taken count for the loop. The exceptions are assumptions and 4704 // guards present in the loop -- SCEV is not great at exploiting 4705 // these to compute max backedge taken counts, but can still use 4706 // these to prove lack of overflow. Use this fact to avoid 4707 // doing extra work that may not pay off. 4708 4709 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4710 AC.assumptions().empty()) 4711 return Result; 4712 4713 // If the backedge is guarded by a comparison with the pre-inc value the 4714 // addrec is safe. Also, if the entry is guarded by a comparison with the 4715 // start value and the backedge is guarded by a comparison with the post-inc 4716 // value, the addrec is safe. 4717 ICmpInst::Predicate Pred; 4718 const SCEV *OverflowLimit = 4719 getSignedOverflowLimitForStep(Step, &Pred, this); 4720 if (OverflowLimit && 4721 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4722 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4723 Result = setFlags(Result, SCEV::FlagNSW); 4724 } 4725 return Result; 4726 } 4727 SCEV::NoWrapFlags 4728 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4729 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4730 4731 if (AR->hasNoUnsignedWrap()) 4732 return Result; 4733 4734 if (!AR->isAffine()) 4735 return Result; 4736 4737 const SCEV *Step = AR->getStepRecurrence(*this); 4738 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4739 const Loop *L = AR->getLoop(); 4740 4741 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4742 // Note that this serves two purposes: It filters out loops that are 4743 // simply not analyzable, and it covers the case where this code is 4744 // being called from within backedge-taken count analysis, such that 4745 // attempting to ask for the backedge-taken count would likely result 4746 // in infinite recursion. In the later case, the analysis code will 4747 // cope with a conservative value, and it will take care to purge 4748 // that value once it has finished. 4749 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4750 4751 // Normally, in the cases we can prove no-overflow via a 4752 // backedge guarding condition, we can also compute a backedge 4753 // taken count for the loop. The exceptions are assumptions and 4754 // guards present in the loop -- SCEV is not great at exploiting 4755 // these to compute max backedge taken counts, but can still use 4756 // these to prove lack of overflow. Use this fact to avoid 4757 // doing extra work that may not pay off. 4758 4759 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4760 AC.assumptions().empty()) 4761 return Result; 4762 4763 // If the backedge is guarded by a comparison with the pre-inc value the 4764 // addrec is safe. Also, if the entry is guarded by a comparison with the 4765 // start value and the backedge is guarded by a comparison with the post-inc 4766 // value, the addrec is safe. 4767 if (isKnownPositive(Step)) { 4768 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4769 getUnsignedRangeMax(Step)); 4770 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4771 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4772 Result = setFlags(Result, SCEV::FlagNUW); 4773 } 4774 } 4775 4776 return Result; 4777 } 4778 4779 namespace { 4780 4781 /// Represents an abstract binary operation. This may exist as a 4782 /// normal instruction or constant expression, or may have been 4783 /// derived from an expression tree. 4784 struct BinaryOp { 4785 unsigned Opcode; 4786 Value *LHS; 4787 Value *RHS; 4788 bool IsNSW = false; 4789 bool IsNUW = false; 4790 4791 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4792 /// constant expression. 4793 Operator *Op = nullptr; 4794 4795 explicit BinaryOp(Operator *Op) 4796 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4797 Op(Op) { 4798 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4799 IsNSW = OBO->hasNoSignedWrap(); 4800 IsNUW = OBO->hasNoUnsignedWrap(); 4801 } 4802 } 4803 4804 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4805 bool IsNUW = false) 4806 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4807 }; 4808 4809 } // end anonymous namespace 4810 4811 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4812 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4813 auto *Op = dyn_cast<Operator>(V); 4814 if (!Op) 4815 return None; 4816 4817 // Implementation detail: all the cleverness here should happen without 4818 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4819 // SCEV expressions when possible, and we should not break that. 4820 4821 switch (Op->getOpcode()) { 4822 case Instruction::Add: 4823 case Instruction::Sub: 4824 case Instruction::Mul: 4825 case Instruction::UDiv: 4826 case Instruction::URem: 4827 case Instruction::And: 4828 case Instruction::Or: 4829 case Instruction::AShr: 4830 case Instruction::Shl: 4831 return BinaryOp(Op); 4832 4833 case Instruction::Xor: 4834 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4835 // If the RHS of the xor is a signmask, then this is just an add. 4836 // Instcombine turns add of signmask into xor as a strength reduction step. 4837 if (RHSC->getValue().isSignMask()) 4838 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4839 return BinaryOp(Op); 4840 4841 case Instruction::LShr: 4842 // Turn logical shift right of a constant into a unsigned divide. 4843 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4844 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4845 4846 // If the shift count is not less than the bitwidth, the result of 4847 // the shift is undefined. Don't try to analyze it, because the 4848 // resolution chosen here may differ from the resolution chosen in 4849 // other parts of the compiler. 4850 if (SA->getValue().ult(BitWidth)) { 4851 Constant *X = 4852 ConstantInt::get(SA->getContext(), 4853 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4854 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4855 } 4856 } 4857 return BinaryOp(Op); 4858 4859 case Instruction::ExtractValue: { 4860 auto *EVI = cast<ExtractValueInst>(Op); 4861 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4862 break; 4863 4864 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4865 if (!WO) 4866 break; 4867 4868 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4869 bool Signed = WO->isSigned(); 4870 // TODO: Should add nuw/nsw flags for mul as well. 4871 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4872 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4873 4874 // Now that we know that all uses of the arithmetic-result component of 4875 // CI are guarded by the overflow check, we can go ahead and pretend 4876 // that the arithmetic is non-overflowing. 4877 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4878 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4879 } 4880 4881 default: 4882 break; 4883 } 4884 4885 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4886 // semantics as a Sub, return a binary sub expression. 4887 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4888 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4889 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4890 4891 return None; 4892 } 4893 4894 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4895 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4896 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4897 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4898 /// follows one of the following patterns: 4899 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4900 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4901 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4902 /// we return the type of the truncation operation, and indicate whether the 4903 /// truncated type should be treated as signed/unsigned by setting 4904 /// \p Signed to true/false, respectively. 4905 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4906 bool &Signed, ScalarEvolution &SE) { 4907 // The case where Op == SymbolicPHI (that is, with no type conversions on 4908 // the way) is handled by the regular add recurrence creating logic and 4909 // would have already been triggered in createAddRecForPHI. Reaching it here 4910 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4911 // because one of the other operands of the SCEVAddExpr updating this PHI is 4912 // not invariant). 4913 // 4914 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4915 // this case predicates that allow us to prove that Op == SymbolicPHI will 4916 // be added. 4917 if (Op == SymbolicPHI) 4918 return nullptr; 4919 4920 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4921 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4922 if (SourceBits != NewBits) 4923 return nullptr; 4924 4925 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4926 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4927 if (!SExt && !ZExt) 4928 return nullptr; 4929 const SCEVTruncateExpr *Trunc = 4930 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4931 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4932 if (!Trunc) 4933 return nullptr; 4934 const SCEV *X = Trunc->getOperand(); 4935 if (X != SymbolicPHI) 4936 return nullptr; 4937 Signed = SExt != nullptr; 4938 return Trunc->getType(); 4939 } 4940 4941 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4942 if (!PN->getType()->isIntegerTy()) 4943 return nullptr; 4944 const Loop *L = LI.getLoopFor(PN->getParent()); 4945 if (!L || L->getHeader() != PN->getParent()) 4946 return nullptr; 4947 return L; 4948 } 4949 4950 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4951 // computation that updates the phi follows the following pattern: 4952 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4953 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4954 // If so, try to see if it can be rewritten as an AddRecExpr under some 4955 // Predicates. If successful, return them as a pair. Also cache the results 4956 // of the analysis. 4957 // 4958 // Example usage scenario: 4959 // Say the Rewriter is called for the following SCEV: 4960 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4961 // where: 4962 // %X = phi i64 (%Start, %BEValue) 4963 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4964 // and call this function with %SymbolicPHI = %X. 4965 // 4966 // The analysis will find that the value coming around the backedge has 4967 // the following SCEV: 4968 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4969 // Upon concluding that this matches the desired pattern, the function 4970 // will return the pair {NewAddRec, SmallPredsVec} where: 4971 // NewAddRec = {%Start,+,%Step} 4972 // SmallPredsVec = {P1, P2, P3} as follows: 4973 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4974 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4975 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4976 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4977 // under the predicates {P1,P2,P3}. 4978 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4979 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4980 // 4981 // TODO's: 4982 // 4983 // 1) Extend the Induction descriptor to also support inductions that involve 4984 // casts: When needed (namely, when we are called in the context of the 4985 // vectorizer induction analysis), a Set of cast instructions will be 4986 // populated by this method, and provided back to isInductionPHI. This is 4987 // needed to allow the vectorizer to properly record them to be ignored by 4988 // the cost model and to avoid vectorizing them (otherwise these casts, 4989 // which are redundant under the runtime overflow checks, will be 4990 // vectorized, which can be costly). 4991 // 4992 // 2) Support additional induction/PHISCEV patterns: We also want to support 4993 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4994 // after the induction update operation (the induction increment): 4995 // 4996 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4997 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4998 // 4999 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5000 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5001 // 5002 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5003 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5004 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5005 SmallVector<const SCEVPredicate *, 3> Predicates; 5006 5007 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5008 // return an AddRec expression under some predicate. 5009 5010 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5011 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5012 assert(L && "Expecting an integer loop header phi"); 5013 5014 // The loop may have multiple entrances or multiple exits; we can analyze 5015 // this phi as an addrec if it has a unique entry value and a unique 5016 // backedge value. 5017 Value *BEValueV = nullptr, *StartValueV = nullptr; 5018 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5019 Value *V = PN->getIncomingValue(i); 5020 if (L->contains(PN->getIncomingBlock(i))) { 5021 if (!BEValueV) { 5022 BEValueV = V; 5023 } else if (BEValueV != V) { 5024 BEValueV = nullptr; 5025 break; 5026 } 5027 } else if (!StartValueV) { 5028 StartValueV = V; 5029 } else if (StartValueV != V) { 5030 StartValueV = nullptr; 5031 break; 5032 } 5033 } 5034 if (!BEValueV || !StartValueV) 5035 return None; 5036 5037 const SCEV *BEValue = getSCEV(BEValueV); 5038 5039 // If the value coming around the backedge is an add with the symbolic 5040 // value we just inserted, possibly with casts that we can ignore under 5041 // an appropriate runtime guard, then we found a simple induction variable! 5042 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5043 if (!Add) 5044 return None; 5045 5046 // If there is a single occurrence of the symbolic value, possibly 5047 // casted, replace it with a recurrence. 5048 unsigned FoundIndex = Add->getNumOperands(); 5049 Type *TruncTy = nullptr; 5050 bool Signed; 5051 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5052 if ((TruncTy = 5053 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5054 if (FoundIndex == e) { 5055 FoundIndex = i; 5056 break; 5057 } 5058 5059 if (FoundIndex == Add->getNumOperands()) 5060 return None; 5061 5062 // Create an add with everything but the specified operand. 5063 SmallVector<const SCEV *, 8> Ops; 5064 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5065 if (i != FoundIndex) 5066 Ops.push_back(Add->getOperand(i)); 5067 const SCEV *Accum = getAddExpr(Ops); 5068 5069 // The runtime checks will not be valid if the step amount is 5070 // varying inside the loop. 5071 if (!isLoopInvariant(Accum, L)) 5072 return None; 5073 5074 // *** Part2: Create the predicates 5075 5076 // Analysis was successful: we have a phi-with-cast pattern for which we 5077 // can return an AddRec expression under the following predicates: 5078 // 5079 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5080 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5081 // P2: An Equal predicate that guarantees that 5082 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5083 // P3: An Equal predicate that guarantees that 5084 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5085 // 5086 // As we next prove, the above predicates guarantee that: 5087 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5088 // 5089 // 5090 // More formally, we want to prove that: 5091 // Expr(i+1) = Start + (i+1) * Accum 5092 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5093 // 5094 // Given that: 5095 // 1) Expr(0) = Start 5096 // 2) Expr(1) = Start + Accum 5097 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5098 // 3) Induction hypothesis (step i): 5099 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5100 // 5101 // Proof: 5102 // Expr(i+1) = 5103 // = Start + (i+1)*Accum 5104 // = (Start + i*Accum) + Accum 5105 // = Expr(i) + Accum 5106 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5107 // :: from step i 5108 // 5109 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5110 // 5111 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5112 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5113 // + Accum :: from P3 5114 // 5115 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5116 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5117 // 5118 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5119 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5120 // 5121 // By induction, the same applies to all iterations 1<=i<n: 5122 // 5123 5124 // Create a truncated addrec for which we will add a no overflow check (P1). 5125 const SCEV *StartVal = getSCEV(StartValueV); 5126 const SCEV *PHISCEV = 5127 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5128 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5129 5130 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5131 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5132 // will be constant. 5133 // 5134 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5135 // add P1. 5136 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5137 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5138 Signed ? SCEVWrapPredicate::IncrementNSSW 5139 : SCEVWrapPredicate::IncrementNUSW; 5140 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5141 Predicates.push_back(AddRecPred); 5142 } 5143 5144 // Create the Equal Predicates P2,P3: 5145 5146 // It is possible that the predicates P2 and/or P3 are computable at 5147 // compile time due to StartVal and/or Accum being constants. 5148 // If either one is, then we can check that now and escape if either P2 5149 // or P3 is false. 5150 5151 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5152 // for each of StartVal and Accum 5153 auto getExtendedExpr = [&](const SCEV *Expr, 5154 bool CreateSignExtend) -> const SCEV * { 5155 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5156 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5157 const SCEV *ExtendedExpr = 5158 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5159 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5160 return ExtendedExpr; 5161 }; 5162 5163 // Given: 5164 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5165 // = getExtendedExpr(Expr) 5166 // Determine whether the predicate P: Expr == ExtendedExpr 5167 // is known to be false at compile time 5168 auto PredIsKnownFalse = [&](const SCEV *Expr, 5169 const SCEV *ExtendedExpr) -> bool { 5170 return Expr != ExtendedExpr && 5171 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5172 }; 5173 5174 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5175 if (PredIsKnownFalse(StartVal, StartExtended)) { 5176 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5177 return None; 5178 } 5179 5180 // The Step is always Signed (because the overflow checks are either 5181 // NSSW or NUSW) 5182 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5183 if (PredIsKnownFalse(Accum, AccumExtended)) { 5184 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5185 return None; 5186 } 5187 5188 auto AppendPredicate = [&](const SCEV *Expr, 5189 const SCEV *ExtendedExpr) -> void { 5190 if (Expr != ExtendedExpr && 5191 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5192 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5193 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5194 Predicates.push_back(Pred); 5195 } 5196 }; 5197 5198 AppendPredicate(StartVal, StartExtended); 5199 AppendPredicate(Accum, AccumExtended); 5200 5201 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5202 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5203 // into NewAR if it will also add the runtime overflow checks specified in 5204 // Predicates. 5205 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5206 5207 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5208 std::make_pair(NewAR, Predicates); 5209 // Remember the result of the analysis for this SCEV at this locayyytion. 5210 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5211 return PredRewrite; 5212 } 5213 5214 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5215 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5216 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5217 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5218 if (!L) 5219 return None; 5220 5221 // Check to see if we already analyzed this PHI. 5222 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5223 if (I != PredicatedSCEVRewrites.end()) { 5224 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5225 I->second; 5226 // Analysis was done before and failed to create an AddRec: 5227 if (Rewrite.first == SymbolicPHI) 5228 return None; 5229 // Analysis was done before and succeeded to create an AddRec under 5230 // a predicate: 5231 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5232 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5233 return Rewrite; 5234 } 5235 5236 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5237 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5238 5239 // Record in the cache that the analysis failed 5240 if (!Rewrite) { 5241 SmallVector<const SCEVPredicate *, 3> Predicates; 5242 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5243 return None; 5244 } 5245 5246 return Rewrite; 5247 } 5248 5249 // FIXME: This utility is currently required because the Rewriter currently 5250 // does not rewrite this expression: 5251 // {0, +, (sext ix (trunc iy to ix) to iy)} 5252 // into {0, +, %step}, 5253 // even when the following Equal predicate exists: 5254 // "%step == (sext ix (trunc iy to ix) to iy)". 5255 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5256 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5257 if (AR1 == AR2) 5258 return true; 5259 5260 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5261 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5262 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5263 return false; 5264 return true; 5265 }; 5266 5267 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5268 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5269 return false; 5270 return true; 5271 } 5272 5273 /// A helper function for createAddRecFromPHI to handle simple cases. 5274 /// 5275 /// This function tries to find an AddRec expression for the simplest (yet most 5276 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5277 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5278 /// technique for finding the AddRec expression. 5279 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5280 Value *BEValueV, 5281 Value *StartValueV) { 5282 const Loop *L = LI.getLoopFor(PN->getParent()); 5283 assert(L && L->getHeader() == PN->getParent()); 5284 assert(BEValueV && StartValueV); 5285 5286 auto BO = MatchBinaryOp(BEValueV, DT); 5287 if (!BO) 5288 return nullptr; 5289 5290 if (BO->Opcode != Instruction::Add) 5291 return nullptr; 5292 5293 const SCEV *Accum = nullptr; 5294 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5295 Accum = getSCEV(BO->RHS); 5296 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5297 Accum = getSCEV(BO->LHS); 5298 5299 if (!Accum) 5300 return nullptr; 5301 5302 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5303 if (BO->IsNUW) 5304 Flags = setFlags(Flags, SCEV::FlagNUW); 5305 if (BO->IsNSW) 5306 Flags = setFlags(Flags, SCEV::FlagNSW); 5307 5308 const SCEV *StartVal = getSCEV(StartValueV); 5309 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5310 5311 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5312 5313 // We can add Flags to the post-inc expression only if we 5314 // know that it is *undefined behavior* for BEValueV to 5315 // overflow. 5316 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5317 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5318 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5319 5320 return PHISCEV; 5321 } 5322 5323 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5324 const Loop *L = LI.getLoopFor(PN->getParent()); 5325 if (!L || L->getHeader() != PN->getParent()) 5326 return nullptr; 5327 5328 // The loop may have multiple entrances or multiple exits; we can analyze 5329 // this phi as an addrec if it has a unique entry value and a unique 5330 // backedge value. 5331 Value *BEValueV = nullptr, *StartValueV = nullptr; 5332 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5333 Value *V = PN->getIncomingValue(i); 5334 if (L->contains(PN->getIncomingBlock(i))) { 5335 if (!BEValueV) { 5336 BEValueV = V; 5337 } else if (BEValueV != V) { 5338 BEValueV = nullptr; 5339 break; 5340 } 5341 } else if (!StartValueV) { 5342 StartValueV = V; 5343 } else if (StartValueV != V) { 5344 StartValueV = nullptr; 5345 break; 5346 } 5347 } 5348 if (!BEValueV || !StartValueV) 5349 return nullptr; 5350 5351 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5352 "PHI node already processed?"); 5353 5354 // First, try to find AddRec expression without creating a fictituos symbolic 5355 // value for PN. 5356 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5357 return S; 5358 5359 // Handle PHI node value symbolically. 5360 const SCEV *SymbolicName = getUnknown(PN); 5361 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5362 5363 // Using this symbolic name for the PHI, analyze the value coming around 5364 // the back-edge. 5365 const SCEV *BEValue = getSCEV(BEValueV); 5366 5367 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5368 // has a special value for the first iteration of the loop. 5369 5370 // If the value coming around the backedge is an add with the symbolic 5371 // value we just inserted, then we found a simple induction variable! 5372 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5373 // If there is a single occurrence of the symbolic value, replace it 5374 // with a recurrence. 5375 unsigned FoundIndex = Add->getNumOperands(); 5376 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5377 if (Add->getOperand(i) == SymbolicName) 5378 if (FoundIndex == e) { 5379 FoundIndex = i; 5380 break; 5381 } 5382 5383 if (FoundIndex != Add->getNumOperands()) { 5384 // Create an add with everything but the specified operand. 5385 SmallVector<const SCEV *, 8> Ops; 5386 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5387 if (i != FoundIndex) 5388 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5389 L, *this)); 5390 const SCEV *Accum = getAddExpr(Ops); 5391 5392 // This is not a valid addrec if the step amount is varying each 5393 // loop iteration, but is not itself an addrec in this loop. 5394 if (isLoopInvariant(Accum, L) || 5395 (isa<SCEVAddRecExpr>(Accum) && 5396 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5397 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5398 5399 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5400 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5401 if (BO->IsNUW) 5402 Flags = setFlags(Flags, SCEV::FlagNUW); 5403 if (BO->IsNSW) 5404 Flags = setFlags(Flags, SCEV::FlagNSW); 5405 } 5406 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5407 // If the increment is an inbounds GEP, then we know the address 5408 // space cannot be wrapped around. We cannot make any guarantee 5409 // about signed or unsigned overflow because pointers are 5410 // unsigned but we may have a negative index from the base 5411 // pointer. We can guarantee that no unsigned wrap occurs if the 5412 // indices form a positive value. 5413 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5414 Flags = setFlags(Flags, SCEV::FlagNW); 5415 5416 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5417 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5418 Flags = setFlags(Flags, SCEV::FlagNUW); 5419 } 5420 5421 // We cannot transfer nuw and nsw flags from subtraction 5422 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5423 // for instance. 5424 } 5425 5426 const SCEV *StartVal = getSCEV(StartValueV); 5427 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5428 5429 // Okay, for the entire analysis of this edge we assumed the PHI 5430 // to be symbolic. We now need to go back and purge all of the 5431 // entries for the scalars that use the symbolic expression. 5432 forgetSymbolicName(PN, SymbolicName); 5433 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5434 5435 // We can add Flags to the post-inc expression only if we 5436 // know that it is *undefined behavior* for BEValueV to 5437 // overflow. 5438 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5439 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5440 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5441 5442 return PHISCEV; 5443 } 5444 } 5445 } else { 5446 // Otherwise, this could be a loop like this: 5447 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5448 // In this case, j = {1,+,1} and BEValue is j. 5449 // Because the other in-value of i (0) fits the evolution of BEValue 5450 // i really is an addrec evolution. 5451 // 5452 // We can generalize this saying that i is the shifted value of BEValue 5453 // by one iteration: 5454 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5455 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5456 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5457 if (Shifted != getCouldNotCompute() && 5458 Start != getCouldNotCompute()) { 5459 const SCEV *StartVal = getSCEV(StartValueV); 5460 if (Start == StartVal) { 5461 // Okay, for the entire analysis of this edge we assumed the PHI 5462 // to be symbolic. We now need to go back and purge all of the 5463 // entries for the scalars that use the symbolic expression. 5464 forgetSymbolicName(PN, SymbolicName); 5465 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5466 return Shifted; 5467 } 5468 } 5469 } 5470 5471 // Remove the temporary PHI node SCEV that has been inserted while intending 5472 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5473 // as it will prevent later (possibly simpler) SCEV expressions to be added 5474 // to the ValueExprMap. 5475 eraseValueFromMap(PN); 5476 5477 return nullptr; 5478 } 5479 5480 // Checks if the SCEV S is available at BB. S is considered available at BB 5481 // if S can be materialized at BB without introducing a fault. 5482 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5483 BasicBlock *BB) { 5484 struct CheckAvailable { 5485 bool TraversalDone = false; 5486 bool Available = true; 5487 5488 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5489 BasicBlock *BB = nullptr; 5490 DominatorTree &DT; 5491 5492 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5493 : L(L), BB(BB), DT(DT) {} 5494 5495 bool setUnavailable() { 5496 TraversalDone = true; 5497 Available = false; 5498 return false; 5499 } 5500 5501 bool follow(const SCEV *S) { 5502 switch (S->getSCEVType()) { 5503 case scConstant: 5504 case scPtrToInt: 5505 case scTruncate: 5506 case scZeroExtend: 5507 case scSignExtend: 5508 case scAddExpr: 5509 case scMulExpr: 5510 case scUMaxExpr: 5511 case scSMaxExpr: 5512 case scUMinExpr: 5513 case scSMinExpr: 5514 // These expressions are available if their operand(s) is/are. 5515 return true; 5516 5517 case scAddRecExpr: { 5518 // We allow add recurrences that are on the loop BB is in, or some 5519 // outer loop. This guarantees availability because the value of the 5520 // add recurrence at BB is simply the "current" value of the induction 5521 // variable. We can relax this in the future; for instance an add 5522 // recurrence on a sibling dominating loop is also available at BB. 5523 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5524 if (L && (ARLoop == L || ARLoop->contains(L))) 5525 return true; 5526 5527 return setUnavailable(); 5528 } 5529 5530 case scUnknown: { 5531 // For SCEVUnknown, we check for simple dominance. 5532 const auto *SU = cast<SCEVUnknown>(S); 5533 Value *V = SU->getValue(); 5534 5535 if (isa<Argument>(V)) 5536 return false; 5537 5538 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5539 return false; 5540 5541 return setUnavailable(); 5542 } 5543 5544 case scUDivExpr: 5545 case scCouldNotCompute: 5546 // We do not try to smart about these at all. 5547 return setUnavailable(); 5548 } 5549 llvm_unreachable("Unknown SCEV kind!"); 5550 } 5551 5552 bool isDone() { return TraversalDone; } 5553 }; 5554 5555 CheckAvailable CA(L, BB, DT); 5556 SCEVTraversal<CheckAvailable> ST(CA); 5557 5558 ST.visitAll(S); 5559 return CA.Available; 5560 } 5561 5562 // Try to match a control flow sequence that branches out at BI and merges back 5563 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5564 // match. 5565 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5566 Value *&C, Value *&LHS, Value *&RHS) { 5567 C = BI->getCondition(); 5568 5569 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5570 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5571 5572 if (!LeftEdge.isSingleEdge()) 5573 return false; 5574 5575 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5576 5577 Use &LeftUse = Merge->getOperandUse(0); 5578 Use &RightUse = Merge->getOperandUse(1); 5579 5580 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5581 LHS = LeftUse; 5582 RHS = RightUse; 5583 return true; 5584 } 5585 5586 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5587 LHS = RightUse; 5588 RHS = LeftUse; 5589 return true; 5590 } 5591 5592 return false; 5593 } 5594 5595 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5596 auto IsReachable = 5597 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5598 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5599 const Loop *L = LI.getLoopFor(PN->getParent()); 5600 5601 // We don't want to break LCSSA, even in a SCEV expression tree. 5602 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5603 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5604 return nullptr; 5605 5606 // Try to match 5607 // 5608 // br %cond, label %left, label %right 5609 // left: 5610 // br label %merge 5611 // right: 5612 // br label %merge 5613 // merge: 5614 // V = phi [ %x, %left ], [ %y, %right ] 5615 // 5616 // as "select %cond, %x, %y" 5617 5618 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5619 assert(IDom && "At least the entry block should dominate PN"); 5620 5621 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5622 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5623 5624 if (BI && BI->isConditional() && 5625 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5626 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5627 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5628 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5629 } 5630 5631 return nullptr; 5632 } 5633 5634 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5635 if (const SCEV *S = createAddRecFromPHI(PN)) 5636 return S; 5637 5638 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5639 return S; 5640 5641 // If the PHI has a single incoming value, follow that value, unless the 5642 // PHI's incoming blocks are in a different loop, in which case doing so 5643 // risks breaking LCSSA form. Instcombine would normally zap these, but 5644 // it doesn't have DominatorTree information, so it may miss cases. 5645 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5646 if (LI.replacementPreservesLCSSAForm(PN, V)) 5647 return getSCEV(V); 5648 5649 // If it's not a loop phi, we can't handle it yet. 5650 return getUnknown(PN); 5651 } 5652 5653 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5654 Value *Cond, 5655 Value *TrueVal, 5656 Value *FalseVal) { 5657 // Handle "constant" branch or select. This can occur for instance when a 5658 // loop pass transforms an inner loop and moves on to process the outer loop. 5659 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5660 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5661 5662 // Try to match some simple smax or umax patterns. 5663 auto *ICI = dyn_cast<ICmpInst>(Cond); 5664 if (!ICI) 5665 return getUnknown(I); 5666 5667 Value *LHS = ICI->getOperand(0); 5668 Value *RHS = ICI->getOperand(1); 5669 5670 switch (ICI->getPredicate()) { 5671 case ICmpInst::ICMP_SLT: 5672 case ICmpInst::ICMP_SLE: 5673 case ICmpInst::ICMP_ULT: 5674 case ICmpInst::ICMP_ULE: 5675 std::swap(LHS, RHS); 5676 LLVM_FALLTHROUGH; 5677 case ICmpInst::ICMP_SGT: 5678 case ICmpInst::ICMP_SGE: 5679 case ICmpInst::ICMP_UGT: 5680 case ICmpInst::ICMP_UGE: 5681 // a > b ? a+x : b+x -> max(a, b)+x 5682 // a > b ? b+x : a+x -> min(a, b)+x 5683 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5684 bool Signed = ICI->isSigned(); 5685 const SCEV *LA = getSCEV(TrueVal); 5686 const SCEV *RA = getSCEV(FalseVal); 5687 const SCEV *LS = getSCEV(LHS); 5688 const SCEV *RS = getSCEV(RHS); 5689 if (LA->getType()->isPointerTy()) { 5690 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5691 // Need to make sure we can't produce weird expressions involving 5692 // negated pointers. 5693 if (LA == LS && RA == RS) 5694 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5695 if (LA == RS && RA == LS) 5696 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5697 } 5698 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5699 if (Op->getType()->isPointerTy()) { 5700 Op = getLosslessPtrToIntExpr(Op); 5701 if (isa<SCEVCouldNotCompute>(Op)) 5702 return Op; 5703 } 5704 if (Signed) 5705 Op = getNoopOrSignExtend(Op, I->getType()); 5706 else 5707 Op = getNoopOrZeroExtend(Op, I->getType()); 5708 return Op; 5709 }; 5710 LS = CoerceOperand(LS); 5711 RS = CoerceOperand(RS); 5712 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5713 break; 5714 const SCEV *LDiff = getMinusSCEV(LA, LS); 5715 const SCEV *RDiff = getMinusSCEV(RA, RS); 5716 if (LDiff == RDiff) 5717 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5718 LDiff); 5719 LDiff = getMinusSCEV(LA, RS); 5720 RDiff = getMinusSCEV(RA, LS); 5721 if (LDiff == RDiff) 5722 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5723 LDiff); 5724 } 5725 break; 5726 case ICmpInst::ICMP_NE: 5727 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5728 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5729 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5730 const SCEV *One = getOne(I->getType()); 5731 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5732 const SCEV *LA = getSCEV(TrueVal); 5733 const SCEV *RA = getSCEV(FalseVal); 5734 const SCEV *LDiff = getMinusSCEV(LA, LS); 5735 const SCEV *RDiff = getMinusSCEV(RA, One); 5736 if (LDiff == RDiff) 5737 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5738 } 5739 break; 5740 case ICmpInst::ICMP_EQ: 5741 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5742 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5743 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5744 const SCEV *One = getOne(I->getType()); 5745 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5746 const SCEV *LA = getSCEV(TrueVal); 5747 const SCEV *RA = getSCEV(FalseVal); 5748 const SCEV *LDiff = getMinusSCEV(LA, One); 5749 const SCEV *RDiff = getMinusSCEV(RA, LS); 5750 if (LDiff == RDiff) 5751 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5752 } 5753 break; 5754 default: 5755 break; 5756 } 5757 5758 return getUnknown(I); 5759 } 5760 5761 /// Expand GEP instructions into add and multiply operations. This allows them 5762 /// to be analyzed by regular SCEV code. 5763 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5764 // Don't attempt to analyze GEPs over unsized objects. 5765 if (!GEP->getSourceElementType()->isSized()) 5766 return getUnknown(GEP); 5767 5768 SmallVector<const SCEV *, 4> IndexExprs; 5769 for (Value *Index : GEP->indices()) 5770 IndexExprs.push_back(getSCEV(Index)); 5771 return getGEPExpr(GEP, IndexExprs); 5772 } 5773 5774 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5775 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5776 return C->getAPInt().countTrailingZeros(); 5777 5778 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5779 return GetMinTrailingZeros(I->getOperand()); 5780 5781 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5782 return std::min(GetMinTrailingZeros(T->getOperand()), 5783 (uint32_t)getTypeSizeInBits(T->getType())); 5784 5785 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5786 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5787 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5788 ? getTypeSizeInBits(E->getType()) 5789 : OpRes; 5790 } 5791 5792 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5793 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5794 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5795 ? getTypeSizeInBits(E->getType()) 5796 : OpRes; 5797 } 5798 5799 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5800 // The result is the min of all operands results. 5801 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5802 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5803 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5804 return MinOpRes; 5805 } 5806 5807 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5808 // The result is the sum of all operands results. 5809 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5810 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5811 for (unsigned i = 1, e = M->getNumOperands(); 5812 SumOpRes != BitWidth && i != e; ++i) 5813 SumOpRes = 5814 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5815 return SumOpRes; 5816 } 5817 5818 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5819 // The result is the min of all operands results. 5820 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5821 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5822 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5823 return MinOpRes; 5824 } 5825 5826 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5827 // The result is the min of all operands results. 5828 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5829 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5830 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5831 return MinOpRes; 5832 } 5833 5834 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5835 // The result is the min of all operands results. 5836 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5837 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5838 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5839 return MinOpRes; 5840 } 5841 5842 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5843 // For a SCEVUnknown, ask ValueTracking. 5844 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5845 return Known.countMinTrailingZeros(); 5846 } 5847 5848 // SCEVUDivExpr 5849 return 0; 5850 } 5851 5852 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5853 auto I = MinTrailingZerosCache.find(S); 5854 if (I != MinTrailingZerosCache.end()) 5855 return I->second; 5856 5857 uint32_t Result = GetMinTrailingZerosImpl(S); 5858 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5859 assert(InsertPair.second && "Should insert a new key"); 5860 return InsertPair.first->second; 5861 } 5862 5863 /// Helper method to assign a range to V from metadata present in the IR. 5864 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5865 if (Instruction *I = dyn_cast<Instruction>(V)) 5866 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5867 return getConstantRangeFromMetadata(*MD); 5868 5869 return None; 5870 } 5871 5872 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5873 SCEV::NoWrapFlags Flags) { 5874 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5875 AddRec->setNoWrapFlags(Flags); 5876 UnsignedRanges.erase(AddRec); 5877 SignedRanges.erase(AddRec); 5878 } 5879 } 5880 5881 ConstantRange ScalarEvolution:: 5882 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5883 const DataLayout &DL = getDataLayout(); 5884 5885 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5886 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5887 5888 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5889 // use information about the trip count to improve our available range. Note 5890 // that the trip count independent cases are already handled by known bits. 5891 // WARNING: The definition of recurrence used here is subtly different than 5892 // the one used by AddRec (and thus most of this file). Step is allowed to 5893 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5894 // and other addrecs in the same loop (for non-affine addrecs). The code 5895 // below intentionally handles the case where step is not loop invariant. 5896 auto *P = dyn_cast<PHINode>(U->getValue()); 5897 if (!P) 5898 return FullSet; 5899 5900 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5901 // even the values that are not available in these blocks may come from them, 5902 // and this leads to false-positive recurrence test. 5903 for (auto *Pred : predecessors(P->getParent())) 5904 if (!DT.isReachableFromEntry(Pred)) 5905 return FullSet; 5906 5907 BinaryOperator *BO; 5908 Value *Start, *Step; 5909 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5910 return FullSet; 5911 5912 // If we found a recurrence in reachable code, we must be in a loop. Note 5913 // that BO might be in some subloop of L, and that's completely okay. 5914 auto *L = LI.getLoopFor(P->getParent()); 5915 assert(L && L->getHeader() == P->getParent()); 5916 if (!L->contains(BO->getParent())) 5917 // NOTE: This bailout should be an assert instead. However, asserting 5918 // the condition here exposes a case where LoopFusion is querying SCEV 5919 // with malformed loop information during the midst of the transform. 5920 // There doesn't appear to be an obvious fix, so for the moment bailout 5921 // until the caller issue can be fixed. PR49566 tracks the bug. 5922 return FullSet; 5923 5924 // TODO: Extend to other opcodes such as mul, and div 5925 switch (BO->getOpcode()) { 5926 default: 5927 return FullSet; 5928 case Instruction::AShr: 5929 case Instruction::LShr: 5930 case Instruction::Shl: 5931 break; 5932 }; 5933 5934 if (BO->getOperand(0) != P) 5935 // TODO: Handle the power function forms some day. 5936 return FullSet; 5937 5938 unsigned TC = getSmallConstantMaxTripCount(L); 5939 if (!TC || TC >= BitWidth) 5940 return FullSet; 5941 5942 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5943 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5944 assert(KnownStart.getBitWidth() == BitWidth && 5945 KnownStep.getBitWidth() == BitWidth); 5946 5947 // Compute total shift amount, being careful of overflow and bitwidths. 5948 auto MaxShiftAmt = KnownStep.getMaxValue(); 5949 APInt TCAP(BitWidth, TC-1); 5950 bool Overflow = false; 5951 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5952 if (Overflow) 5953 return FullSet; 5954 5955 switch (BO->getOpcode()) { 5956 default: 5957 llvm_unreachable("filtered out above"); 5958 case Instruction::AShr: { 5959 // For each ashr, three cases: 5960 // shift = 0 => unchanged value 5961 // saturation => 0 or -1 5962 // other => a value closer to zero (of the same sign) 5963 // Thus, the end value is closer to zero than the start. 5964 auto KnownEnd = KnownBits::ashr(KnownStart, 5965 KnownBits::makeConstant(TotalShift)); 5966 if (KnownStart.isNonNegative()) 5967 // Analogous to lshr (simply not yet canonicalized) 5968 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5969 KnownStart.getMaxValue() + 1); 5970 if (KnownStart.isNegative()) 5971 // End >=u Start && End <=s Start 5972 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5973 KnownEnd.getMaxValue() + 1); 5974 break; 5975 } 5976 case Instruction::LShr: { 5977 // For each lshr, three cases: 5978 // shift = 0 => unchanged value 5979 // saturation => 0 5980 // other => a smaller positive number 5981 // Thus, the low end of the unsigned range is the last value produced. 5982 auto KnownEnd = KnownBits::lshr(KnownStart, 5983 KnownBits::makeConstant(TotalShift)); 5984 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5985 KnownStart.getMaxValue() + 1); 5986 } 5987 case Instruction::Shl: { 5988 // Iff no bits are shifted out, value increases on every shift. 5989 auto KnownEnd = KnownBits::shl(KnownStart, 5990 KnownBits::makeConstant(TotalShift)); 5991 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5992 return ConstantRange(KnownStart.getMinValue(), 5993 KnownEnd.getMaxValue() + 1); 5994 break; 5995 } 5996 }; 5997 return FullSet; 5998 } 5999 6000 /// Determine the range for a particular SCEV. If SignHint is 6001 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6002 /// with a "cleaner" unsigned (resp. signed) representation. 6003 const ConstantRange & 6004 ScalarEvolution::getRangeRef(const SCEV *S, 6005 ScalarEvolution::RangeSignHint SignHint) { 6006 DenseMap<const SCEV *, ConstantRange> &Cache = 6007 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6008 : SignedRanges; 6009 ConstantRange::PreferredRangeType RangeType = 6010 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6011 ? ConstantRange::Unsigned : ConstantRange::Signed; 6012 6013 // See if we've computed this range already. 6014 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6015 if (I != Cache.end()) 6016 return I->second; 6017 6018 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6019 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6020 6021 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6022 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6023 using OBO = OverflowingBinaryOperator; 6024 6025 // If the value has known zeros, the maximum value will have those known zeros 6026 // as well. 6027 uint32_t TZ = GetMinTrailingZeros(S); 6028 if (TZ != 0) { 6029 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6030 ConservativeResult = 6031 ConstantRange(APInt::getMinValue(BitWidth), 6032 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6033 else 6034 ConservativeResult = ConstantRange( 6035 APInt::getSignedMinValue(BitWidth), 6036 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6037 } 6038 6039 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6040 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6041 unsigned WrapType = OBO::AnyWrap; 6042 if (Add->hasNoSignedWrap()) 6043 WrapType |= OBO::NoSignedWrap; 6044 if (Add->hasNoUnsignedWrap()) 6045 WrapType |= OBO::NoUnsignedWrap; 6046 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6047 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6048 WrapType, RangeType); 6049 return setRange(Add, SignHint, 6050 ConservativeResult.intersectWith(X, RangeType)); 6051 } 6052 6053 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6054 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6055 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6056 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6057 return setRange(Mul, SignHint, 6058 ConservativeResult.intersectWith(X, RangeType)); 6059 } 6060 6061 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6062 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6063 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6064 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6065 return setRange(SMax, SignHint, 6066 ConservativeResult.intersectWith(X, RangeType)); 6067 } 6068 6069 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6070 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6071 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6072 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6073 return setRange(UMax, SignHint, 6074 ConservativeResult.intersectWith(X, RangeType)); 6075 } 6076 6077 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6078 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6079 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6080 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6081 return setRange(SMin, SignHint, 6082 ConservativeResult.intersectWith(X, RangeType)); 6083 } 6084 6085 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6086 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6087 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6088 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6089 return setRange(UMin, SignHint, 6090 ConservativeResult.intersectWith(X, RangeType)); 6091 } 6092 6093 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6094 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6095 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6096 return setRange(UDiv, SignHint, 6097 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6098 } 6099 6100 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6101 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6102 return setRange(ZExt, SignHint, 6103 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6104 RangeType)); 6105 } 6106 6107 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6108 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6109 return setRange(SExt, SignHint, 6110 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6111 RangeType)); 6112 } 6113 6114 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6115 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6116 return setRange(PtrToInt, SignHint, X); 6117 } 6118 6119 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6120 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6121 return setRange(Trunc, SignHint, 6122 ConservativeResult.intersectWith(X.truncate(BitWidth), 6123 RangeType)); 6124 } 6125 6126 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6127 // If there's no unsigned wrap, the value will never be less than its 6128 // initial value. 6129 if (AddRec->hasNoUnsignedWrap()) { 6130 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6131 if (!UnsignedMinValue.isZero()) 6132 ConservativeResult = ConservativeResult.intersectWith( 6133 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6134 } 6135 6136 // If there's no signed wrap, and all the operands except initial value have 6137 // the same sign or zero, the value won't ever be: 6138 // 1: smaller than initial value if operands are non negative, 6139 // 2: bigger than initial value if operands are non positive. 6140 // For both cases, value can not cross signed min/max boundary. 6141 if (AddRec->hasNoSignedWrap()) { 6142 bool AllNonNeg = true; 6143 bool AllNonPos = true; 6144 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6145 if (!isKnownNonNegative(AddRec->getOperand(i))) 6146 AllNonNeg = false; 6147 if (!isKnownNonPositive(AddRec->getOperand(i))) 6148 AllNonPos = false; 6149 } 6150 if (AllNonNeg) 6151 ConservativeResult = ConservativeResult.intersectWith( 6152 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6153 APInt::getSignedMinValue(BitWidth)), 6154 RangeType); 6155 else if (AllNonPos) 6156 ConservativeResult = ConservativeResult.intersectWith( 6157 ConstantRange::getNonEmpty( 6158 APInt::getSignedMinValue(BitWidth), 6159 getSignedRangeMax(AddRec->getStart()) + 1), 6160 RangeType); 6161 } 6162 6163 // TODO: non-affine addrec 6164 if (AddRec->isAffine()) { 6165 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6166 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6167 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6168 auto RangeFromAffine = getRangeForAffineAR( 6169 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6170 BitWidth); 6171 ConservativeResult = 6172 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6173 6174 auto RangeFromFactoring = getRangeViaFactoring( 6175 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6176 BitWidth); 6177 ConservativeResult = 6178 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6179 } 6180 6181 // Now try symbolic BE count and more powerful methods. 6182 if (UseExpensiveRangeSharpening) { 6183 const SCEV *SymbolicMaxBECount = 6184 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6185 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6186 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6187 AddRec->hasNoSelfWrap()) { 6188 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6189 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6190 ConservativeResult = 6191 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6192 } 6193 } 6194 } 6195 6196 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6197 } 6198 6199 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6200 6201 // Check if the IR explicitly contains !range metadata. 6202 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6203 if (MDRange.hasValue()) 6204 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6205 RangeType); 6206 6207 // Use facts about recurrences in the underlying IR. Note that add 6208 // recurrences are AddRecExprs and thus don't hit this path. This 6209 // primarily handles shift recurrences. 6210 auto CR = getRangeForUnknownRecurrence(U); 6211 ConservativeResult = ConservativeResult.intersectWith(CR); 6212 6213 // See if ValueTracking can give us a useful range. 6214 const DataLayout &DL = getDataLayout(); 6215 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6216 if (Known.getBitWidth() != BitWidth) 6217 Known = Known.zextOrTrunc(BitWidth); 6218 6219 // ValueTracking may be able to compute a tighter result for the number of 6220 // sign bits than for the value of those sign bits. 6221 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6222 if (U->getType()->isPointerTy()) { 6223 // If the pointer size is larger than the index size type, this can cause 6224 // NS to be larger than BitWidth. So compensate for this. 6225 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6226 int ptrIdxDiff = ptrSize - BitWidth; 6227 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6228 NS -= ptrIdxDiff; 6229 } 6230 6231 if (NS > 1) { 6232 // If we know any of the sign bits, we know all of the sign bits. 6233 if (!Known.Zero.getHiBits(NS).isZero()) 6234 Known.Zero.setHighBits(NS); 6235 if (!Known.One.getHiBits(NS).isZero()) 6236 Known.One.setHighBits(NS); 6237 } 6238 6239 if (Known.getMinValue() != Known.getMaxValue() + 1) 6240 ConservativeResult = ConservativeResult.intersectWith( 6241 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6242 RangeType); 6243 if (NS > 1) 6244 ConservativeResult = ConservativeResult.intersectWith( 6245 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6246 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6247 RangeType); 6248 6249 // A range of Phi is a subset of union of all ranges of its input. 6250 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6251 // Make sure that we do not run over cycled Phis. 6252 if (PendingPhiRanges.insert(Phi).second) { 6253 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6254 for (auto &Op : Phi->operands()) { 6255 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6256 RangeFromOps = RangeFromOps.unionWith(OpRange); 6257 // No point to continue if we already have a full set. 6258 if (RangeFromOps.isFullSet()) 6259 break; 6260 } 6261 ConservativeResult = 6262 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6263 bool Erased = PendingPhiRanges.erase(Phi); 6264 assert(Erased && "Failed to erase Phi properly?"); 6265 (void) Erased; 6266 } 6267 } 6268 6269 return setRange(U, SignHint, std::move(ConservativeResult)); 6270 } 6271 6272 return setRange(S, SignHint, std::move(ConservativeResult)); 6273 } 6274 6275 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6276 // values that the expression can take. Initially, the expression has a value 6277 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6278 // argument defines if we treat Step as signed or unsigned. 6279 static ConstantRange getRangeForAffineARHelper(APInt Step, 6280 const ConstantRange &StartRange, 6281 const APInt &MaxBECount, 6282 unsigned BitWidth, bool Signed) { 6283 // If either Step or MaxBECount is 0, then the expression won't change, and we 6284 // just need to return the initial range. 6285 if (Step == 0 || MaxBECount == 0) 6286 return StartRange; 6287 6288 // If we don't know anything about the initial value (i.e. StartRange is 6289 // FullRange), then we don't know anything about the final range either. 6290 // Return FullRange. 6291 if (StartRange.isFullSet()) 6292 return ConstantRange::getFull(BitWidth); 6293 6294 // If Step is signed and negative, then we use its absolute value, but we also 6295 // note that we're moving in the opposite direction. 6296 bool Descending = Signed && Step.isNegative(); 6297 6298 if (Signed) 6299 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6300 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6301 // This equations hold true due to the well-defined wrap-around behavior of 6302 // APInt. 6303 Step = Step.abs(); 6304 6305 // Check if Offset is more than full span of BitWidth. If it is, the 6306 // expression is guaranteed to overflow. 6307 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6308 return ConstantRange::getFull(BitWidth); 6309 6310 // Offset is by how much the expression can change. Checks above guarantee no 6311 // overflow here. 6312 APInt Offset = Step * MaxBECount; 6313 6314 // Minimum value of the final range will match the minimal value of StartRange 6315 // if the expression is increasing and will be decreased by Offset otherwise. 6316 // Maximum value of the final range will match the maximal value of StartRange 6317 // if the expression is decreasing and will be increased by Offset otherwise. 6318 APInt StartLower = StartRange.getLower(); 6319 APInt StartUpper = StartRange.getUpper() - 1; 6320 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6321 : (StartUpper + std::move(Offset)); 6322 6323 // It's possible that the new minimum/maximum value will fall into the initial 6324 // range (due to wrap around). This means that the expression can take any 6325 // value in this bitwidth, and we have to return full range. 6326 if (StartRange.contains(MovedBoundary)) 6327 return ConstantRange::getFull(BitWidth); 6328 6329 APInt NewLower = 6330 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6331 APInt NewUpper = 6332 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6333 NewUpper += 1; 6334 6335 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6336 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6337 } 6338 6339 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6340 const SCEV *Step, 6341 const SCEV *MaxBECount, 6342 unsigned BitWidth) { 6343 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6344 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6345 "Precondition!"); 6346 6347 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6348 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6349 6350 // First, consider step signed. 6351 ConstantRange StartSRange = getSignedRange(Start); 6352 ConstantRange StepSRange = getSignedRange(Step); 6353 6354 // If Step can be both positive and negative, we need to find ranges for the 6355 // maximum absolute step values in both directions and union them. 6356 ConstantRange SR = 6357 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6358 MaxBECountValue, BitWidth, /* Signed = */ true); 6359 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6360 StartSRange, MaxBECountValue, 6361 BitWidth, /* Signed = */ true)); 6362 6363 // Next, consider step unsigned. 6364 ConstantRange UR = getRangeForAffineARHelper( 6365 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6366 MaxBECountValue, BitWidth, /* Signed = */ false); 6367 6368 // Finally, intersect signed and unsigned ranges. 6369 return SR.intersectWith(UR, ConstantRange::Smallest); 6370 } 6371 6372 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6373 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6374 ScalarEvolution::RangeSignHint SignHint) { 6375 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6376 assert(AddRec->hasNoSelfWrap() && 6377 "This only works for non-self-wrapping AddRecs!"); 6378 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6379 const SCEV *Step = AddRec->getStepRecurrence(*this); 6380 // Only deal with constant step to save compile time. 6381 if (!isa<SCEVConstant>(Step)) 6382 return ConstantRange::getFull(BitWidth); 6383 // Let's make sure that we can prove that we do not self-wrap during 6384 // MaxBECount iterations. We need this because MaxBECount is a maximum 6385 // iteration count estimate, and we might infer nw from some exit for which we 6386 // do not know max exit count (or any other side reasoning). 6387 // TODO: Turn into assert at some point. 6388 if (getTypeSizeInBits(MaxBECount->getType()) > 6389 getTypeSizeInBits(AddRec->getType())) 6390 return ConstantRange::getFull(BitWidth); 6391 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6392 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6393 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6394 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6395 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6396 MaxItersWithoutWrap)) 6397 return ConstantRange::getFull(BitWidth); 6398 6399 ICmpInst::Predicate LEPred = 6400 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6401 ICmpInst::Predicate GEPred = 6402 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6403 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6404 6405 // We know that there is no self-wrap. Let's take Start and End values and 6406 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6407 // the iteration. They either lie inside the range [Min(Start, End), 6408 // Max(Start, End)] or outside it: 6409 // 6410 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6411 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6412 // 6413 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6414 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6415 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6416 // Start <= End and step is positive, or Start >= End and step is negative. 6417 const SCEV *Start = AddRec->getStart(); 6418 ConstantRange StartRange = getRangeRef(Start, SignHint); 6419 ConstantRange EndRange = getRangeRef(End, SignHint); 6420 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6421 // If they already cover full iteration space, we will know nothing useful 6422 // even if we prove what we want to prove. 6423 if (RangeBetween.isFullSet()) 6424 return RangeBetween; 6425 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6426 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6427 : RangeBetween.isWrappedSet(); 6428 if (IsWrappedSet) 6429 return ConstantRange::getFull(BitWidth); 6430 6431 if (isKnownPositive(Step) && 6432 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6433 return RangeBetween; 6434 else if (isKnownNegative(Step) && 6435 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6436 return RangeBetween; 6437 return ConstantRange::getFull(BitWidth); 6438 } 6439 6440 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6441 const SCEV *Step, 6442 const SCEV *MaxBECount, 6443 unsigned BitWidth) { 6444 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6445 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6446 6447 struct SelectPattern { 6448 Value *Condition = nullptr; 6449 APInt TrueValue; 6450 APInt FalseValue; 6451 6452 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6453 const SCEV *S) { 6454 Optional<unsigned> CastOp; 6455 APInt Offset(BitWidth, 0); 6456 6457 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6458 "Should be!"); 6459 6460 // Peel off a constant offset: 6461 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6462 // In the future we could consider being smarter here and handle 6463 // {Start+Step,+,Step} too. 6464 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6465 return; 6466 6467 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6468 S = SA->getOperand(1); 6469 } 6470 6471 // Peel off a cast operation 6472 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6473 CastOp = SCast->getSCEVType(); 6474 S = SCast->getOperand(); 6475 } 6476 6477 using namespace llvm::PatternMatch; 6478 6479 auto *SU = dyn_cast<SCEVUnknown>(S); 6480 const APInt *TrueVal, *FalseVal; 6481 if (!SU || 6482 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6483 m_APInt(FalseVal)))) { 6484 Condition = nullptr; 6485 return; 6486 } 6487 6488 TrueValue = *TrueVal; 6489 FalseValue = *FalseVal; 6490 6491 // Re-apply the cast we peeled off earlier 6492 if (CastOp.hasValue()) 6493 switch (*CastOp) { 6494 default: 6495 llvm_unreachable("Unknown SCEV cast type!"); 6496 6497 case scTruncate: 6498 TrueValue = TrueValue.trunc(BitWidth); 6499 FalseValue = FalseValue.trunc(BitWidth); 6500 break; 6501 case scZeroExtend: 6502 TrueValue = TrueValue.zext(BitWidth); 6503 FalseValue = FalseValue.zext(BitWidth); 6504 break; 6505 case scSignExtend: 6506 TrueValue = TrueValue.sext(BitWidth); 6507 FalseValue = FalseValue.sext(BitWidth); 6508 break; 6509 } 6510 6511 // Re-apply the constant offset we peeled off earlier 6512 TrueValue += Offset; 6513 FalseValue += Offset; 6514 } 6515 6516 bool isRecognized() { return Condition != nullptr; } 6517 }; 6518 6519 SelectPattern StartPattern(*this, BitWidth, Start); 6520 if (!StartPattern.isRecognized()) 6521 return ConstantRange::getFull(BitWidth); 6522 6523 SelectPattern StepPattern(*this, BitWidth, Step); 6524 if (!StepPattern.isRecognized()) 6525 return ConstantRange::getFull(BitWidth); 6526 6527 if (StartPattern.Condition != StepPattern.Condition) { 6528 // We don't handle this case today; but we could, by considering four 6529 // possibilities below instead of two. I'm not sure if there are cases where 6530 // that will help over what getRange already does, though. 6531 return ConstantRange::getFull(BitWidth); 6532 } 6533 6534 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6535 // construct arbitrary general SCEV expressions here. This function is called 6536 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6537 // say) can end up caching a suboptimal value. 6538 6539 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6540 // C2352 and C2512 (otherwise it isn't needed). 6541 6542 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6543 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6544 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6545 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6546 6547 ConstantRange TrueRange = 6548 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6549 ConstantRange FalseRange = 6550 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6551 6552 return TrueRange.unionWith(FalseRange); 6553 } 6554 6555 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6556 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6557 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6558 6559 // Return early if there are no flags to propagate to the SCEV. 6560 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6561 if (BinOp->hasNoUnsignedWrap()) 6562 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6563 if (BinOp->hasNoSignedWrap()) 6564 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6565 if (Flags == SCEV::FlagAnyWrap) 6566 return SCEV::FlagAnyWrap; 6567 6568 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6569 } 6570 6571 const Instruction * 6572 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6573 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6574 return &*AddRec->getLoop()->getHeader()->begin(); 6575 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6576 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6577 return I; 6578 return nullptr; 6579 } 6580 6581 /// Fills \p Ops with unique operands of \p S, if it has operands. If not, 6582 /// \p Ops remains unmodified. 6583 static void collectUniqueOps(const SCEV *S, 6584 SmallVectorImpl<const SCEV *> &Ops) { 6585 SmallPtrSet<const SCEV *, 4> Unique; 6586 auto InsertUnique = [&](const SCEV *S) { 6587 if (Unique.insert(S).second) 6588 Ops.push_back(S); 6589 }; 6590 if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6591 for (auto *Op : S2->operands()) 6592 InsertUnique(Op); 6593 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6594 for (auto *Op : S2->operands()) 6595 InsertUnique(Op); 6596 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6597 for (auto *Op : S2->operands()) 6598 InsertUnique(Op); 6599 } 6600 6601 const Instruction * 6602 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6603 // Do a bounded search of the def relation of the requested SCEVs. 6604 SmallSet<const SCEV *, 16> Visited; 6605 SmallVector<const SCEV *> Worklist; 6606 auto pushOp = [&](const SCEV *S) { 6607 if (!Visited.insert(S).second) 6608 return; 6609 // Threshold of 30 here is arbitrary. 6610 if (Visited.size() > 30) 6611 return; 6612 Worklist.push_back(S); 6613 }; 6614 6615 for (auto *S : Ops) 6616 pushOp(S); 6617 6618 const Instruction *Bound = nullptr; 6619 while (!Worklist.empty()) { 6620 auto *S = Worklist.pop_back_val(); 6621 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6622 if (!Bound || DT.dominates(Bound, DefI)) 6623 Bound = DefI; 6624 } else { 6625 SmallVector<const SCEV *, 4> Ops; 6626 collectUniqueOps(S, Ops); 6627 for (auto *Op : Ops) 6628 pushOp(Op); 6629 } 6630 } 6631 return Bound ? Bound : &*F.getEntryBlock().begin(); 6632 } 6633 6634 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6635 const Instruction *B) { 6636 if (A->getParent() == B->getParent() && 6637 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6638 B->getIterator())) 6639 return true; 6640 6641 auto *BLoop = LI.getLoopFor(B->getParent()); 6642 if (BLoop && BLoop->getHeader() == B->getParent() && 6643 BLoop->getLoopPreheader() == A->getParent() && 6644 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6645 A->getParent()->end()) && 6646 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6647 B->getIterator())) 6648 return true; 6649 return false; 6650 } 6651 6652 6653 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6654 // Only proceed if we can prove that I does not yield poison. 6655 if (!programUndefinedIfPoison(I)) 6656 return false; 6657 6658 // At this point we know that if I is executed, then it does not wrap 6659 // according to at least one of NSW or NUW. If I is not executed, then we do 6660 // not know if the calculation that I represents would wrap. Multiple 6661 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6662 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6663 // derived from other instructions that map to the same SCEV. We cannot make 6664 // that guarantee for cases where I is not executed. So we need to find a 6665 // upper bound on the defining scope for the SCEV, and prove that I is 6666 // executed every time we enter that scope. When the bounding scope is a 6667 // loop (the common case), this is equivalent to proving I executes on every 6668 // iteration of that loop. 6669 SmallVector<const SCEV *> SCEVOps; 6670 for (const Use &Op : I->operands()) { 6671 // I could be an extractvalue from a call to an overflow intrinsic. 6672 // TODO: We can do better here in some cases. 6673 if (isSCEVable(Op->getType())) 6674 SCEVOps.push_back(getSCEV(Op)); 6675 } 6676 auto *DefI = getDefiningScopeBound(SCEVOps); 6677 return isGuaranteedToTransferExecutionTo(DefI, I); 6678 } 6679 6680 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6681 // If we know that \c I can never be poison period, then that's enough. 6682 if (isSCEVExprNeverPoison(I)) 6683 return true; 6684 6685 // For an add recurrence specifically, we assume that infinite loops without 6686 // side effects are undefined behavior, and then reason as follows: 6687 // 6688 // If the add recurrence is poison in any iteration, it is poison on all 6689 // future iterations (since incrementing poison yields poison). If the result 6690 // of the add recurrence is fed into the loop latch condition and the loop 6691 // does not contain any throws or exiting blocks other than the latch, we now 6692 // have the ability to "choose" whether the backedge is taken or not (by 6693 // choosing a sufficiently evil value for the poison feeding into the branch) 6694 // for every iteration including and after the one in which \p I first became 6695 // poison. There are two possibilities (let's call the iteration in which \p 6696 // I first became poison as K): 6697 // 6698 // 1. In the set of iterations including and after K, the loop body executes 6699 // no side effects. In this case executing the backege an infinte number 6700 // of times will yield undefined behavior. 6701 // 6702 // 2. In the set of iterations including and after K, the loop body executes 6703 // at least one side effect. In this case, that specific instance of side 6704 // effect is control dependent on poison, which also yields undefined 6705 // behavior. 6706 6707 auto *ExitingBB = L->getExitingBlock(); 6708 auto *LatchBB = L->getLoopLatch(); 6709 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6710 return false; 6711 6712 SmallPtrSet<const Instruction *, 16> Pushed; 6713 SmallVector<const Instruction *, 8> PoisonStack; 6714 6715 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6716 // things that are known to be poison under that assumption go on the 6717 // PoisonStack. 6718 Pushed.insert(I); 6719 PoisonStack.push_back(I); 6720 6721 bool LatchControlDependentOnPoison = false; 6722 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6723 const Instruction *Poison = PoisonStack.pop_back_val(); 6724 6725 for (auto *PoisonUser : Poison->users()) { 6726 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6727 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6728 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6729 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6730 assert(BI->isConditional() && "Only possibility!"); 6731 if (BI->getParent() == LatchBB) { 6732 LatchControlDependentOnPoison = true; 6733 break; 6734 } 6735 } 6736 } 6737 } 6738 6739 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6740 } 6741 6742 ScalarEvolution::LoopProperties 6743 ScalarEvolution::getLoopProperties(const Loop *L) { 6744 using LoopProperties = ScalarEvolution::LoopProperties; 6745 6746 auto Itr = LoopPropertiesCache.find(L); 6747 if (Itr == LoopPropertiesCache.end()) { 6748 auto HasSideEffects = [](Instruction *I) { 6749 if (auto *SI = dyn_cast<StoreInst>(I)) 6750 return !SI->isSimple(); 6751 6752 return I->mayThrow() || I->mayWriteToMemory(); 6753 }; 6754 6755 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6756 /*HasNoSideEffects*/ true}; 6757 6758 for (auto *BB : L->getBlocks()) 6759 for (auto &I : *BB) { 6760 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6761 LP.HasNoAbnormalExits = false; 6762 if (HasSideEffects(&I)) 6763 LP.HasNoSideEffects = false; 6764 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6765 break; // We're already as pessimistic as we can get. 6766 } 6767 6768 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6769 assert(InsertPair.second && "We just checked!"); 6770 Itr = InsertPair.first; 6771 } 6772 6773 return Itr->second; 6774 } 6775 6776 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6777 // A mustprogress loop without side effects must be finite. 6778 // TODO: The check used here is very conservative. It's only *specific* 6779 // side effects which are well defined in infinite loops. 6780 return isMustProgress(L) && loopHasNoSideEffects(L); 6781 } 6782 6783 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6784 if (!isSCEVable(V->getType())) 6785 return getUnknown(V); 6786 6787 if (Instruction *I = dyn_cast<Instruction>(V)) { 6788 // Don't attempt to analyze instructions in blocks that aren't 6789 // reachable. Such instructions don't matter, and they aren't required 6790 // to obey basic rules for definitions dominating uses which this 6791 // analysis depends on. 6792 if (!DT.isReachableFromEntry(I->getParent())) 6793 return getUnknown(UndefValue::get(V->getType())); 6794 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6795 return getConstant(CI); 6796 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6797 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6798 else if (!isa<ConstantExpr>(V)) 6799 return getUnknown(V); 6800 6801 Operator *U = cast<Operator>(V); 6802 if (auto BO = MatchBinaryOp(U, DT)) { 6803 switch (BO->Opcode) { 6804 case Instruction::Add: { 6805 // The simple thing to do would be to just call getSCEV on both operands 6806 // and call getAddExpr with the result. However if we're looking at a 6807 // bunch of things all added together, this can be quite inefficient, 6808 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6809 // Instead, gather up all the operands and make a single getAddExpr call. 6810 // LLVM IR canonical form means we need only traverse the left operands. 6811 SmallVector<const SCEV *, 4> AddOps; 6812 do { 6813 if (BO->Op) { 6814 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6815 AddOps.push_back(OpSCEV); 6816 break; 6817 } 6818 6819 // If a NUW or NSW flag can be applied to the SCEV for this 6820 // addition, then compute the SCEV for this addition by itself 6821 // with a separate call to getAddExpr. We need to do that 6822 // instead of pushing the operands of the addition onto AddOps, 6823 // since the flags are only known to apply to this particular 6824 // addition - they may not apply to other additions that can be 6825 // formed with operands from AddOps. 6826 const SCEV *RHS = getSCEV(BO->RHS); 6827 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6828 if (Flags != SCEV::FlagAnyWrap) { 6829 const SCEV *LHS = getSCEV(BO->LHS); 6830 if (BO->Opcode == Instruction::Sub) 6831 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6832 else 6833 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6834 break; 6835 } 6836 } 6837 6838 if (BO->Opcode == Instruction::Sub) 6839 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6840 else 6841 AddOps.push_back(getSCEV(BO->RHS)); 6842 6843 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6844 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6845 NewBO->Opcode != Instruction::Sub)) { 6846 AddOps.push_back(getSCEV(BO->LHS)); 6847 break; 6848 } 6849 BO = NewBO; 6850 } while (true); 6851 6852 return getAddExpr(AddOps); 6853 } 6854 6855 case Instruction::Mul: { 6856 SmallVector<const SCEV *, 4> MulOps; 6857 do { 6858 if (BO->Op) { 6859 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6860 MulOps.push_back(OpSCEV); 6861 break; 6862 } 6863 6864 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6865 if (Flags != SCEV::FlagAnyWrap) { 6866 MulOps.push_back( 6867 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6868 break; 6869 } 6870 } 6871 6872 MulOps.push_back(getSCEV(BO->RHS)); 6873 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6874 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6875 MulOps.push_back(getSCEV(BO->LHS)); 6876 break; 6877 } 6878 BO = NewBO; 6879 } while (true); 6880 6881 return getMulExpr(MulOps); 6882 } 6883 case Instruction::UDiv: 6884 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6885 case Instruction::URem: 6886 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6887 case Instruction::Sub: { 6888 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6889 if (BO->Op) 6890 Flags = getNoWrapFlagsFromUB(BO->Op); 6891 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6892 } 6893 case Instruction::And: 6894 // For an expression like x&255 that merely masks off the high bits, 6895 // use zext(trunc(x)) as the SCEV expression. 6896 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6897 if (CI->isZero()) 6898 return getSCEV(BO->RHS); 6899 if (CI->isMinusOne()) 6900 return getSCEV(BO->LHS); 6901 const APInt &A = CI->getValue(); 6902 6903 // Instcombine's ShrinkDemandedConstant may strip bits out of 6904 // constants, obscuring what would otherwise be a low-bits mask. 6905 // Use computeKnownBits to compute what ShrinkDemandedConstant 6906 // knew about to reconstruct a low-bits mask value. 6907 unsigned LZ = A.countLeadingZeros(); 6908 unsigned TZ = A.countTrailingZeros(); 6909 unsigned BitWidth = A.getBitWidth(); 6910 KnownBits Known(BitWidth); 6911 computeKnownBits(BO->LHS, Known, getDataLayout(), 6912 0, &AC, nullptr, &DT); 6913 6914 APInt EffectiveMask = 6915 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6916 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6917 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6918 const SCEV *LHS = getSCEV(BO->LHS); 6919 const SCEV *ShiftedLHS = nullptr; 6920 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6921 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6922 // For an expression like (x * 8) & 8, simplify the multiply. 6923 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6924 unsigned GCD = std::min(MulZeros, TZ); 6925 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6926 SmallVector<const SCEV*, 4> MulOps; 6927 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6928 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6929 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6930 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6931 } 6932 } 6933 if (!ShiftedLHS) 6934 ShiftedLHS = getUDivExpr(LHS, MulCount); 6935 return getMulExpr( 6936 getZeroExtendExpr( 6937 getTruncateExpr(ShiftedLHS, 6938 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6939 BO->LHS->getType()), 6940 MulCount); 6941 } 6942 } 6943 break; 6944 6945 case Instruction::Or: 6946 // If the RHS of the Or is a constant, we may have something like: 6947 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6948 // optimizations will transparently handle this case. 6949 // 6950 // In order for this transformation to be safe, the LHS must be of the 6951 // form X*(2^n) and the Or constant must be less than 2^n. 6952 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6953 const SCEV *LHS = getSCEV(BO->LHS); 6954 const APInt &CIVal = CI->getValue(); 6955 if (GetMinTrailingZeros(LHS) >= 6956 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6957 // Build a plain add SCEV. 6958 return getAddExpr(LHS, getSCEV(CI), 6959 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6960 } 6961 } 6962 break; 6963 6964 case Instruction::Xor: 6965 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6966 // If the RHS of xor is -1, then this is a not operation. 6967 if (CI->isMinusOne()) 6968 return getNotSCEV(getSCEV(BO->LHS)); 6969 6970 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6971 // This is a variant of the check for xor with -1, and it handles 6972 // the case where instcombine has trimmed non-demanded bits out 6973 // of an xor with -1. 6974 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6975 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6976 if (LBO->getOpcode() == Instruction::And && 6977 LCI->getValue() == CI->getValue()) 6978 if (const SCEVZeroExtendExpr *Z = 6979 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6980 Type *UTy = BO->LHS->getType(); 6981 const SCEV *Z0 = Z->getOperand(); 6982 Type *Z0Ty = Z0->getType(); 6983 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6984 6985 // If C is a low-bits mask, the zero extend is serving to 6986 // mask off the high bits. Complement the operand and 6987 // re-apply the zext. 6988 if (CI->getValue().isMask(Z0TySize)) 6989 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6990 6991 // If C is a single bit, it may be in the sign-bit position 6992 // before the zero-extend. In this case, represent the xor 6993 // using an add, which is equivalent, and re-apply the zext. 6994 APInt Trunc = CI->getValue().trunc(Z0TySize); 6995 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6996 Trunc.isSignMask()) 6997 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6998 UTy); 6999 } 7000 } 7001 break; 7002 7003 case Instruction::Shl: 7004 // Turn shift left of a constant amount into a multiply. 7005 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7006 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7007 7008 // If the shift count is not less than the bitwidth, the result of 7009 // the shift is undefined. Don't try to analyze it, because the 7010 // resolution chosen here may differ from the resolution chosen in 7011 // other parts of the compiler. 7012 if (SA->getValue().uge(BitWidth)) 7013 break; 7014 7015 // We can safely preserve the nuw flag in all cases. It's also safe to 7016 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7017 // requires special handling. It can be preserved as long as we're not 7018 // left shifting by bitwidth - 1. 7019 auto Flags = SCEV::FlagAnyWrap; 7020 if (BO->Op) { 7021 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7022 if ((MulFlags & SCEV::FlagNSW) && 7023 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7024 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7025 if (MulFlags & SCEV::FlagNUW) 7026 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7027 } 7028 7029 Constant *X = ConstantInt::get( 7030 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7031 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7032 } 7033 break; 7034 7035 case Instruction::AShr: { 7036 // AShr X, C, where C is a constant. 7037 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7038 if (!CI) 7039 break; 7040 7041 Type *OuterTy = BO->LHS->getType(); 7042 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7043 // If the shift count is not less than the bitwidth, the result of 7044 // the shift is undefined. Don't try to analyze it, because the 7045 // resolution chosen here may differ from the resolution chosen in 7046 // other parts of the compiler. 7047 if (CI->getValue().uge(BitWidth)) 7048 break; 7049 7050 if (CI->isZero()) 7051 return getSCEV(BO->LHS); // shift by zero --> noop 7052 7053 uint64_t AShrAmt = CI->getZExtValue(); 7054 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7055 7056 Operator *L = dyn_cast<Operator>(BO->LHS); 7057 if (L && L->getOpcode() == Instruction::Shl) { 7058 // X = Shl A, n 7059 // Y = AShr X, m 7060 // Both n and m are constant. 7061 7062 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7063 if (L->getOperand(1) == BO->RHS) 7064 // For a two-shift sext-inreg, i.e. n = m, 7065 // use sext(trunc(x)) as the SCEV expression. 7066 return getSignExtendExpr( 7067 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7068 7069 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7070 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7071 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7072 if (ShlAmt > AShrAmt) { 7073 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7074 // expression. We already checked that ShlAmt < BitWidth, so 7075 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7076 // ShlAmt - AShrAmt < Amt. 7077 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7078 ShlAmt - AShrAmt); 7079 return getSignExtendExpr( 7080 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7081 getConstant(Mul)), OuterTy); 7082 } 7083 } 7084 } 7085 break; 7086 } 7087 } 7088 } 7089 7090 switch (U->getOpcode()) { 7091 case Instruction::Trunc: 7092 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7093 7094 case Instruction::ZExt: 7095 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7096 7097 case Instruction::SExt: 7098 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7099 // The NSW flag of a subtract does not always survive the conversion to 7100 // A + (-1)*B. By pushing sign extension onto its operands we are much 7101 // more likely to preserve NSW and allow later AddRec optimisations. 7102 // 7103 // NOTE: This is effectively duplicating this logic from getSignExtend: 7104 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7105 // but by that point the NSW information has potentially been lost. 7106 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7107 Type *Ty = U->getType(); 7108 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7109 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7110 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7111 } 7112 } 7113 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7114 7115 case Instruction::BitCast: 7116 // BitCasts are no-op casts so we just eliminate the cast. 7117 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7118 return getSCEV(U->getOperand(0)); 7119 break; 7120 7121 case Instruction::PtrToInt: { 7122 // Pointer to integer cast is straight-forward, so do model it. 7123 const SCEV *Op = getSCEV(U->getOperand(0)); 7124 Type *DstIntTy = U->getType(); 7125 // But only if effective SCEV (integer) type is wide enough to represent 7126 // all possible pointer values. 7127 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7128 if (isa<SCEVCouldNotCompute>(IntOp)) 7129 return getUnknown(V); 7130 return IntOp; 7131 } 7132 case Instruction::IntToPtr: 7133 // Just don't deal with inttoptr casts. 7134 return getUnknown(V); 7135 7136 case Instruction::SDiv: 7137 // If both operands are non-negative, this is just an udiv. 7138 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7139 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7140 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7141 break; 7142 7143 case Instruction::SRem: 7144 // If both operands are non-negative, this is just an urem. 7145 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7146 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7147 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7148 break; 7149 7150 case Instruction::GetElementPtr: 7151 return createNodeForGEP(cast<GEPOperator>(U)); 7152 7153 case Instruction::PHI: 7154 return createNodeForPHI(cast<PHINode>(U)); 7155 7156 case Instruction::Select: 7157 // U can also be a select constant expr, which let fall through. Since 7158 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7159 // constant expressions cannot have instructions as operands, we'd have 7160 // returned getUnknown for a select constant expressions anyway. 7161 if (isa<Instruction>(U)) 7162 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7163 U->getOperand(1), U->getOperand(2)); 7164 break; 7165 7166 case Instruction::Call: 7167 case Instruction::Invoke: 7168 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7169 return getSCEV(RV); 7170 7171 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7172 switch (II->getIntrinsicID()) { 7173 case Intrinsic::abs: 7174 return getAbsExpr( 7175 getSCEV(II->getArgOperand(0)), 7176 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7177 case Intrinsic::umax: 7178 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7179 getSCEV(II->getArgOperand(1))); 7180 case Intrinsic::umin: 7181 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7182 getSCEV(II->getArgOperand(1))); 7183 case Intrinsic::smax: 7184 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7185 getSCEV(II->getArgOperand(1))); 7186 case Intrinsic::smin: 7187 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7188 getSCEV(II->getArgOperand(1))); 7189 case Intrinsic::usub_sat: { 7190 const SCEV *X = getSCEV(II->getArgOperand(0)); 7191 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7192 const SCEV *ClampedY = getUMinExpr(X, Y); 7193 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7194 } 7195 case Intrinsic::uadd_sat: { 7196 const SCEV *X = getSCEV(II->getArgOperand(0)); 7197 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7198 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7199 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7200 } 7201 case Intrinsic::start_loop_iterations: 7202 // A start_loop_iterations is just equivalent to the first operand for 7203 // SCEV purposes. 7204 return getSCEV(II->getArgOperand(0)); 7205 default: 7206 break; 7207 } 7208 } 7209 break; 7210 } 7211 7212 return getUnknown(V); 7213 } 7214 7215 //===----------------------------------------------------------------------===// 7216 // Iteration Count Computation Code 7217 // 7218 7219 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7220 bool Extend) { 7221 if (isa<SCEVCouldNotCompute>(ExitCount)) 7222 return getCouldNotCompute(); 7223 7224 auto *ExitCountType = ExitCount->getType(); 7225 assert(ExitCountType->isIntegerTy()); 7226 7227 if (!Extend) 7228 return getAddExpr(ExitCount, getOne(ExitCountType)); 7229 7230 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7231 1 + ExitCountType->getScalarSizeInBits()); 7232 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7233 getOne(WiderType)); 7234 } 7235 7236 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7237 if (!ExitCount) 7238 return 0; 7239 7240 ConstantInt *ExitConst = ExitCount->getValue(); 7241 7242 // Guard against huge trip counts. 7243 if (ExitConst->getValue().getActiveBits() > 32) 7244 return 0; 7245 7246 // In case of integer overflow, this returns 0, which is correct. 7247 return ((unsigned)ExitConst->getZExtValue()) + 1; 7248 } 7249 7250 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7251 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7252 return getConstantTripCount(ExitCount); 7253 } 7254 7255 unsigned 7256 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7257 const BasicBlock *ExitingBlock) { 7258 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7259 assert(L->isLoopExiting(ExitingBlock) && 7260 "Exiting block must actually branch out of the loop!"); 7261 const SCEVConstant *ExitCount = 7262 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7263 return getConstantTripCount(ExitCount); 7264 } 7265 7266 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7267 const auto *MaxExitCount = 7268 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7269 return getConstantTripCount(MaxExitCount); 7270 } 7271 7272 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7273 SmallVector<BasicBlock *, 8> ExitingBlocks; 7274 L->getExitingBlocks(ExitingBlocks); 7275 7276 Optional<unsigned> Res = None; 7277 for (auto *ExitingBB : ExitingBlocks) { 7278 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7279 if (!Res) 7280 Res = Multiple; 7281 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7282 } 7283 return Res.getValueOr(1); 7284 } 7285 7286 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7287 const SCEV *ExitCount) { 7288 if (ExitCount == getCouldNotCompute()) 7289 return 1; 7290 7291 // Get the trip count 7292 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7293 7294 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7295 if (!TC) 7296 // Attempt to factor more general cases. Returns the greatest power of 7297 // two divisor. If overflow happens, the trip count expression is still 7298 // divisible by the greatest power of 2 divisor returned. 7299 return 1U << std::min((uint32_t)31, 7300 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7301 7302 ConstantInt *Result = TC->getValue(); 7303 7304 // Guard against huge trip counts (this requires checking 7305 // for zero to handle the case where the trip count == -1 and the 7306 // addition wraps). 7307 if (!Result || Result->getValue().getActiveBits() > 32 || 7308 Result->getValue().getActiveBits() == 0) 7309 return 1; 7310 7311 return (unsigned)Result->getZExtValue(); 7312 } 7313 7314 /// Returns the largest constant divisor of the trip count of this loop as a 7315 /// normal unsigned value, if possible. This means that the actual trip count is 7316 /// always a multiple of the returned value (don't forget the trip count could 7317 /// very well be zero as well!). 7318 /// 7319 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7320 /// multiple of a constant (which is also the case if the trip count is simply 7321 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7322 /// if the trip count is very large (>= 2^32). 7323 /// 7324 /// As explained in the comments for getSmallConstantTripCount, this assumes 7325 /// that control exits the loop via ExitingBlock. 7326 unsigned 7327 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7328 const BasicBlock *ExitingBlock) { 7329 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7330 assert(L->isLoopExiting(ExitingBlock) && 7331 "Exiting block must actually branch out of the loop!"); 7332 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7333 return getSmallConstantTripMultiple(L, ExitCount); 7334 } 7335 7336 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7337 const BasicBlock *ExitingBlock, 7338 ExitCountKind Kind) { 7339 switch (Kind) { 7340 case Exact: 7341 case SymbolicMaximum: 7342 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7343 case ConstantMaximum: 7344 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7345 }; 7346 llvm_unreachable("Invalid ExitCountKind!"); 7347 } 7348 7349 const SCEV * 7350 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7351 SCEVUnionPredicate &Preds) { 7352 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7353 } 7354 7355 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7356 ExitCountKind Kind) { 7357 switch (Kind) { 7358 case Exact: 7359 return getBackedgeTakenInfo(L).getExact(L, this); 7360 case ConstantMaximum: 7361 return getBackedgeTakenInfo(L).getConstantMax(this); 7362 case SymbolicMaximum: 7363 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7364 }; 7365 llvm_unreachable("Invalid ExitCountKind!"); 7366 } 7367 7368 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7369 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7370 } 7371 7372 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7373 static void PushLoopPHIs(const Loop *L, 7374 SmallVectorImpl<Instruction *> &Worklist, 7375 SmallPtrSetImpl<Instruction *> &Visited) { 7376 BasicBlock *Header = L->getHeader(); 7377 7378 // Push all Loop-header PHIs onto the Worklist stack. 7379 for (PHINode &PN : Header->phis()) 7380 if (Visited.insert(&PN).second) 7381 Worklist.push_back(&PN); 7382 } 7383 7384 const ScalarEvolution::BackedgeTakenInfo & 7385 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7386 auto &BTI = getBackedgeTakenInfo(L); 7387 if (BTI.hasFullInfo()) 7388 return BTI; 7389 7390 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7391 7392 if (!Pair.second) 7393 return Pair.first->second; 7394 7395 BackedgeTakenInfo Result = 7396 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7397 7398 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7399 } 7400 7401 ScalarEvolution::BackedgeTakenInfo & 7402 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7403 // Initially insert an invalid entry for this loop. If the insertion 7404 // succeeds, proceed to actually compute a backedge-taken count and 7405 // update the value. The temporary CouldNotCompute value tells SCEV 7406 // code elsewhere that it shouldn't attempt to request a new 7407 // backedge-taken count, which could result in infinite recursion. 7408 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7409 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7410 if (!Pair.second) 7411 return Pair.first->second; 7412 7413 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7414 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7415 // must be cleared in this scope. 7416 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7417 7418 // In product build, there are no usage of statistic. 7419 (void)NumTripCountsComputed; 7420 (void)NumTripCountsNotComputed; 7421 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7422 const SCEV *BEExact = Result.getExact(L, this); 7423 if (BEExact != getCouldNotCompute()) { 7424 assert(isLoopInvariant(BEExact, L) && 7425 isLoopInvariant(Result.getConstantMax(this), L) && 7426 "Computed backedge-taken count isn't loop invariant for loop!"); 7427 ++NumTripCountsComputed; 7428 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7429 isa<PHINode>(L->getHeader()->begin())) { 7430 // Only count loops that have phi nodes as not being computable. 7431 ++NumTripCountsNotComputed; 7432 } 7433 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7434 7435 // Now that we know more about the trip count for this loop, forget any 7436 // existing SCEV values for PHI nodes in this loop since they are only 7437 // conservative estimates made without the benefit of trip count 7438 // information. This is similar to the code in forgetLoop, except that 7439 // it handles SCEVUnknown PHI nodes specially. 7440 if (Result.hasAnyInfo()) { 7441 SmallVector<Instruction *, 16> Worklist; 7442 SmallPtrSet<Instruction *, 8> Discovered; 7443 SmallVector<const SCEV *, 8> ToForget; 7444 PushLoopPHIs(L, Worklist, Discovered); 7445 while (!Worklist.empty()) { 7446 Instruction *I = Worklist.pop_back_val(); 7447 7448 ValueExprMapType::iterator It = 7449 ValueExprMap.find_as(static_cast<Value *>(I)); 7450 if (It != ValueExprMap.end()) { 7451 const SCEV *Old = It->second; 7452 7453 // SCEVUnknown for a PHI either means that it has an unrecognized 7454 // structure, or it's a PHI that's in the progress of being computed 7455 // by createNodeForPHI. In the former case, additional loop trip 7456 // count information isn't going to change anything. In the later 7457 // case, createNodeForPHI will perform the necessary updates on its 7458 // own when it gets to that point. 7459 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7460 eraseValueFromMap(It->first); 7461 ToForget.push_back(Old); 7462 } 7463 if (PHINode *PN = dyn_cast<PHINode>(I)) 7464 ConstantEvolutionLoopExitValue.erase(PN); 7465 } 7466 7467 // Since we don't need to invalidate anything for correctness and we're 7468 // only invalidating to make SCEV's results more precise, we get to stop 7469 // early to avoid invalidating too much. This is especially important in 7470 // cases like: 7471 // 7472 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7473 // loop0: 7474 // %pn0 = phi 7475 // ... 7476 // loop1: 7477 // %pn1 = phi 7478 // ... 7479 // 7480 // where both loop0 and loop1's backedge taken count uses the SCEV 7481 // expression for %v. If we don't have the early stop below then in cases 7482 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7483 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7484 // count for loop1, effectively nullifying SCEV's trip count cache. 7485 for (auto *U : I->users()) 7486 if (auto *I = dyn_cast<Instruction>(U)) { 7487 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7488 if (LoopForUser && L->contains(LoopForUser) && 7489 Discovered.insert(I).second) 7490 Worklist.push_back(I); 7491 } 7492 } 7493 forgetMemoizedResults(ToForget); 7494 } 7495 7496 // Re-lookup the insert position, since the call to 7497 // computeBackedgeTakenCount above could result in a 7498 // recusive call to getBackedgeTakenInfo (on a different 7499 // loop), which would invalidate the iterator computed 7500 // earlier. 7501 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7502 } 7503 7504 void ScalarEvolution::forgetAllLoops() { 7505 // This method is intended to forget all info about loops. It should 7506 // invalidate caches as if the following happened: 7507 // - The trip counts of all loops have changed arbitrarily 7508 // - Every llvm::Value has been updated in place to produce a different 7509 // result. 7510 BackedgeTakenCounts.clear(); 7511 PredicatedBackedgeTakenCounts.clear(); 7512 LoopPropertiesCache.clear(); 7513 ConstantEvolutionLoopExitValue.clear(); 7514 ValueExprMap.clear(); 7515 ValuesAtScopes.clear(); 7516 LoopDispositions.clear(); 7517 BlockDispositions.clear(); 7518 UnsignedRanges.clear(); 7519 SignedRanges.clear(); 7520 ExprValueMap.clear(); 7521 HasRecMap.clear(); 7522 MinTrailingZerosCache.clear(); 7523 PredicatedSCEVRewrites.clear(); 7524 } 7525 7526 void ScalarEvolution::forgetLoop(const Loop *L) { 7527 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7528 SmallVector<Instruction *, 32> Worklist; 7529 SmallPtrSet<Instruction *, 16> Visited; 7530 SmallVector<const SCEV *, 16> ToForget; 7531 7532 // Iterate over all the loops and sub-loops to drop SCEV information. 7533 while (!LoopWorklist.empty()) { 7534 auto *CurrL = LoopWorklist.pop_back_val(); 7535 7536 // Drop any stored trip count value. 7537 BackedgeTakenCounts.erase(CurrL); 7538 PredicatedBackedgeTakenCounts.erase(CurrL); 7539 7540 // Drop information about predicated SCEV rewrites for this loop. 7541 for (auto I = PredicatedSCEVRewrites.begin(); 7542 I != PredicatedSCEVRewrites.end();) { 7543 std::pair<const SCEV *, const Loop *> Entry = I->first; 7544 if (Entry.second == CurrL) 7545 PredicatedSCEVRewrites.erase(I++); 7546 else 7547 ++I; 7548 } 7549 7550 auto LoopUsersItr = LoopUsers.find(CurrL); 7551 if (LoopUsersItr != LoopUsers.end()) { 7552 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 7553 LoopUsersItr->second.end()); 7554 LoopUsers.erase(LoopUsersItr); 7555 } 7556 7557 // Drop information about expressions based on loop-header PHIs. 7558 PushLoopPHIs(CurrL, Worklist, Visited); 7559 7560 while (!Worklist.empty()) { 7561 Instruction *I = Worklist.pop_back_val(); 7562 7563 ValueExprMapType::iterator It = 7564 ValueExprMap.find_as(static_cast<Value *>(I)); 7565 if (It != ValueExprMap.end()) { 7566 eraseValueFromMap(It->first); 7567 ToForget.push_back(It->second); 7568 if (PHINode *PN = dyn_cast<PHINode>(I)) 7569 ConstantEvolutionLoopExitValue.erase(PN); 7570 } 7571 7572 PushDefUseChildren(I, Worklist, Visited); 7573 } 7574 7575 LoopPropertiesCache.erase(CurrL); 7576 // Forget all contained loops too, to avoid dangling entries in the 7577 // ValuesAtScopes map. 7578 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7579 } 7580 forgetMemoizedResults(ToForget); 7581 } 7582 7583 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7584 while (Loop *Parent = L->getParentLoop()) 7585 L = Parent; 7586 forgetLoop(L); 7587 } 7588 7589 void ScalarEvolution::forgetValue(Value *V) { 7590 Instruction *I = dyn_cast<Instruction>(V); 7591 if (!I) return; 7592 7593 // Drop information about expressions based on loop-header PHIs. 7594 SmallVector<Instruction *, 16> Worklist; 7595 SmallPtrSet<Instruction *, 8> Visited; 7596 SmallVector<const SCEV *, 8> ToForget; 7597 Worklist.push_back(I); 7598 Visited.insert(I); 7599 7600 while (!Worklist.empty()) { 7601 I = Worklist.pop_back_val(); 7602 ValueExprMapType::iterator It = 7603 ValueExprMap.find_as(static_cast<Value *>(I)); 7604 if (It != ValueExprMap.end()) { 7605 eraseValueFromMap(It->first); 7606 ToForget.push_back(It->second); 7607 if (PHINode *PN = dyn_cast<PHINode>(I)) 7608 ConstantEvolutionLoopExitValue.erase(PN); 7609 } 7610 7611 PushDefUseChildren(I, Worklist, Visited); 7612 } 7613 forgetMemoizedResults(ToForget); 7614 } 7615 7616 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7617 LoopDispositions.clear(); 7618 } 7619 7620 /// Get the exact loop backedge taken count considering all loop exits. A 7621 /// computable result can only be returned for loops with all exiting blocks 7622 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7623 /// is never skipped. This is a valid assumption as long as the loop exits via 7624 /// that test. For precise results, it is the caller's responsibility to specify 7625 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7626 const SCEV * 7627 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7628 SCEVUnionPredicate *Preds) const { 7629 // If any exits were not computable, the loop is not computable. 7630 if (!isComplete() || ExitNotTaken.empty()) 7631 return SE->getCouldNotCompute(); 7632 7633 const BasicBlock *Latch = L->getLoopLatch(); 7634 // All exiting blocks we have collected must dominate the only backedge. 7635 if (!Latch) 7636 return SE->getCouldNotCompute(); 7637 7638 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7639 // count is simply a minimum out of all these calculated exit counts. 7640 SmallVector<const SCEV *, 2> Ops; 7641 for (auto &ENT : ExitNotTaken) { 7642 const SCEV *BECount = ENT.ExactNotTaken; 7643 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7644 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7645 "We should only have known counts for exiting blocks that dominate " 7646 "latch!"); 7647 7648 Ops.push_back(BECount); 7649 7650 if (Preds && !ENT.hasAlwaysTruePredicate()) 7651 Preds->add(ENT.Predicate.get()); 7652 7653 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7654 "Predicate should be always true!"); 7655 } 7656 7657 return SE->getUMinFromMismatchedTypes(Ops); 7658 } 7659 7660 /// Get the exact not taken count for this loop exit. 7661 const SCEV * 7662 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7663 ScalarEvolution *SE) const { 7664 for (auto &ENT : ExitNotTaken) 7665 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7666 return ENT.ExactNotTaken; 7667 7668 return SE->getCouldNotCompute(); 7669 } 7670 7671 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7672 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7673 for (auto &ENT : ExitNotTaken) 7674 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7675 return ENT.MaxNotTaken; 7676 7677 return SE->getCouldNotCompute(); 7678 } 7679 7680 /// getConstantMax - Get the constant max backedge taken count for the loop. 7681 const SCEV * 7682 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7683 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7684 return !ENT.hasAlwaysTruePredicate(); 7685 }; 7686 7687 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 7688 return SE->getCouldNotCompute(); 7689 7690 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7691 isa<SCEVConstant>(getConstantMax())) && 7692 "No point in having a non-constant max backedge taken count!"); 7693 return getConstantMax(); 7694 } 7695 7696 const SCEV * 7697 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7698 ScalarEvolution *SE) { 7699 if (!SymbolicMax) 7700 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7701 return SymbolicMax; 7702 } 7703 7704 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7705 ScalarEvolution *SE) const { 7706 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7707 return !ENT.hasAlwaysTruePredicate(); 7708 }; 7709 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7710 } 7711 7712 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7713 return Operands.contains(S); 7714 } 7715 7716 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7717 : ExitLimit(E, E, false, None) { 7718 } 7719 7720 ScalarEvolution::ExitLimit::ExitLimit( 7721 const SCEV *E, const SCEV *M, bool MaxOrZero, 7722 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7723 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7724 // If we prove the max count is zero, so is the symbolic bound. This happens 7725 // in practice due to differences in a) how context sensitive we've chosen 7726 // to be and b) how we reason about bounds impied by UB. 7727 if (MaxNotTaken->isZero()) 7728 ExactNotTaken = MaxNotTaken; 7729 7730 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7731 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7732 "Exact is not allowed to be less precise than Max"); 7733 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7734 isa<SCEVConstant>(MaxNotTaken)) && 7735 "No point in having a non-constant max backedge taken count!"); 7736 for (auto *PredSet : PredSetList) 7737 for (auto *P : *PredSet) 7738 addPredicate(P); 7739 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7740 "Backedge count should be int"); 7741 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7742 "Max backedge count should be int"); 7743 } 7744 7745 ScalarEvolution::ExitLimit::ExitLimit( 7746 const SCEV *E, const SCEV *M, bool MaxOrZero, 7747 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7748 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7749 } 7750 7751 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7752 bool MaxOrZero) 7753 : ExitLimit(E, M, MaxOrZero, None) { 7754 } 7755 7756 class SCEVRecordOperands { 7757 SmallPtrSetImpl<const SCEV *> &Operands; 7758 7759 public: 7760 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7761 : Operands(Operands) {} 7762 bool follow(const SCEV *S) { 7763 Operands.insert(S); 7764 return true; 7765 } 7766 bool isDone() { return false; } 7767 }; 7768 7769 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7770 /// computable exit into a persistent ExitNotTakenInfo array. 7771 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7772 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7773 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7774 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7775 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7776 7777 ExitNotTaken.reserve(ExitCounts.size()); 7778 std::transform( 7779 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7780 [&](const EdgeExitInfo &EEI) { 7781 BasicBlock *ExitBB = EEI.first; 7782 const ExitLimit &EL = EEI.second; 7783 if (EL.Predicates.empty()) 7784 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7785 nullptr); 7786 7787 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7788 for (auto *Pred : EL.Predicates) 7789 Predicate->add(Pred); 7790 7791 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7792 std::move(Predicate)); 7793 }); 7794 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7795 isa<SCEVConstant>(ConstantMax)) && 7796 "No point in having a non-constant max backedge taken count!"); 7797 7798 SCEVRecordOperands RecordOperands(Operands); 7799 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7800 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7801 ST.visitAll(ConstantMax); 7802 for (auto &ENT : ExitNotTaken) 7803 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7804 ST.visitAll(ENT.ExactNotTaken); 7805 } 7806 7807 /// Compute the number of times the backedge of the specified loop will execute. 7808 ScalarEvolution::BackedgeTakenInfo 7809 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7810 bool AllowPredicates) { 7811 SmallVector<BasicBlock *, 8> ExitingBlocks; 7812 L->getExitingBlocks(ExitingBlocks); 7813 7814 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7815 7816 SmallVector<EdgeExitInfo, 4> ExitCounts; 7817 bool CouldComputeBECount = true; 7818 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7819 const SCEV *MustExitMaxBECount = nullptr; 7820 const SCEV *MayExitMaxBECount = nullptr; 7821 bool MustExitMaxOrZero = false; 7822 7823 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7824 // and compute maxBECount. 7825 // Do a union of all the predicates here. 7826 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7827 BasicBlock *ExitBB = ExitingBlocks[i]; 7828 7829 // We canonicalize untaken exits to br (constant), ignore them so that 7830 // proving an exit untaken doesn't negatively impact our ability to reason 7831 // about the loop as whole. 7832 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7833 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7834 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7835 if (ExitIfTrue == CI->isZero()) 7836 continue; 7837 } 7838 7839 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7840 7841 assert((AllowPredicates || EL.Predicates.empty()) && 7842 "Predicated exit limit when predicates are not allowed!"); 7843 7844 // 1. For each exit that can be computed, add an entry to ExitCounts. 7845 // CouldComputeBECount is true only if all exits can be computed. 7846 if (EL.ExactNotTaken == getCouldNotCompute()) 7847 // We couldn't compute an exact value for this exit, so 7848 // we won't be able to compute an exact value for the loop. 7849 CouldComputeBECount = false; 7850 else 7851 ExitCounts.emplace_back(ExitBB, EL); 7852 7853 // 2. Derive the loop's MaxBECount from each exit's max number of 7854 // non-exiting iterations. Partition the loop exits into two kinds: 7855 // LoopMustExits and LoopMayExits. 7856 // 7857 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7858 // is a LoopMayExit. If any computable LoopMustExit is found, then 7859 // MaxBECount is the minimum EL.MaxNotTaken of computable 7860 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7861 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7862 // computable EL.MaxNotTaken. 7863 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7864 DT.dominates(ExitBB, Latch)) { 7865 if (!MustExitMaxBECount) { 7866 MustExitMaxBECount = EL.MaxNotTaken; 7867 MustExitMaxOrZero = EL.MaxOrZero; 7868 } else { 7869 MustExitMaxBECount = 7870 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7871 } 7872 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7873 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7874 MayExitMaxBECount = EL.MaxNotTaken; 7875 else { 7876 MayExitMaxBECount = 7877 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7878 } 7879 } 7880 } 7881 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7882 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7883 // The loop backedge will be taken the maximum or zero times if there's 7884 // a single exit that must be taken the maximum or zero times. 7885 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7886 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7887 MaxBECount, MaxOrZero); 7888 } 7889 7890 ScalarEvolution::ExitLimit 7891 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7892 bool AllowPredicates) { 7893 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7894 // If our exiting block does not dominate the latch, then its connection with 7895 // loop's exit limit may be far from trivial. 7896 const BasicBlock *Latch = L->getLoopLatch(); 7897 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7898 return getCouldNotCompute(); 7899 7900 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7901 Instruction *Term = ExitingBlock->getTerminator(); 7902 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7903 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7904 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7905 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7906 "It should have one successor in loop and one exit block!"); 7907 // Proceed to the next level to examine the exit condition expression. 7908 return computeExitLimitFromCond( 7909 L, BI->getCondition(), ExitIfTrue, 7910 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7911 } 7912 7913 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7914 // For switch, make sure that there is a single exit from the loop. 7915 BasicBlock *Exit = nullptr; 7916 for (auto *SBB : successors(ExitingBlock)) 7917 if (!L->contains(SBB)) { 7918 if (Exit) // Multiple exit successors. 7919 return getCouldNotCompute(); 7920 Exit = SBB; 7921 } 7922 assert(Exit && "Exiting block must have at least one exit"); 7923 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7924 /*ControlsExit=*/IsOnlyExit); 7925 } 7926 7927 return getCouldNotCompute(); 7928 } 7929 7930 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7931 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7932 bool ControlsExit, bool AllowPredicates) { 7933 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7934 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7935 ControlsExit, AllowPredicates); 7936 } 7937 7938 Optional<ScalarEvolution::ExitLimit> 7939 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7940 bool ExitIfTrue, bool ControlsExit, 7941 bool AllowPredicates) { 7942 (void)this->L; 7943 (void)this->ExitIfTrue; 7944 (void)this->AllowPredicates; 7945 7946 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7947 this->AllowPredicates == AllowPredicates && 7948 "Variance in assumed invariant key components!"); 7949 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7950 if (Itr == TripCountMap.end()) 7951 return None; 7952 return Itr->second; 7953 } 7954 7955 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7956 bool ExitIfTrue, 7957 bool ControlsExit, 7958 bool AllowPredicates, 7959 const ExitLimit &EL) { 7960 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7961 this->AllowPredicates == AllowPredicates && 7962 "Variance in assumed invariant key components!"); 7963 7964 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7965 assert(InsertResult.second && "Expected successful insertion!"); 7966 (void)InsertResult; 7967 (void)ExitIfTrue; 7968 } 7969 7970 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7971 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7972 bool ControlsExit, bool AllowPredicates) { 7973 7974 if (auto MaybeEL = 7975 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7976 return *MaybeEL; 7977 7978 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7979 ControlsExit, AllowPredicates); 7980 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7981 return EL; 7982 } 7983 7984 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7985 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7986 bool ControlsExit, bool AllowPredicates) { 7987 // Handle BinOp conditions (And, Or). 7988 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7989 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7990 return *LimitFromBinOp; 7991 7992 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7993 // Proceed to the next level to examine the icmp. 7994 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7995 ExitLimit EL = 7996 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7997 if (EL.hasFullInfo() || !AllowPredicates) 7998 return EL; 7999 8000 // Try again, but use SCEV predicates this time. 8001 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8002 /*AllowPredicates=*/true); 8003 } 8004 8005 // Check for a constant condition. These are normally stripped out by 8006 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8007 // preserve the CFG and is temporarily leaving constant conditions 8008 // in place. 8009 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8010 if (ExitIfTrue == !CI->getZExtValue()) 8011 // The backedge is always taken. 8012 return getCouldNotCompute(); 8013 else 8014 // The backedge is never taken. 8015 return getZero(CI->getType()); 8016 } 8017 8018 // If it's not an integer or pointer comparison then compute it the hard way. 8019 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8020 } 8021 8022 Optional<ScalarEvolution::ExitLimit> 8023 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8024 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8025 bool ControlsExit, bool AllowPredicates) { 8026 // Check if the controlling expression for this loop is an And or Or. 8027 Value *Op0, *Op1; 8028 bool IsAnd = false; 8029 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8030 IsAnd = true; 8031 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8032 IsAnd = false; 8033 else 8034 return None; 8035 8036 // EitherMayExit is true in these two cases: 8037 // br (and Op0 Op1), loop, exit 8038 // br (or Op0 Op1), exit, loop 8039 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8040 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8041 ControlsExit && !EitherMayExit, 8042 AllowPredicates); 8043 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8044 ControlsExit && !EitherMayExit, 8045 AllowPredicates); 8046 8047 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8048 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8049 if (isa<ConstantInt>(Op1)) 8050 return Op1 == NeutralElement ? EL0 : EL1; 8051 if (isa<ConstantInt>(Op0)) 8052 return Op0 == NeutralElement ? EL1 : EL0; 8053 8054 const SCEV *BECount = getCouldNotCompute(); 8055 const SCEV *MaxBECount = getCouldNotCompute(); 8056 if (EitherMayExit) { 8057 // Both conditions must be same for the loop to continue executing. 8058 // Choose the less conservative count. 8059 // If ExitCond is a short-circuit form (select), using 8060 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 8061 // To see the detailed examples, please see 8062 // test/Analysis/ScalarEvolution/exit-count-select.ll 8063 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 8064 if (!PoisonSafe) 8065 // Even if ExitCond is select, we can safely derive BECount using both 8066 // EL0 and EL1 in these cases: 8067 // (1) EL0.ExactNotTaken is non-zero 8068 // (2) EL1.ExactNotTaken is non-poison 8069 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 8070 // it cannot be umin(0, ..)) 8071 // The PoisonSafe assignment below is simplified and the assertion after 8072 // BECount calculation fully guarantees the condition (3). 8073 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 8074 isa<SCEVConstant>(EL1.ExactNotTaken); 8075 if (EL0.ExactNotTaken != getCouldNotCompute() && 8076 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 8077 BECount = 8078 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 8079 8080 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8081 // it should have been simplified to zero (see the condition (3) above) 8082 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8083 BECount->isZero()); 8084 } 8085 if (EL0.MaxNotTaken == getCouldNotCompute()) 8086 MaxBECount = EL1.MaxNotTaken; 8087 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8088 MaxBECount = EL0.MaxNotTaken; 8089 else 8090 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8091 } else { 8092 // Both conditions must be same at the same time for the loop to exit. 8093 // For now, be conservative. 8094 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8095 BECount = EL0.ExactNotTaken; 8096 } 8097 8098 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8099 // to be more aggressive when computing BECount than when computing 8100 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8101 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8102 // to not. 8103 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8104 !isa<SCEVCouldNotCompute>(BECount)) 8105 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8106 8107 return ExitLimit(BECount, MaxBECount, false, 8108 { &EL0.Predicates, &EL1.Predicates }); 8109 } 8110 8111 ScalarEvolution::ExitLimit 8112 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8113 ICmpInst *ExitCond, 8114 bool ExitIfTrue, 8115 bool ControlsExit, 8116 bool AllowPredicates) { 8117 // If the condition was exit on true, convert the condition to exit on false 8118 ICmpInst::Predicate Pred; 8119 if (!ExitIfTrue) 8120 Pred = ExitCond->getPredicate(); 8121 else 8122 Pred = ExitCond->getInversePredicate(); 8123 const ICmpInst::Predicate OriginalPred = Pred; 8124 8125 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8126 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8127 8128 // Try to evaluate any dependencies out of the loop. 8129 LHS = getSCEVAtScope(LHS, L); 8130 RHS = getSCEVAtScope(RHS, L); 8131 8132 // At this point, we would like to compute how many iterations of the 8133 // loop the predicate will return true for these inputs. 8134 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8135 // If there is a loop-invariant, force it into the RHS. 8136 std::swap(LHS, RHS); 8137 Pred = ICmpInst::getSwappedPredicate(Pred); 8138 } 8139 8140 // Simplify the operands before analyzing them. 8141 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8142 8143 // If we have a comparison of a chrec against a constant, try to use value 8144 // ranges to answer this query. 8145 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8146 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8147 if (AddRec->getLoop() == L) { 8148 // Form the constant range. 8149 ConstantRange CompRange = 8150 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8151 8152 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8153 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8154 } 8155 8156 switch (Pred) { 8157 case ICmpInst::ICMP_NE: { // while (X != Y) 8158 // Convert to: while (X-Y != 0) 8159 if (LHS->getType()->isPointerTy()) { 8160 LHS = getLosslessPtrToIntExpr(LHS); 8161 if (isa<SCEVCouldNotCompute>(LHS)) 8162 return LHS; 8163 } 8164 if (RHS->getType()->isPointerTy()) { 8165 RHS = getLosslessPtrToIntExpr(RHS); 8166 if (isa<SCEVCouldNotCompute>(RHS)) 8167 return RHS; 8168 } 8169 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8170 AllowPredicates); 8171 if (EL.hasAnyInfo()) return EL; 8172 break; 8173 } 8174 case ICmpInst::ICMP_EQ: { // while (X == Y) 8175 // Convert to: while (X-Y == 0) 8176 if (LHS->getType()->isPointerTy()) { 8177 LHS = getLosslessPtrToIntExpr(LHS); 8178 if (isa<SCEVCouldNotCompute>(LHS)) 8179 return LHS; 8180 } 8181 if (RHS->getType()->isPointerTy()) { 8182 RHS = getLosslessPtrToIntExpr(RHS); 8183 if (isa<SCEVCouldNotCompute>(RHS)) 8184 return RHS; 8185 } 8186 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8187 if (EL.hasAnyInfo()) return EL; 8188 break; 8189 } 8190 case ICmpInst::ICMP_SLT: 8191 case ICmpInst::ICMP_ULT: { // while (X < Y) 8192 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8193 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8194 AllowPredicates); 8195 if (EL.hasAnyInfo()) return EL; 8196 break; 8197 } 8198 case ICmpInst::ICMP_SGT: 8199 case ICmpInst::ICMP_UGT: { // while (X > Y) 8200 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8201 ExitLimit EL = 8202 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8203 AllowPredicates); 8204 if (EL.hasAnyInfo()) return EL; 8205 break; 8206 } 8207 default: 8208 break; 8209 } 8210 8211 auto *ExhaustiveCount = 8212 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8213 8214 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8215 return ExhaustiveCount; 8216 8217 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8218 ExitCond->getOperand(1), L, OriginalPred); 8219 } 8220 8221 ScalarEvolution::ExitLimit 8222 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8223 SwitchInst *Switch, 8224 BasicBlock *ExitingBlock, 8225 bool ControlsExit) { 8226 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8227 8228 // Give up if the exit is the default dest of a switch. 8229 if (Switch->getDefaultDest() == ExitingBlock) 8230 return getCouldNotCompute(); 8231 8232 assert(L->contains(Switch->getDefaultDest()) && 8233 "Default case must not exit the loop!"); 8234 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8235 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8236 8237 // while (X != Y) --> while (X-Y != 0) 8238 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8239 if (EL.hasAnyInfo()) 8240 return EL; 8241 8242 return getCouldNotCompute(); 8243 } 8244 8245 static ConstantInt * 8246 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8247 ScalarEvolution &SE) { 8248 const SCEV *InVal = SE.getConstant(C); 8249 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8250 assert(isa<SCEVConstant>(Val) && 8251 "Evaluation of SCEV at constant didn't fold correctly?"); 8252 return cast<SCEVConstant>(Val)->getValue(); 8253 } 8254 8255 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8256 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8257 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8258 if (!RHS) 8259 return getCouldNotCompute(); 8260 8261 const BasicBlock *Latch = L->getLoopLatch(); 8262 if (!Latch) 8263 return getCouldNotCompute(); 8264 8265 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8266 if (!Predecessor) 8267 return getCouldNotCompute(); 8268 8269 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8270 // Return LHS in OutLHS and shift_opt in OutOpCode. 8271 auto MatchPositiveShift = 8272 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8273 8274 using namespace PatternMatch; 8275 8276 ConstantInt *ShiftAmt; 8277 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8278 OutOpCode = Instruction::LShr; 8279 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8280 OutOpCode = Instruction::AShr; 8281 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8282 OutOpCode = Instruction::Shl; 8283 else 8284 return false; 8285 8286 return ShiftAmt->getValue().isStrictlyPositive(); 8287 }; 8288 8289 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8290 // 8291 // loop: 8292 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8293 // %iv.shifted = lshr i32 %iv, <positive constant> 8294 // 8295 // Return true on a successful match. Return the corresponding PHI node (%iv 8296 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8297 auto MatchShiftRecurrence = 8298 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8299 Optional<Instruction::BinaryOps> PostShiftOpCode; 8300 8301 { 8302 Instruction::BinaryOps OpC; 8303 Value *V; 8304 8305 // If we encounter a shift instruction, "peel off" the shift operation, 8306 // and remember that we did so. Later when we inspect %iv's backedge 8307 // value, we will make sure that the backedge value uses the same 8308 // operation. 8309 // 8310 // Note: the peeled shift operation does not have to be the same 8311 // instruction as the one feeding into the PHI's backedge value. We only 8312 // really care about it being the same *kind* of shift instruction -- 8313 // that's all that is required for our later inferences to hold. 8314 if (MatchPositiveShift(LHS, V, OpC)) { 8315 PostShiftOpCode = OpC; 8316 LHS = V; 8317 } 8318 } 8319 8320 PNOut = dyn_cast<PHINode>(LHS); 8321 if (!PNOut || PNOut->getParent() != L->getHeader()) 8322 return false; 8323 8324 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8325 Value *OpLHS; 8326 8327 return 8328 // The backedge value for the PHI node must be a shift by a positive 8329 // amount 8330 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8331 8332 // of the PHI node itself 8333 OpLHS == PNOut && 8334 8335 // and the kind of shift should be match the kind of shift we peeled 8336 // off, if any. 8337 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8338 }; 8339 8340 PHINode *PN; 8341 Instruction::BinaryOps OpCode; 8342 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8343 return getCouldNotCompute(); 8344 8345 const DataLayout &DL = getDataLayout(); 8346 8347 // The key rationale for this optimization is that for some kinds of shift 8348 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8349 // within a finite number of iterations. If the condition guarding the 8350 // backedge (in the sense that the backedge is taken if the condition is true) 8351 // is false for the value the shift recurrence stabilizes to, then we know 8352 // that the backedge is taken only a finite number of times. 8353 8354 ConstantInt *StableValue = nullptr; 8355 switch (OpCode) { 8356 default: 8357 llvm_unreachable("Impossible case!"); 8358 8359 case Instruction::AShr: { 8360 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8361 // bitwidth(K) iterations. 8362 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8363 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8364 Predecessor->getTerminator(), &DT); 8365 auto *Ty = cast<IntegerType>(RHS->getType()); 8366 if (Known.isNonNegative()) 8367 StableValue = ConstantInt::get(Ty, 0); 8368 else if (Known.isNegative()) 8369 StableValue = ConstantInt::get(Ty, -1, true); 8370 else 8371 return getCouldNotCompute(); 8372 8373 break; 8374 } 8375 case Instruction::LShr: 8376 case Instruction::Shl: 8377 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8378 // stabilize to 0 in at most bitwidth(K) iterations. 8379 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8380 break; 8381 } 8382 8383 auto *Result = 8384 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8385 assert(Result->getType()->isIntegerTy(1) && 8386 "Otherwise cannot be an operand to a branch instruction"); 8387 8388 if (Result->isZeroValue()) { 8389 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8390 const SCEV *UpperBound = 8391 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8392 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8393 } 8394 8395 return getCouldNotCompute(); 8396 } 8397 8398 /// Return true if we can constant fold an instruction of the specified type, 8399 /// assuming that all operands were constants. 8400 static bool CanConstantFold(const Instruction *I) { 8401 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8402 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8403 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8404 return true; 8405 8406 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8407 if (const Function *F = CI->getCalledFunction()) 8408 return canConstantFoldCallTo(CI, F); 8409 return false; 8410 } 8411 8412 /// Determine whether this instruction can constant evolve within this loop 8413 /// assuming its operands can all constant evolve. 8414 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8415 // An instruction outside of the loop can't be derived from a loop PHI. 8416 if (!L->contains(I)) return false; 8417 8418 if (isa<PHINode>(I)) { 8419 // We don't currently keep track of the control flow needed to evaluate 8420 // PHIs, so we cannot handle PHIs inside of loops. 8421 return L->getHeader() == I->getParent(); 8422 } 8423 8424 // If we won't be able to constant fold this expression even if the operands 8425 // are constants, bail early. 8426 return CanConstantFold(I); 8427 } 8428 8429 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8430 /// recursing through each instruction operand until reaching a loop header phi. 8431 static PHINode * 8432 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8433 DenseMap<Instruction *, PHINode *> &PHIMap, 8434 unsigned Depth) { 8435 if (Depth > MaxConstantEvolvingDepth) 8436 return nullptr; 8437 8438 // Otherwise, we can evaluate this instruction if all of its operands are 8439 // constant or derived from a PHI node themselves. 8440 PHINode *PHI = nullptr; 8441 for (Value *Op : UseInst->operands()) { 8442 if (isa<Constant>(Op)) continue; 8443 8444 Instruction *OpInst = dyn_cast<Instruction>(Op); 8445 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8446 8447 PHINode *P = dyn_cast<PHINode>(OpInst); 8448 if (!P) 8449 // If this operand is already visited, reuse the prior result. 8450 // We may have P != PHI if this is the deepest point at which the 8451 // inconsistent paths meet. 8452 P = PHIMap.lookup(OpInst); 8453 if (!P) { 8454 // Recurse and memoize the results, whether a phi is found or not. 8455 // This recursive call invalidates pointers into PHIMap. 8456 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8457 PHIMap[OpInst] = P; 8458 } 8459 if (!P) 8460 return nullptr; // Not evolving from PHI 8461 if (PHI && PHI != P) 8462 return nullptr; // Evolving from multiple different PHIs. 8463 PHI = P; 8464 } 8465 // This is a expression evolving from a constant PHI! 8466 return PHI; 8467 } 8468 8469 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8470 /// in the loop that V is derived from. We allow arbitrary operations along the 8471 /// way, but the operands of an operation must either be constants or a value 8472 /// derived from a constant PHI. If this expression does not fit with these 8473 /// constraints, return null. 8474 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8475 Instruction *I = dyn_cast<Instruction>(V); 8476 if (!I || !canConstantEvolve(I, L)) return nullptr; 8477 8478 if (PHINode *PN = dyn_cast<PHINode>(I)) 8479 return PN; 8480 8481 // Record non-constant instructions contained by the loop. 8482 DenseMap<Instruction *, PHINode *> PHIMap; 8483 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8484 } 8485 8486 /// EvaluateExpression - Given an expression that passes the 8487 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8488 /// in the loop has the value PHIVal. If we can't fold this expression for some 8489 /// reason, return null. 8490 static Constant *EvaluateExpression(Value *V, const Loop *L, 8491 DenseMap<Instruction *, Constant *> &Vals, 8492 const DataLayout &DL, 8493 const TargetLibraryInfo *TLI) { 8494 // Convenient constant check, but redundant for recursive calls. 8495 if (Constant *C = dyn_cast<Constant>(V)) return C; 8496 Instruction *I = dyn_cast<Instruction>(V); 8497 if (!I) return nullptr; 8498 8499 if (Constant *C = Vals.lookup(I)) return C; 8500 8501 // An instruction inside the loop depends on a value outside the loop that we 8502 // weren't given a mapping for, or a value such as a call inside the loop. 8503 if (!canConstantEvolve(I, L)) return nullptr; 8504 8505 // An unmapped PHI can be due to a branch or another loop inside this loop, 8506 // or due to this not being the initial iteration through a loop where we 8507 // couldn't compute the evolution of this particular PHI last time. 8508 if (isa<PHINode>(I)) return nullptr; 8509 8510 std::vector<Constant*> Operands(I->getNumOperands()); 8511 8512 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8513 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8514 if (!Operand) { 8515 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8516 if (!Operands[i]) return nullptr; 8517 continue; 8518 } 8519 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8520 Vals[Operand] = C; 8521 if (!C) return nullptr; 8522 Operands[i] = C; 8523 } 8524 8525 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8526 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8527 Operands[1], DL, TLI); 8528 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8529 if (!LI->isVolatile()) 8530 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8531 } 8532 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8533 } 8534 8535 8536 // If every incoming value to PN except the one for BB is a specific Constant, 8537 // return that, else return nullptr. 8538 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8539 Constant *IncomingVal = nullptr; 8540 8541 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8542 if (PN->getIncomingBlock(i) == BB) 8543 continue; 8544 8545 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8546 if (!CurrentVal) 8547 return nullptr; 8548 8549 if (IncomingVal != CurrentVal) { 8550 if (IncomingVal) 8551 return nullptr; 8552 IncomingVal = CurrentVal; 8553 } 8554 } 8555 8556 return IncomingVal; 8557 } 8558 8559 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8560 /// in the header of its containing loop, we know the loop executes a 8561 /// constant number of times, and the PHI node is just a recurrence 8562 /// involving constants, fold it. 8563 Constant * 8564 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8565 const APInt &BEs, 8566 const Loop *L) { 8567 auto I = ConstantEvolutionLoopExitValue.find(PN); 8568 if (I != ConstantEvolutionLoopExitValue.end()) 8569 return I->second; 8570 8571 if (BEs.ugt(MaxBruteForceIterations)) 8572 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8573 8574 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8575 8576 DenseMap<Instruction *, Constant *> CurrentIterVals; 8577 BasicBlock *Header = L->getHeader(); 8578 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8579 8580 BasicBlock *Latch = L->getLoopLatch(); 8581 if (!Latch) 8582 return nullptr; 8583 8584 for (PHINode &PHI : Header->phis()) { 8585 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8586 CurrentIterVals[&PHI] = StartCST; 8587 } 8588 if (!CurrentIterVals.count(PN)) 8589 return RetVal = nullptr; 8590 8591 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8592 8593 // Execute the loop symbolically to determine the exit value. 8594 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8595 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8596 8597 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8598 unsigned IterationNum = 0; 8599 const DataLayout &DL = getDataLayout(); 8600 for (; ; ++IterationNum) { 8601 if (IterationNum == NumIterations) 8602 return RetVal = CurrentIterVals[PN]; // Got exit value! 8603 8604 // Compute the value of the PHIs for the next iteration. 8605 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8606 DenseMap<Instruction *, Constant *> NextIterVals; 8607 Constant *NextPHI = 8608 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8609 if (!NextPHI) 8610 return nullptr; // Couldn't evaluate! 8611 NextIterVals[PN] = NextPHI; 8612 8613 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8614 8615 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8616 // cease to be able to evaluate one of them or if they stop evolving, 8617 // because that doesn't necessarily prevent us from computing PN. 8618 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8619 for (const auto &I : CurrentIterVals) { 8620 PHINode *PHI = dyn_cast<PHINode>(I.first); 8621 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8622 PHIsToCompute.emplace_back(PHI, I.second); 8623 } 8624 // We use two distinct loops because EvaluateExpression may invalidate any 8625 // iterators into CurrentIterVals. 8626 for (const auto &I : PHIsToCompute) { 8627 PHINode *PHI = I.first; 8628 Constant *&NextPHI = NextIterVals[PHI]; 8629 if (!NextPHI) { // Not already computed. 8630 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8631 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8632 } 8633 if (NextPHI != I.second) 8634 StoppedEvolving = false; 8635 } 8636 8637 // If all entries in CurrentIterVals == NextIterVals then we can stop 8638 // iterating, the loop can't continue to change. 8639 if (StoppedEvolving) 8640 return RetVal = CurrentIterVals[PN]; 8641 8642 CurrentIterVals.swap(NextIterVals); 8643 } 8644 } 8645 8646 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8647 Value *Cond, 8648 bool ExitWhen) { 8649 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8650 if (!PN) return getCouldNotCompute(); 8651 8652 // If the loop is canonicalized, the PHI will have exactly two entries. 8653 // That's the only form we support here. 8654 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8655 8656 DenseMap<Instruction *, Constant *> CurrentIterVals; 8657 BasicBlock *Header = L->getHeader(); 8658 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8659 8660 BasicBlock *Latch = L->getLoopLatch(); 8661 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8662 8663 for (PHINode &PHI : Header->phis()) { 8664 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8665 CurrentIterVals[&PHI] = StartCST; 8666 } 8667 if (!CurrentIterVals.count(PN)) 8668 return getCouldNotCompute(); 8669 8670 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8671 // the loop symbolically to determine when the condition gets a value of 8672 // "ExitWhen". 8673 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8674 const DataLayout &DL = getDataLayout(); 8675 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8676 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8677 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8678 8679 // Couldn't symbolically evaluate. 8680 if (!CondVal) return getCouldNotCompute(); 8681 8682 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8683 ++NumBruteForceTripCountsComputed; 8684 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8685 } 8686 8687 // Update all the PHI nodes for the next iteration. 8688 DenseMap<Instruction *, Constant *> NextIterVals; 8689 8690 // Create a list of which PHIs we need to compute. We want to do this before 8691 // calling EvaluateExpression on them because that may invalidate iterators 8692 // into CurrentIterVals. 8693 SmallVector<PHINode *, 8> PHIsToCompute; 8694 for (const auto &I : CurrentIterVals) { 8695 PHINode *PHI = dyn_cast<PHINode>(I.first); 8696 if (!PHI || PHI->getParent() != Header) continue; 8697 PHIsToCompute.push_back(PHI); 8698 } 8699 for (PHINode *PHI : PHIsToCompute) { 8700 Constant *&NextPHI = NextIterVals[PHI]; 8701 if (NextPHI) continue; // Already computed! 8702 8703 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8704 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8705 } 8706 CurrentIterVals.swap(NextIterVals); 8707 } 8708 8709 // Too many iterations were needed to evaluate. 8710 return getCouldNotCompute(); 8711 } 8712 8713 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8714 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8715 ValuesAtScopes[V]; 8716 // Check to see if we've folded this expression at this loop before. 8717 for (auto &LS : Values) 8718 if (LS.first == L) 8719 return LS.second ? LS.second : V; 8720 8721 Values.emplace_back(L, nullptr); 8722 8723 // Otherwise compute it. 8724 const SCEV *C = computeSCEVAtScope(V, L); 8725 for (auto &LS : reverse(ValuesAtScopes[V])) 8726 if (LS.first == L) { 8727 LS.second = C; 8728 break; 8729 } 8730 return C; 8731 } 8732 8733 /// This builds up a Constant using the ConstantExpr interface. That way, we 8734 /// will return Constants for objects which aren't represented by a 8735 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8736 /// Returns NULL if the SCEV isn't representable as a Constant. 8737 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8738 switch (V->getSCEVType()) { 8739 case scCouldNotCompute: 8740 case scAddRecExpr: 8741 return nullptr; 8742 case scConstant: 8743 return cast<SCEVConstant>(V)->getValue(); 8744 case scUnknown: 8745 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8746 case scSignExtend: { 8747 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8748 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8749 return ConstantExpr::getSExt(CastOp, SS->getType()); 8750 return nullptr; 8751 } 8752 case scZeroExtend: { 8753 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8754 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8755 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8756 return nullptr; 8757 } 8758 case scPtrToInt: { 8759 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8760 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8761 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8762 8763 return nullptr; 8764 } 8765 case scTruncate: { 8766 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8767 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8768 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8769 return nullptr; 8770 } 8771 case scAddExpr: { 8772 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8773 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8774 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8775 unsigned AS = PTy->getAddressSpace(); 8776 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8777 C = ConstantExpr::getBitCast(C, DestPtrTy); 8778 } 8779 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8780 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8781 if (!C2) 8782 return nullptr; 8783 8784 // First pointer! 8785 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8786 unsigned AS = C2->getType()->getPointerAddressSpace(); 8787 std::swap(C, C2); 8788 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8789 // The offsets have been converted to bytes. We can add bytes to an 8790 // i8* by GEP with the byte count in the first index. 8791 C = ConstantExpr::getBitCast(C, DestPtrTy); 8792 } 8793 8794 // Don't bother trying to sum two pointers. We probably can't 8795 // statically compute a load that results from it anyway. 8796 if (C2->getType()->isPointerTy()) 8797 return nullptr; 8798 8799 if (C->getType()->isPointerTy()) { 8800 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8801 C, C2); 8802 } else { 8803 C = ConstantExpr::getAdd(C, C2); 8804 } 8805 } 8806 return C; 8807 } 8808 return nullptr; 8809 } 8810 case scMulExpr: { 8811 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8812 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8813 // Don't bother with pointers at all. 8814 if (C->getType()->isPointerTy()) 8815 return nullptr; 8816 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8817 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8818 if (!C2 || C2->getType()->isPointerTy()) 8819 return nullptr; 8820 C = ConstantExpr::getMul(C, C2); 8821 } 8822 return C; 8823 } 8824 return nullptr; 8825 } 8826 case scUDivExpr: { 8827 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8828 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8829 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8830 if (LHS->getType() == RHS->getType()) 8831 return ConstantExpr::getUDiv(LHS, RHS); 8832 return nullptr; 8833 } 8834 case scSMaxExpr: 8835 case scUMaxExpr: 8836 case scSMinExpr: 8837 case scUMinExpr: 8838 return nullptr; // TODO: smax, umax, smin, umax. 8839 } 8840 llvm_unreachable("Unknown SCEV kind!"); 8841 } 8842 8843 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8844 if (isa<SCEVConstant>(V)) return V; 8845 8846 // If this instruction is evolved from a constant-evolving PHI, compute the 8847 // exit value from the loop without using SCEVs. 8848 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8849 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8850 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8851 const Loop *CurrLoop = this->LI[I->getParent()]; 8852 // Looking for loop exit value. 8853 if (CurrLoop && CurrLoop->getParentLoop() == L && 8854 PN->getParent() == CurrLoop->getHeader()) { 8855 // Okay, there is no closed form solution for the PHI node. Check 8856 // to see if the loop that contains it has a known backedge-taken 8857 // count. If so, we may be able to force computation of the exit 8858 // value. 8859 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8860 // This trivial case can show up in some degenerate cases where 8861 // the incoming IR has not yet been fully simplified. 8862 if (BackedgeTakenCount->isZero()) { 8863 Value *InitValue = nullptr; 8864 bool MultipleInitValues = false; 8865 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8866 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8867 if (!InitValue) 8868 InitValue = PN->getIncomingValue(i); 8869 else if (InitValue != PN->getIncomingValue(i)) { 8870 MultipleInitValues = true; 8871 break; 8872 } 8873 } 8874 } 8875 if (!MultipleInitValues && InitValue) 8876 return getSCEV(InitValue); 8877 } 8878 // Do we have a loop invariant value flowing around the backedge 8879 // for a loop which must execute the backedge? 8880 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8881 isKnownPositive(BackedgeTakenCount) && 8882 PN->getNumIncomingValues() == 2) { 8883 8884 unsigned InLoopPred = 8885 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8886 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8887 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8888 return getSCEV(BackedgeVal); 8889 } 8890 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8891 // Okay, we know how many times the containing loop executes. If 8892 // this is a constant evolving PHI node, get the final value at 8893 // the specified iteration number. 8894 Constant *RV = getConstantEvolutionLoopExitValue( 8895 PN, BTCC->getAPInt(), CurrLoop); 8896 if (RV) return getSCEV(RV); 8897 } 8898 } 8899 8900 // If there is a single-input Phi, evaluate it at our scope. If we can 8901 // prove that this replacement does not break LCSSA form, use new value. 8902 if (PN->getNumOperands() == 1) { 8903 const SCEV *Input = getSCEV(PN->getOperand(0)); 8904 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8905 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8906 // for the simplest case just support constants. 8907 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8908 } 8909 } 8910 8911 // Okay, this is an expression that we cannot symbolically evaluate 8912 // into a SCEV. Check to see if it's possible to symbolically evaluate 8913 // the arguments into constants, and if so, try to constant propagate the 8914 // result. This is particularly useful for computing loop exit values. 8915 if (CanConstantFold(I)) { 8916 SmallVector<Constant *, 4> Operands; 8917 bool MadeImprovement = false; 8918 for (Value *Op : I->operands()) { 8919 if (Constant *C = dyn_cast<Constant>(Op)) { 8920 Operands.push_back(C); 8921 continue; 8922 } 8923 8924 // If any of the operands is non-constant and if they are 8925 // non-integer and non-pointer, don't even try to analyze them 8926 // with scev techniques. 8927 if (!isSCEVable(Op->getType())) 8928 return V; 8929 8930 const SCEV *OrigV = getSCEV(Op); 8931 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8932 MadeImprovement |= OrigV != OpV; 8933 8934 Constant *C = BuildConstantFromSCEV(OpV); 8935 if (!C) return V; 8936 if (C->getType() != Op->getType()) 8937 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8938 Op->getType(), 8939 false), 8940 C, Op->getType()); 8941 Operands.push_back(C); 8942 } 8943 8944 // Check to see if getSCEVAtScope actually made an improvement. 8945 if (MadeImprovement) { 8946 Constant *C = nullptr; 8947 const DataLayout &DL = getDataLayout(); 8948 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8949 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8950 Operands[1], DL, &TLI); 8951 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8952 if (!Load->isVolatile()) 8953 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8954 DL); 8955 } else 8956 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8957 if (!C) return V; 8958 return getSCEV(C); 8959 } 8960 } 8961 } 8962 8963 // This is some other type of SCEVUnknown, just return it. 8964 return V; 8965 } 8966 8967 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8968 // Avoid performing the look-up in the common case where the specified 8969 // expression has no loop-variant portions. 8970 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8971 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8972 if (OpAtScope != Comm->getOperand(i)) { 8973 // Okay, at least one of these operands is loop variant but might be 8974 // foldable. Build a new instance of the folded commutative expression. 8975 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8976 Comm->op_begin()+i); 8977 NewOps.push_back(OpAtScope); 8978 8979 for (++i; i != e; ++i) { 8980 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8981 NewOps.push_back(OpAtScope); 8982 } 8983 if (isa<SCEVAddExpr>(Comm)) 8984 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8985 if (isa<SCEVMulExpr>(Comm)) 8986 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8987 if (isa<SCEVMinMaxExpr>(Comm)) 8988 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8989 llvm_unreachable("Unknown commutative SCEV type!"); 8990 } 8991 } 8992 // If we got here, all operands are loop invariant. 8993 return Comm; 8994 } 8995 8996 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8997 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8998 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8999 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9000 return Div; // must be loop invariant 9001 return getUDivExpr(LHS, RHS); 9002 } 9003 9004 // If this is a loop recurrence for a loop that does not contain L, then we 9005 // are dealing with the final value computed by the loop. 9006 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9007 // First, attempt to evaluate each operand. 9008 // Avoid performing the look-up in the common case where the specified 9009 // expression has no loop-variant portions. 9010 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9011 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9012 if (OpAtScope == AddRec->getOperand(i)) 9013 continue; 9014 9015 // Okay, at least one of these operands is loop variant but might be 9016 // foldable. Build a new instance of the folded commutative expression. 9017 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9018 AddRec->op_begin()+i); 9019 NewOps.push_back(OpAtScope); 9020 for (++i; i != e; ++i) 9021 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9022 9023 const SCEV *FoldedRec = 9024 getAddRecExpr(NewOps, AddRec->getLoop(), 9025 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9026 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9027 // The addrec may be folded to a nonrecurrence, for example, if the 9028 // induction variable is multiplied by zero after constant folding. Go 9029 // ahead and return the folded value. 9030 if (!AddRec) 9031 return FoldedRec; 9032 break; 9033 } 9034 9035 // If the scope is outside the addrec's loop, evaluate it by using the 9036 // loop exit value of the addrec. 9037 if (!AddRec->getLoop()->contains(L)) { 9038 // To evaluate this recurrence, we need to know how many times the AddRec 9039 // loop iterates. Compute this now. 9040 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9041 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9042 9043 // Then, evaluate the AddRec. 9044 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9045 } 9046 9047 return AddRec; 9048 } 9049 9050 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9051 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9052 if (Op == Cast->getOperand()) 9053 return Cast; // must be loop invariant 9054 return getZeroExtendExpr(Op, Cast->getType()); 9055 } 9056 9057 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9058 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9059 if (Op == Cast->getOperand()) 9060 return Cast; // must be loop invariant 9061 return getSignExtendExpr(Op, Cast->getType()); 9062 } 9063 9064 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9065 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9066 if (Op == Cast->getOperand()) 9067 return Cast; // must be loop invariant 9068 return getTruncateExpr(Op, Cast->getType()); 9069 } 9070 9071 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9072 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9073 if (Op == Cast->getOperand()) 9074 return Cast; // must be loop invariant 9075 return getPtrToIntExpr(Op, Cast->getType()); 9076 } 9077 9078 llvm_unreachable("Unknown SCEV type!"); 9079 } 9080 9081 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9082 return getSCEVAtScope(getSCEV(V), L); 9083 } 9084 9085 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9086 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9087 return stripInjectiveFunctions(ZExt->getOperand()); 9088 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9089 return stripInjectiveFunctions(SExt->getOperand()); 9090 return S; 9091 } 9092 9093 /// Finds the minimum unsigned root of the following equation: 9094 /// 9095 /// A * X = B (mod N) 9096 /// 9097 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9098 /// A and B isn't important. 9099 /// 9100 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9101 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9102 ScalarEvolution &SE) { 9103 uint32_t BW = A.getBitWidth(); 9104 assert(BW == SE.getTypeSizeInBits(B->getType())); 9105 assert(A != 0 && "A must be non-zero."); 9106 9107 // 1. D = gcd(A, N) 9108 // 9109 // The gcd of A and N may have only one prime factor: 2. The number of 9110 // trailing zeros in A is its multiplicity 9111 uint32_t Mult2 = A.countTrailingZeros(); 9112 // D = 2^Mult2 9113 9114 // 2. Check if B is divisible by D. 9115 // 9116 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9117 // is not less than multiplicity of this prime factor for D. 9118 if (SE.GetMinTrailingZeros(B) < Mult2) 9119 return SE.getCouldNotCompute(); 9120 9121 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9122 // modulo (N / D). 9123 // 9124 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9125 // (N / D) in general. The inverse itself always fits into BW bits, though, 9126 // so we immediately truncate it. 9127 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9128 APInt Mod(BW + 1, 0); 9129 Mod.setBit(BW - Mult2); // Mod = N / D 9130 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9131 9132 // 4. Compute the minimum unsigned root of the equation: 9133 // I * (B / D) mod (N / D) 9134 // To simplify the computation, we factor out the divide by D: 9135 // (I * B mod N) / D 9136 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9137 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9138 } 9139 9140 /// For a given quadratic addrec, generate coefficients of the corresponding 9141 /// quadratic equation, multiplied by a common value to ensure that they are 9142 /// integers. 9143 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9144 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9145 /// were multiplied by, and BitWidth is the bit width of the original addrec 9146 /// coefficients. 9147 /// This function returns None if the addrec coefficients are not compile- 9148 /// time constants. 9149 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9150 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9151 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9152 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9153 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9154 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9155 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9156 << *AddRec << '\n'); 9157 9158 // We currently can only solve this if the coefficients are constants. 9159 if (!LC || !MC || !NC) { 9160 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9161 return None; 9162 } 9163 9164 APInt L = LC->getAPInt(); 9165 APInt M = MC->getAPInt(); 9166 APInt N = NC->getAPInt(); 9167 assert(!N.isZero() && "This is not a quadratic addrec"); 9168 9169 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9170 unsigned NewWidth = BitWidth + 1; 9171 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9172 << BitWidth << '\n'); 9173 // The sign-extension (as opposed to a zero-extension) here matches the 9174 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9175 N = N.sext(NewWidth); 9176 M = M.sext(NewWidth); 9177 L = L.sext(NewWidth); 9178 9179 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9180 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9181 // L+M, L+2M+N, L+3M+3N, ... 9182 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9183 // 9184 // The equation Acc = 0 is then 9185 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9186 // In a quadratic form it becomes: 9187 // N n^2 + (2M-N) n + 2L = 0. 9188 9189 APInt A = N; 9190 APInt B = 2 * M - A; 9191 APInt C = 2 * L; 9192 APInt T = APInt(NewWidth, 2); 9193 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9194 << "x + " << C << ", coeff bw: " << NewWidth 9195 << ", multiplied by " << T << '\n'); 9196 return std::make_tuple(A, B, C, T, BitWidth); 9197 } 9198 9199 /// Helper function to compare optional APInts: 9200 /// (a) if X and Y both exist, return min(X, Y), 9201 /// (b) if neither X nor Y exist, return None, 9202 /// (c) if exactly one of X and Y exists, return that value. 9203 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9204 if (X.hasValue() && Y.hasValue()) { 9205 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9206 APInt XW = X->sextOrSelf(W); 9207 APInt YW = Y->sextOrSelf(W); 9208 return XW.slt(YW) ? *X : *Y; 9209 } 9210 if (!X.hasValue() && !Y.hasValue()) 9211 return None; 9212 return X.hasValue() ? *X : *Y; 9213 } 9214 9215 /// Helper function to truncate an optional APInt to a given BitWidth. 9216 /// When solving addrec-related equations, it is preferable to return a value 9217 /// that has the same bit width as the original addrec's coefficients. If the 9218 /// solution fits in the original bit width, truncate it (except for i1). 9219 /// Returning a value of a different bit width may inhibit some optimizations. 9220 /// 9221 /// In general, a solution to a quadratic equation generated from an addrec 9222 /// may require BW+1 bits, where BW is the bit width of the addrec's 9223 /// coefficients. The reason is that the coefficients of the quadratic 9224 /// equation are BW+1 bits wide (to avoid truncation when converting from 9225 /// the addrec to the equation). 9226 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9227 if (!X.hasValue()) 9228 return None; 9229 unsigned W = X->getBitWidth(); 9230 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9231 return X->trunc(BitWidth); 9232 return X; 9233 } 9234 9235 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9236 /// iterations. The values L, M, N are assumed to be signed, and they 9237 /// should all have the same bit widths. 9238 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9239 /// where BW is the bit width of the addrec's coefficients. 9240 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9241 /// returned as such, otherwise the bit width of the returned value may 9242 /// be greater than BW. 9243 /// 9244 /// This function returns None if 9245 /// (a) the addrec coefficients are not constant, or 9246 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9247 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9248 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9249 static Optional<APInt> 9250 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9251 APInt A, B, C, M; 9252 unsigned BitWidth; 9253 auto T = GetQuadraticEquation(AddRec); 9254 if (!T.hasValue()) 9255 return None; 9256 9257 std::tie(A, B, C, M, BitWidth) = *T; 9258 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9259 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9260 if (!X.hasValue()) 9261 return None; 9262 9263 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9264 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9265 if (!V->isZero()) 9266 return None; 9267 9268 return TruncIfPossible(X, BitWidth); 9269 } 9270 9271 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9272 /// iterations. The values M, N are assumed to be signed, and they 9273 /// should all have the same bit widths. 9274 /// Find the least n such that c(n) does not belong to the given range, 9275 /// while c(n-1) does. 9276 /// 9277 /// This function returns None if 9278 /// (a) the addrec coefficients are not constant, or 9279 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9280 /// bounds of the range. 9281 static Optional<APInt> 9282 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9283 const ConstantRange &Range, ScalarEvolution &SE) { 9284 assert(AddRec->getOperand(0)->isZero() && 9285 "Starting value of addrec should be 0"); 9286 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9287 << Range << ", addrec " << *AddRec << '\n'); 9288 // This case is handled in getNumIterationsInRange. Here we can assume that 9289 // we start in the range. 9290 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9291 "Addrec's initial value should be in range"); 9292 9293 APInt A, B, C, M; 9294 unsigned BitWidth; 9295 auto T = GetQuadraticEquation(AddRec); 9296 if (!T.hasValue()) 9297 return None; 9298 9299 // Be careful about the return value: there can be two reasons for not 9300 // returning an actual number. First, if no solutions to the equations 9301 // were found, and second, if the solutions don't leave the given range. 9302 // The first case means that the actual solution is "unknown", the second 9303 // means that it's known, but not valid. If the solution is unknown, we 9304 // cannot make any conclusions. 9305 // Return a pair: the optional solution and a flag indicating if the 9306 // solution was found. 9307 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9308 // Solve for signed overflow and unsigned overflow, pick the lower 9309 // solution. 9310 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9311 << Bound << " (before multiplying by " << M << ")\n"); 9312 Bound *= M; // The quadratic equation multiplier. 9313 9314 Optional<APInt> SO = None; 9315 if (BitWidth > 1) { 9316 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9317 "signed overflow\n"); 9318 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9319 } 9320 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9321 "unsigned overflow\n"); 9322 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9323 BitWidth+1); 9324 9325 auto LeavesRange = [&] (const APInt &X) { 9326 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9327 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9328 if (Range.contains(V0->getValue())) 9329 return false; 9330 // X should be at least 1, so X-1 is non-negative. 9331 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9332 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9333 if (Range.contains(V1->getValue())) 9334 return true; 9335 return false; 9336 }; 9337 9338 // If SolveQuadraticEquationWrap returns None, it means that there can 9339 // be a solution, but the function failed to find it. We cannot treat it 9340 // as "no solution". 9341 if (!SO.hasValue() || !UO.hasValue()) 9342 return { None, false }; 9343 9344 // Check the smaller value first to see if it leaves the range. 9345 // At this point, both SO and UO must have values. 9346 Optional<APInt> Min = MinOptional(SO, UO); 9347 if (LeavesRange(*Min)) 9348 return { Min, true }; 9349 Optional<APInt> Max = Min == SO ? UO : SO; 9350 if (LeavesRange(*Max)) 9351 return { Max, true }; 9352 9353 // Solutions were found, but were eliminated, hence the "true". 9354 return { None, true }; 9355 }; 9356 9357 std::tie(A, B, C, M, BitWidth) = *T; 9358 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9359 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9360 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9361 auto SL = SolveForBoundary(Lower); 9362 auto SU = SolveForBoundary(Upper); 9363 // If any of the solutions was unknown, no meaninigful conclusions can 9364 // be made. 9365 if (!SL.second || !SU.second) 9366 return None; 9367 9368 // Claim: The correct solution is not some value between Min and Max. 9369 // 9370 // Justification: Assuming that Min and Max are different values, one of 9371 // them is when the first signed overflow happens, the other is when the 9372 // first unsigned overflow happens. Crossing the range boundary is only 9373 // possible via an overflow (treating 0 as a special case of it, modeling 9374 // an overflow as crossing k*2^W for some k). 9375 // 9376 // The interesting case here is when Min was eliminated as an invalid 9377 // solution, but Max was not. The argument is that if there was another 9378 // overflow between Min and Max, it would also have been eliminated if 9379 // it was considered. 9380 // 9381 // For a given boundary, it is possible to have two overflows of the same 9382 // type (signed/unsigned) without having the other type in between: this 9383 // can happen when the vertex of the parabola is between the iterations 9384 // corresponding to the overflows. This is only possible when the two 9385 // overflows cross k*2^W for the same k. In such case, if the second one 9386 // left the range (and was the first one to do so), the first overflow 9387 // would have to enter the range, which would mean that either we had left 9388 // the range before or that we started outside of it. Both of these cases 9389 // are contradictions. 9390 // 9391 // Claim: In the case where SolveForBoundary returns None, the correct 9392 // solution is not some value between the Max for this boundary and the 9393 // Min of the other boundary. 9394 // 9395 // Justification: Assume that we had such Max_A and Min_B corresponding 9396 // to range boundaries A and B and such that Max_A < Min_B. If there was 9397 // a solution between Max_A and Min_B, it would have to be caused by an 9398 // overflow corresponding to either A or B. It cannot correspond to B, 9399 // since Min_B is the first occurrence of such an overflow. If it 9400 // corresponded to A, it would have to be either a signed or an unsigned 9401 // overflow that is larger than both eliminated overflows for A. But 9402 // between the eliminated overflows and this overflow, the values would 9403 // cover the entire value space, thus crossing the other boundary, which 9404 // is a contradiction. 9405 9406 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9407 } 9408 9409 ScalarEvolution::ExitLimit 9410 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9411 bool AllowPredicates) { 9412 9413 // This is only used for loops with a "x != y" exit test. The exit condition 9414 // is now expressed as a single expression, V = x-y. So the exit test is 9415 // effectively V != 0. We know and take advantage of the fact that this 9416 // expression only being used in a comparison by zero context. 9417 9418 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9419 // If the value is a constant 9420 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9421 // If the value is already zero, the branch will execute zero times. 9422 if (C->getValue()->isZero()) return C; 9423 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9424 } 9425 9426 const SCEVAddRecExpr *AddRec = 9427 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9428 9429 if (!AddRec && AllowPredicates) 9430 // Try to make this an AddRec using runtime tests, in the first X 9431 // iterations of this loop, where X is the SCEV expression found by the 9432 // algorithm below. 9433 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9434 9435 if (!AddRec || AddRec->getLoop() != L) 9436 return getCouldNotCompute(); 9437 9438 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9439 // the quadratic equation to solve it. 9440 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9441 // We can only use this value if the chrec ends up with an exact zero 9442 // value at this index. When solving for "X*X != 5", for example, we 9443 // should not accept a root of 2. 9444 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9445 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9446 return ExitLimit(R, R, false, Predicates); 9447 } 9448 return getCouldNotCompute(); 9449 } 9450 9451 // Otherwise we can only handle this if it is affine. 9452 if (!AddRec->isAffine()) 9453 return getCouldNotCompute(); 9454 9455 // If this is an affine expression, the execution count of this branch is 9456 // the minimum unsigned root of the following equation: 9457 // 9458 // Start + Step*N = 0 (mod 2^BW) 9459 // 9460 // equivalent to: 9461 // 9462 // Step*N = -Start (mod 2^BW) 9463 // 9464 // where BW is the common bit width of Start and Step. 9465 9466 // Get the initial value for the loop. 9467 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9468 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9469 9470 // For now we handle only constant steps. 9471 // 9472 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9473 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9474 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9475 // We have not yet seen any such cases. 9476 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9477 if (!StepC || StepC->getValue()->isZero()) 9478 return getCouldNotCompute(); 9479 9480 // For positive steps (counting up until unsigned overflow): 9481 // N = -Start/Step (as unsigned) 9482 // For negative steps (counting down to zero): 9483 // N = Start/-Step 9484 // First compute the unsigned distance from zero in the direction of Step. 9485 bool CountDown = StepC->getAPInt().isNegative(); 9486 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9487 9488 // Handle unitary steps, which cannot wraparound. 9489 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9490 // N = Distance (as unsigned) 9491 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9492 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9493 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9494 if (MaxBECountBase.ult(MaxBECount)) 9495 MaxBECount = MaxBECountBase; 9496 9497 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9498 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9499 // case, and see if we can improve the bound. 9500 // 9501 // Explicitly handling this here is necessary because getUnsignedRange 9502 // isn't context-sensitive; it doesn't know that we only care about the 9503 // range inside the loop. 9504 const SCEV *Zero = getZero(Distance->getType()); 9505 const SCEV *One = getOne(Distance->getType()); 9506 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9507 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9508 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9509 // as "unsigned_max(Distance + 1) - 1". 9510 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9511 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9512 } 9513 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9514 } 9515 9516 // If the condition controls loop exit (the loop exits only if the expression 9517 // is true) and the addition is no-wrap we can use unsigned divide to 9518 // compute the backedge count. In this case, the step may not divide the 9519 // distance, but we don't care because if the condition is "missed" the loop 9520 // will have undefined behavior due to wrapping. 9521 if (ControlsExit && AddRec->hasNoSelfWrap() && 9522 loopHasNoAbnormalExits(AddRec->getLoop())) { 9523 const SCEV *Exact = 9524 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9525 const SCEV *Max = getCouldNotCompute(); 9526 if (Exact != getCouldNotCompute()) { 9527 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9528 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9529 if (BaseMaxInt.ult(MaxInt)) 9530 Max = getConstant(BaseMaxInt); 9531 else 9532 Max = getConstant(MaxInt); 9533 } 9534 return ExitLimit(Exact, Max, false, Predicates); 9535 } 9536 9537 // Solve the general equation. 9538 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9539 getNegativeSCEV(Start), *this); 9540 const SCEV *M = E == getCouldNotCompute() 9541 ? E 9542 : getConstant(getUnsignedRangeMax(E)); 9543 return ExitLimit(E, M, false, Predicates); 9544 } 9545 9546 ScalarEvolution::ExitLimit 9547 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9548 // Loops that look like: while (X == 0) are very strange indeed. We don't 9549 // handle them yet except for the trivial case. This could be expanded in the 9550 // future as needed. 9551 9552 // If the value is a constant, check to see if it is known to be non-zero 9553 // already. If so, the backedge will execute zero times. 9554 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9555 if (!C->getValue()->isZero()) 9556 return getZero(C->getType()); 9557 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9558 } 9559 9560 // We could implement others, but I really doubt anyone writes loops like 9561 // this, and if they did, they would already be constant folded. 9562 return getCouldNotCompute(); 9563 } 9564 9565 std::pair<const BasicBlock *, const BasicBlock *> 9566 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9567 const { 9568 // If the block has a unique predecessor, then there is no path from the 9569 // predecessor to the block that does not go through the direct edge 9570 // from the predecessor to the block. 9571 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9572 return {Pred, BB}; 9573 9574 // A loop's header is defined to be a block that dominates the loop. 9575 // If the header has a unique predecessor outside the loop, it must be 9576 // a block that has exactly one successor that can reach the loop. 9577 if (const Loop *L = LI.getLoopFor(BB)) 9578 return {L->getLoopPredecessor(), L->getHeader()}; 9579 9580 return {nullptr, nullptr}; 9581 } 9582 9583 /// SCEV structural equivalence is usually sufficient for testing whether two 9584 /// expressions are equal, however for the purposes of looking for a condition 9585 /// guarding a loop, it can be useful to be a little more general, since a 9586 /// front-end may have replicated the controlling expression. 9587 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9588 // Quick check to see if they are the same SCEV. 9589 if (A == B) return true; 9590 9591 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9592 // Not all instructions that are "identical" compute the same value. For 9593 // instance, two distinct alloca instructions allocating the same type are 9594 // identical and do not read memory; but compute distinct values. 9595 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9596 }; 9597 9598 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9599 // two different instructions with the same value. Check for this case. 9600 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9601 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9602 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9603 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9604 if (ComputesEqualValues(AI, BI)) 9605 return true; 9606 9607 // Otherwise assume they may have a different value. 9608 return false; 9609 } 9610 9611 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9612 const SCEV *&LHS, const SCEV *&RHS, 9613 unsigned Depth) { 9614 bool Changed = false; 9615 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9616 // '0 != 0'. 9617 auto TrivialCase = [&](bool TriviallyTrue) { 9618 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9619 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9620 return true; 9621 }; 9622 // If we hit the max recursion limit bail out. 9623 if (Depth >= 3) 9624 return false; 9625 9626 // Canonicalize a constant to the right side. 9627 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9628 // Check for both operands constant. 9629 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9630 if (ConstantExpr::getICmp(Pred, 9631 LHSC->getValue(), 9632 RHSC->getValue())->isNullValue()) 9633 return TrivialCase(false); 9634 else 9635 return TrivialCase(true); 9636 } 9637 // Otherwise swap the operands to put the constant on the right. 9638 std::swap(LHS, RHS); 9639 Pred = ICmpInst::getSwappedPredicate(Pred); 9640 Changed = true; 9641 } 9642 9643 // If we're comparing an addrec with a value which is loop-invariant in the 9644 // addrec's loop, put the addrec on the left. Also make a dominance check, 9645 // as both operands could be addrecs loop-invariant in each other's loop. 9646 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9647 const Loop *L = AR->getLoop(); 9648 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9649 std::swap(LHS, RHS); 9650 Pred = ICmpInst::getSwappedPredicate(Pred); 9651 Changed = true; 9652 } 9653 } 9654 9655 // If there's a constant operand, canonicalize comparisons with boundary 9656 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9657 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9658 const APInt &RA = RC->getAPInt(); 9659 9660 bool SimplifiedByConstantRange = false; 9661 9662 if (!ICmpInst::isEquality(Pred)) { 9663 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9664 if (ExactCR.isFullSet()) 9665 return TrivialCase(true); 9666 else if (ExactCR.isEmptySet()) 9667 return TrivialCase(false); 9668 9669 APInt NewRHS; 9670 CmpInst::Predicate NewPred; 9671 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9672 ICmpInst::isEquality(NewPred)) { 9673 // We were able to convert an inequality to an equality. 9674 Pred = NewPred; 9675 RHS = getConstant(NewRHS); 9676 Changed = SimplifiedByConstantRange = true; 9677 } 9678 } 9679 9680 if (!SimplifiedByConstantRange) { 9681 switch (Pred) { 9682 default: 9683 break; 9684 case ICmpInst::ICMP_EQ: 9685 case ICmpInst::ICMP_NE: 9686 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9687 if (!RA) 9688 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9689 if (const SCEVMulExpr *ME = 9690 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9691 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9692 ME->getOperand(0)->isAllOnesValue()) { 9693 RHS = AE->getOperand(1); 9694 LHS = ME->getOperand(1); 9695 Changed = true; 9696 } 9697 break; 9698 9699 9700 // The "Should have been caught earlier!" messages refer to the fact 9701 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9702 // should have fired on the corresponding cases, and canonicalized the 9703 // check to trivial case. 9704 9705 case ICmpInst::ICMP_UGE: 9706 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9707 Pred = ICmpInst::ICMP_UGT; 9708 RHS = getConstant(RA - 1); 9709 Changed = true; 9710 break; 9711 case ICmpInst::ICMP_ULE: 9712 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9713 Pred = ICmpInst::ICMP_ULT; 9714 RHS = getConstant(RA + 1); 9715 Changed = true; 9716 break; 9717 case ICmpInst::ICMP_SGE: 9718 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9719 Pred = ICmpInst::ICMP_SGT; 9720 RHS = getConstant(RA - 1); 9721 Changed = true; 9722 break; 9723 case ICmpInst::ICMP_SLE: 9724 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9725 Pred = ICmpInst::ICMP_SLT; 9726 RHS = getConstant(RA + 1); 9727 Changed = true; 9728 break; 9729 } 9730 } 9731 } 9732 9733 // Check for obvious equality. 9734 if (HasSameValue(LHS, RHS)) { 9735 if (ICmpInst::isTrueWhenEqual(Pred)) 9736 return TrivialCase(true); 9737 if (ICmpInst::isFalseWhenEqual(Pred)) 9738 return TrivialCase(false); 9739 } 9740 9741 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9742 // adding or subtracting 1 from one of the operands. 9743 switch (Pred) { 9744 case ICmpInst::ICMP_SLE: 9745 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9746 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9747 SCEV::FlagNSW); 9748 Pred = ICmpInst::ICMP_SLT; 9749 Changed = true; 9750 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9751 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9752 SCEV::FlagNSW); 9753 Pred = ICmpInst::ICMP_SLT; 9754 Changed = true; 9755 } 9756 break; 9757 case ICmpInst::ICMP_SGE: 9758 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9759 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9760 SCEV::FlagNSW); 9761 Pred = ICmpInst::ICMP_SGT; 9762 Changed = true; 9763 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9764 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9765 SCEV::FlagNSW); 9766 Pred = ICmpInst::ICMP_SGT; 9767 Changed = true; 9768 } 9769 break; 9770 case ICmpInst::ICMP_ULE: 9771 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9772 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9773 SCEV::FlagNUW); 9774 Pred = ICmpInst::ICMP_ULT; 9775 Changed = true; 9776 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9777 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9778 Pred = ICmpInst::ICMP_ULT; 9779 Changed = true; 9780 } 9781 break; 9782 case ICmpInst::ICMP_UGE: 9783 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9784 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9785 Pred = ICmpInst::ICMP_UGT; 9786 Changed = true; 9787 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9788 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9789 SCEV::FlagNUW); 9790 Pred = ICmpInst::ICMP_UGT; 9791 Changed = true; 9792 } 9793 break; 9794 default: 9795 break; 9796 } 9797 9798 // TODO: More simplifications are possible here. 9799 9800 // Recursively simplify until we either hit a recursion limit or nothing 9801 // changes. 9802 if (Changed) 9803 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9804 9805 return Changed; 9806 } 9807 9808 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9809 return getSignedRangeMax(S).isNegative(); 9810 } 9811 9812 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9813 return getSignedRangeMin(S).isStrictlyPositive(); 9814 } 9815 9816 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9817 return !getSignedRangeMin(S).isNegative(); 9818 } 9819 9820 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9821 return !getSignedRangeMax(S).isStrictlyPositive(); 9822 } 9823 9824 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9825 return getUnsignedRangeMin(S) != 0; 9826 } 9827 9828 std::pair<const SCEV *, const SCEV *> 9829 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9830 // Compute SCEV on entry of loop L. 9831 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9832 if (Start == getCouldNotCompute()) 9833 return { Start, Start }; 9834 // Compute post increment SCEV for loop L. 9835 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9836 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9837 return { Start, PostInc }; 9838 } 9839 9840 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9841 const SCEV *LHS, const SCEV *RHS) { 9842 // First collect all loops. 9843 SmallPtrSet<const Loop *, 8> LoopsUsed; 9844 getUsedLoops(LHS, LoopsUsed); 9845 getUsedLoops(RHS, LoopsUsed); 9846 9847 if (LoopsUsed.empty()) 9848 return false; 9849 9850 // Domination relationship must be a linear order on collected loops. 9851 #ifndef NDEBUG 9852 for (auto *L1 : LoopsUsed) 9853 for (auto *L2 : LoopsUsed) 9854 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9855 DT.dominates(L2->getHeader(), L1->getHeader())) && 9856 "Domination relationship is not a linear order"); 9857 #endif 9858 9859 const Loop *MDL = 9860 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9861 [&](const Loop *L1, const Loop *L2) { 9862 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9863 }); 9864 9865 // Get init and post increment value for LHS. 9866 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9867 // if LHS contains unknown non-invariant SCEV then bail out. 9868 if (SplitLHS.first == getCouldNotCompute()) 9869 return false; 9870 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9871 // Get init and post increment value for RHS. 9872 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9873 // if RHS contains unknown non-invariant SCEV then bail out. 9874 if (SplitRHS.first == getCouldNotCompute()) 9875 return false; 9876 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9877 // It is possible that init SCEV contains an invariant load but it does 9878 // not dominate MDL and is not available at MDL loop entry, so we should 9879 // check it here. 9880 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9881 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9882 return false; 9883 9884 // It seems backedge guard check is faster than entry one so in some cases 9885 // it can speed up whole estimation by short circuit 9886 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9887 SplitRHS.second) && 9888 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9889 } 9890 9891 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9892 const SCEV *LHS, const SCEV *RHS) { 9893 // Canonicalize the inputs first. 9894 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9895 9896 if (isKnownViaInduction(Pred, LHS, RHS)) 9897 return true; 9898 9899 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9900 return true; 9901 9902 // Otherwise see what can be done with some simple reasoning. 9903 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9904 } 9905 9906 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9907 const SCEV *LHS, 9908 const SCEV *RHS) { 9909 if (isKnownPredicate(Pred, LHS, RHS)) 9910 return true; 9911 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9912 return false; 9913 return None; 9914 } 9915 9916 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9917 const SCEV *LHS, const SCEV *RHS, 9918 const Instruction *CtxI) { 9919 // TODO: Analyze guards and assumes from Context's block. 9920 return isKnownPredicate(Pred, LHS, RHS) || 9921 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 9922 } 9923 9924 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 9925 const SCEV *LHS, 9926 const SCEV *RHS, 9927 const Instruction *CtxI) { 9928 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9929 if (KnownWithoutContext) 9930 return KnownWithoutContext; 9931 9932 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 9933 return true; 9934 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 9935 ICmpInst::getInversePredicate(Pred), 9936 LHS, RHS)) 9937 return false; 9938 return None; 9939 } 9940 9941 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9942 const SCEVAddRecExpr *LHS, 9943 const SCEV *RHS) { 9944 const Loop *L = LHS->getLoop(); 9945 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9946 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9947 } 9948 9949 Optional<ScalarEvolution::MonotonicPredicateType> 9950 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9951 ICmpInst::Predicate Pred) { 9952 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9953 9954 #ifndef NDEBUG 9955 // Verify an invariant: inverting the predicate should turn a monotonically 9956 // increasing change to a monotonically decreasing one, and vice versa. 9957 if (Result) { 9958 auto ResultSwapped = 9959 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9960 9961 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9962 assert(ResultSwapped.getValue() != Result.getValue() && 9963 "monotonicity should flip as we flip the predicate"); 9964 } 9965 #endif 9966 9967 return Result; 9968 } 9969 9970 Optional<ScalarEvolution::MonotonicPredicateType> 9971 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9972 ICmpInst::Predicate Pred) { 9973 // A zero step value for LHS means the induction variable is essentially a 9974 // loop invariant value. We don't really depend on the predicate actually 9975 // flipping from false to true (for increasing predicates, and the other way 9976 // around for decreasing predicates), all we care about is that *if* the 9977 // predicate changes then it only changes from false to true. 9978 // 9979 // A zero step value in itself is not very useful, but there may be places 9980 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9981 // as general as possible. 9982 9983 // Only handle LE/LT/GE/GT predicates. 9984 if (!ICmpInst::isRelational(Pred)) 9985 return None; 9986 9987 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9988 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9989 "Should be greater or less!"); 9990 9991 // Check that AR does not wrap. 9992 if (ICmpInst::isUnsigned(Pred)) { 9993 if (!LHS->hasNoUnsignedWrap()) 9994 return None; 9995 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9996 } else { 9997 assert(ICmpInst::isSigned(Pred) && 9998 "Relational predicate is either signed or unsigned!"); 9999 if (!LHS->hasNoSignedWrap()) 10000 return None; 10001 10002 const SCEV *Step = LHS->getStepRecurrence(*this); 10003 10004 if (isKnownNonNegative(Step)) 10005 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10006 10007 if (isKnownNonPositive(Step)) 10008 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10009 10010 return None; 10011 } 10012 } 10013 10014 Optional<ScalarEvolution::LoopInvariantPredicate> 10015 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10016 const SCEV *LHS, const SCEV *RHS, 10017 const Loop *L) { 10018 10019 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10020 if (!isLoopInvariant(RHS, L)) { 10021 if (!isLoopInvariant(LHS, L)) 10022 return None; 10023 10024 std::swap(LHS, RHS); 10025 Pred = ICmpInst::getSwappedPredicate(Pred); 10026 } 10027 10028 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10029 if (!ArLHS || ArLHS->getLoop() != L) 10030 return None; 10031 10032 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10033 if (!MonotonicType) 10034 return None; 10035 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10036 // true as the loop iterates, and the backedge is control dependent on 10037 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10038 // 10039 // * if the predicate was false in the first iteration then the predicate 10040 // is never evaluated again, since the loop exits without taking the 10041 // backedge. 10042 // * if the predicate was true in the first iteration then it will 10043 // continue to be true for all future iterations since it is 10044 // monotonically increasing. 10045 // 10046 // For both the above possibilities, we can replace the loop varying 10047 // predicate with its value on the first iteration of the loop (which is 10048 // loop invariant). 10049 // 10050 // A similar reasoning applies for a monotonically decreasing predicate, by 10051 // replacing true with false and false with true in the above two bullets. 10052 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10053 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10054 10055 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10056 return None; 10057 10058 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10059 } 10060 10061 Optional<ScalarEvolution::LoopInvariantPredicate> 10062 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10063 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10064 const Instruction *CtxI, const SCEV *MaxIter) { 10065 // Try to prove the following set of facts: 10066 // - The predicate is monotonic in the iteration space. 10067 // - If the check does not fail on the 1st iteration: 10068 // - No overflow will happen during first MaxIter iterations; 10069 // - It will not fail on the MaxIter'th iteration. 10070 // If the check does fail on the 1st iteration, we leave the loop and no 10071 // other checks matter. 10072 10073 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10074 if (!isLoopInvariant(RHS, L)) { 10075 if (!isLoopInvariant(LHS, L)) 10076 return None; 10077 10078 std::swap(LHS, RHS); 10079 Pred = ICmpInst::getSwappedPredicate(Pred); 10080 } 10081 10082 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10083 if (!AR || AR->getLoop() != L) 10084 return None; 10085 10086 // The predicate must be relational (i.e. <, <=, >=, >). 10087 if (!ICmpInst::isRelational(Pred)) 10088 return None; 10089 10090 // TODO: Support steps other than +/- 1. 10091 const SCEV *Step = AR->getStepRecurrence(*this); 10092 auto *One = getOne(Step->getType()); 10093 auto *MinusOne = getNegativeSCEV(One); 10094 if (Step != One && Step != MinusOne) 10095 return None; 10096 10097 // Type mismatch here means that MaxIter is potentially larger than max 10098 // unsigned value in start type, which mean we cannot prove no wrap for the 10099 // indvar. 10100 if (AR->getType() != MaxIter->getType()) 10101 return None; 10102 10103 // Value of IV on suggested last iteration. 10104 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10105 // Does it still meet the requirement? 10106 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10107 return None; 10108 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10109 // not exceed max unsigned value of this type), this effectively proves 10110 // that there is no wrap during the iteration. To prove that there is no 10111 // signed/unsigned wrap, we need to check that 10112 // Start <= Last for step = 1 or Start >= Last for step = -1. 10113 ICmpInst::Predicate NoOverflowPred = 10114 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10115 if (Step == MinusOne) 10116 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10117 const SCEV *Start = AR->getStart(); 10118 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10119 return None; 10120 10121 // Everything is fine. 10122 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10123 } 10124 10125 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10126 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10127 if (HasSameValue(LHS, RHS)) 10128 return ICmpInst::isTrueWhenEqual(Pred); 10129 10130 // This code is split out from isKnownPredicate because it is called from 10131 // within isLoopEntryGuardedByCond. 10132 10133 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10134 const ConstantRange &RangeRHS) { 10135 return RangeLHS.icmp(Pred, RangeRHS); 10136 }; 10137 10138 // The check at the top of the function catches the case where the values are 10139 // known to be equal. 10140 if (Pred == CmpInst::ICMP_EQ) 10141 return false; 10142 10143 if (Pred == CmpInst::ICMP_NE) { 10144 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10145 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10146 return true; 10147 auto *Diff = getMinusSCEV(LHS, RHS); 10148 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10149 } 10150 10151 if (CmpInst::isSigned(Pred)) 10152 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10153 10154 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10155 } 10156 10157 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10158 const SCEV *LHS, 10159 const SCEV *RHS) { 10160 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10161 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10162 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10163 // OutC1 and OutC2. 10164 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10165 APInt &OutC1, APInt &OutC2, 10166 SCEV::NoWrapFlags ExpectedFlags) { 10167 const SCEV *XNonConstOp, *XConstOp; 10168 const SCEV *YNonConstOp, *YConstOp; 10169 SCEV::NoWrapFlags XFlagsPresent; 10170 SCEV::NoWrapFlags YFlagsPresent; 10171 10172 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10173 XConstOp = getZero(X->getType()); 10174 XNonConstOp = X; 10175 XFlagsPresent = ExpectedFlags; 10176 } 10177 if (!isa<SCEVConstant>(XConstOp) || 10178 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10179 return false; 10180 10181 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10182 YConstOp = getZero(Y->getType()); 10183 YNonConstOp = Y; 10184 YFlagsPresent = ExpectedFlags; 10185 } 10186 10187 if (!isa<SCEVConstant>(YConstOp) || 10188 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10189 return false; 10190 10191 if (YNonConstOp != XNonConstOp) 10192 return false; 10193 10194 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10195 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10196 10197 return true; 10198 }; 10199 10200 APInt C1; 10201 APInt C2; 10202 10203 switch (Pred) { 10204 default: 10205 break; 10206 10207 case ICmpInst::ICMP_SGE: 10208 std::swap(LHS, RHS); 10209 LLVM_FALLTHROUGH; 10210 case ICmpInst::ICMP_SLE: 10211 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10212 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10213 return true; 10214 10215 break; 10216 10217 case ICmpInst::ICMP_SGT: 10218 std::swap(LHS, RHS); 10219 LLVM_FALLTHROUGH; 10220 case ICmpInst::ICMP_SLT: 10221 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10222 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10223 return true; 10224 10225 break; 10226 10227 case ICmpInst::ICMP_UGE: 10228 std::swap(LHS, RHS); 10229 LLVM_FALLTHROUGH; 10230 case ICmpInst::ICMP_ULE: 10231 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10232 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10233 return true; 10234 10235 break; 10236 10237 case ICmpInst::ICMP_UGT: 10238 std::swap(LHS, RHS); 10239 LLVM_FALLTHROUGH; 10240 case ICmpInst::ICMP_ULT: 10241 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10242 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10243 return true; 10244 break; 10245 } 10246 10247 return false; 10248 } 10249 10250 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10251 const SCEV *LHS, 10252 const SCEV *RHS) { 10253 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10254 return false; 10255 10256 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10257 // the stack can result in exponential time complexity. 10258 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10259 10260 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10261 // 10262 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10263 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10264 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10265 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10266 // use isKnownPredicate later if needed. 10267 return isKnownNonNegative(RHS) && 10268 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10269 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10270 } 10271 10272 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10273 ICmpInst::Predicate Pred, 10274 const SCEV *LHS, const SCEV *RHS) { 10275 // No need to even try if we know the module has no guards. 10276 if (!HasGuards) 10277 return false; 10278 10279 return any_of(*BB, [&](const Instruction &I) { 10280 using namespace llvm::PatternMatch; 10281 10282 Value *Condition; 10283 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10284 m_Value(Condition))) && 10285 isImpliedCond(Pred, LHS, RHS, Condition, false); 10286 }); 10287 } 10288 10289 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10290 /// protected by a conditional between LHS and RHS. This is used to 10291 /// to eliminate casts. 10292 bool 10293 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10294 ICmpInst::Predicate Pred, 10295 const SCEV *LHS, const SCEV *RHS) { 10296 // Interpret a null as meaning no loop, where there is obviously no guard 10297 // (interprocedural conditions notwithstanding). 10298 if (!L) return true; 10299 10300 if (VerifyIR) 10301 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10302 "This cannot be done on broken IR!"); 10303 10304 10305 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10306 return true; 10307 10308 BasicBlock *Latch = L->getLoopLatch(); 10309 if (!Latch) 10310 return false; 10311 10312 BranchInst *LoopContinuePredicate = 10313 dyn_cast<BranchInst>(Latch->getTerminator()); 10314 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10315 isImpliedCond(Pred, LHS, RHS, 10316 LoopContinuePredicate->getCondition(), 10317 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10318 return true; 10319 10320 // We don't want more than one activation of the following loops on the stack 10321 // -- that can lead to O(n!) time complexity. 10322 if (WalkingBEDominatingConds) 10323 return false; 10324 10325 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10326 10327 // See if we can exploit a trip count to prove the predicate. 10328 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10329 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10330 if (LatchBECount != getCouldNotCompute()) { 10331 // We know that Latch branches back to the loop header exactly 10332 // LatchBECount times. This means the backdege condition at Latch is 10333 // equivalent to "{0,+,1} u< LatchBECount". 10334 Type *Ty = LatchBECount->getType(); 10335 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10336 const SCEV *LoopCounter = 10337 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10338 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10339 LatchBECount)) 10340 return true; 10341 } 10342 10343 // Check conditions due to any @llvm.assume intrinsics. 10344 for (auto &AssumeVH : AC.assumptions()) { 10345 if (!AssumeVH) 10346 continue; 10347 auto *CI = cast<CallInst>(AssumeVH); 10348 if (!DT.dominates(CI, Latch->getTerminator())) 10349 continue; 10350 10351 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10352 return true; 10353 } 10354 10355 // If the loop is not reachable from the entry block, we risk running into an 10356 // infinite loop as we walk up into the dom tree. These loops do not matter 10357 // anyway, so we just return a conservative answer when we see them. 10358 if (!DT.isReachableFromEntry(L->getHeader())) 10359 return false; 10360 10361 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10362 return true; 10363 10364 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10365 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10366 assert(DTN && "should reach the loop header before reaching the root!"); 10367 10368 BasicBlock *BB = DTN->getBlock(); 10369 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10370 return true; 10371 10372 BasicBlock *PBB = BB->getSinglePredecessor(); 10373 if (!PBB) 10374 continue; 10375 10376 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10377 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10378 continue; 10379 10380 Value *Condition = ContinuePredicate->getCondition(); 10381 10382 // If we have an edge `E` within the loop body that dominates the only 10383 // latch, the condition guarding `E` also guards the backedge. This 10384 // reasoning works only for loops with a single latch. 10385 10386 BasicBlockEdge DominatingEdge(PBB, BB); 10387 if (DominatingEdge.isSingleEdge()) { 10388 // We're constructively (and conservatively) enumerating edges within the 10389 // loop body that dominate the latch. The dominator tree better agree 10390 // with us on this: 10391 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10392 10393 if (isImpliedCond(Pred, LHS, RHS, Condition, 10394 BB != ContinuePredicate->getSuccessor(0))) 10395 return true; 10396 } 10397 } 10398 10399 return false; 10400 } 10401 10402 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10403 ICmpInst::Predicate Pred, 10404 const SCEV *LHS, 10405 const SCEV *RHS) { 10406 if (VerifyIR) 10407 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10408 "This cannot be done on broken IR!"); 10409 10410 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10411 // the facts (a >= b && a != b) separately. A typical situation is when the 10412 // non-strict comparison is known from ranges and non-equality is known from 10413 // dominating predicates. If we are proving strict comparison, we always try 10414 // to prove non-equality and non-strict comparison separately. 10415 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10416 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10417 bool ProvedNonStrictComparison = false; 10418 bool ProvedNonEquality = false; 10419 10420 auto SplitAndProve = 10421 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10422 if (!ProvedNonStrictComparison) 10423 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10424 if (!ProvedNonEquality) 10425 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10426 if (ProvedNonStrictComparison && ProvedNonEquality) 10427 return true; 10428 return false; 10429 }; 10430 10431 if (ProvingStrictComparison) { 10432 auto ProofFn = [&](ICmpInst::Predicate P) { 10433 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10434 }; 10435 if (SplitAndProve(ProofFn)) 10436 return true; 10437 } 10438 10439 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10440 auto ProveViaGuard = [&](const BasicBlock *Block) { 10441 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10442 return true; 10443 if (ProvingStrictComparison) { 10444 auto ProofFn = [&](ICmpInst::Predicate P) { 10445 return isImpliedViaGuard(Block, P, LHS, RHS); 10446 }; 10447 if (SplitAndProve(ProofFn)) 10448 return true; 10449 } 10450 return false; 10451 }; 10452 10453 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10454 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10455 const Instruction *CtxI = &BB->front(); 10456 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10457 return true; 10458 if (ProvingStrictComparison) { 10459 auto ProofFn = [&](ICmpInst::Predicate P) { 10460 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10461 }; 10462 if (SplitAndProve(ProofFn)) 10463 return true; 10464 } 10465 return false; 10466 }; 10467 10468 // Starting at the block's predecessor, climb up the predecessor chain, as long 10469 // as there are predecessors that can be found that have unique successors 10470 // leading to the original block. 10471 const Loop *ContainingLoop = LI.getLoopFor(BB); 10472 const BasicBlock *PredBB; 10473 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10474 PredBB = ContainingLoop->getLoopPredecessor(); 10475 else 10476 PredBB = BB->getSinglePredecessor(); 10477 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10478 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10479 if (ProveViaGuard(Pair.first)) 10480 return true; 10481 10482 const BranchInst *LoopEntryPredicate = 10483 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10484 if (!LoopEntryPredicate || 10485 LoopEntryPredicate->isUnconditional()) 10486 continue; 10487 10488 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10489 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10490 return true; 10491 } 10492 10493 // Check conditions due to any @llvm.assume intrinsics. 10494 for (auto &AssumeVH : AC.assumptions()) { 10495 if (!AssumeVH) 10496 continue; 10497 auto *CI = cast<CallInst>(AssumeVH); 10498 if (!DT.dominates(CI, BB)) 10499 continue; 10500 10501 if (ProveViaCond(CI->getArgOperand(0), false)) 10502 return true; 10503 } 10504 10505 return false; 10506 } 10507 10508 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10509 ICmpInst::Predicate Pred, 10510 const SCEV *LHS, 10511 const SCEV *RHS) { 10512 // Interpret a null as meaning no loop, where there is obviously no guard 10513 // (interprocedural conditions notwithstanding). 10514 if (!L) 10515 return false; 10516 10517 // Both LHS and RHS must be available at loop entry. 10518 assert(isAvailableAtLoopEntry(LHS, L) && 10519 "LHS is not available at Loop Entry"); 10520 assert(isAvailableAtLoopEntry(RHS, L) && 10521 "RHS is not available at Loop Entry"); 10522 10523 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10524 return true; 10525 10526 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10527 } 10528 10529 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10530 const SCEV *RHS, 10531 const Value *FoundCondValue, bool Inverse, 10532 const Instruction *CtxI) { 10533 // False conditions implies anything. Do not bother analyzing it further. 10534 if (FoundCondValue == 10535 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10536 return true; 10537 10538 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10539 return false; 10540 10541 auto ClearOnExit = 10542 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10543 10544 // Recursively handle And and Or conditions. 10545 const Value *Op0, *Op1; 10546 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10547 if (!Inverse) 10548 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10549 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10550 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10551 if (Inverse) 10552 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10553 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10554 } 10555 10556 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10557 if (!ICI) return false; 10558 10559 // Now that we found a conditional branch that dominates the loop or controls 10560 // the loop latch. Check to see if it is the comparison we are looking for. 10561 ICmpInst::Predicate FoundPred; 10562 if (Inverse) 10563 FoundPred = ICI->getInversePredicate(); 10564 else 10565 FoundPred = ICI->getPredicate(); 10566 10567 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10568 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10569 10570 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10571 } 10572 10573 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10574 const SCEV *RHS, 10575 ICmpInst::Predicate FoundPred, 10576 const SCEV *FoundLHS, const SCEV *FoundRHS, 10577 const Instruction *CtxI) { 10578 // Balance the types. 10579 if (getTypeSizeInBits(LHS->getType()) < 10580 getTypeSizeInBits(FoundLHS->getType())) { 10581 // For unsigned and equality predicates, try to prove that both found 10582 // operands fit into narrow unsigned range. If so, try to prove facts in 10583 // narrow types. 10584 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10585 auto *NarrowType = LHS->getType(); 10586 auto *WideType = FoundLHS->getType(); 10587 auto BitWidth = getTypeSizeInBits(NarrowType); 10588 const SCEV *MaxValue = getZeroExtendExpr( 10589 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10590 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10591 MaxValue) && 10592 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10593 MaxValue)) { 10594 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10595 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10596 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10597 TruncFoundRHS, CtxI)) 10598 return true; 10599 } 10600 } 10601 10602 if (LHS->getType()->isPointerTy()) 10603 return false; 10604 if (CmpInst::isSigned(Pred)) { 10605 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10606 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10607 } else { 10608 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10609 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10610 } 10611 } else if (getTypeSizeInBits(LHS->getType()) > 10612 getTypeSizeInBits(FoundLHS->getType())) { 10613 if (FoundLHS->getType()->isPointerTy()) 10614 return false; 10615 if (CmpInst::isSigned(FoundPred)) { 10616 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10617 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10618 } else { 10619 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10620 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10621 } 10622 } 10623 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10624 FoundRHS, CtxI); 10625 } 10626 10627 bool ScalarEvolution::isImpliedCondBalancedTypes( 10628 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10629 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10630 const Instruction *CtxI) { 10631 assert(getTypeSizeInBits(LHS->getType()) == 10632 getTypeSizeInBits(FoundLHS->getType()) && 10633 "Types should be balanced!"); 10634 // Canonicalize the query to match the way instcombine will have 10635 // canonicalized the comparison. 10636 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10637 if (LHS == RHS) 10638 return CmpInst::isTrueWhenEqual(Pred); 10639 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10640 if (FoundLHS == FoundRHS) 10641 return CmpInst::isFalseWhenEqual(FoundPred); 10642 10643 // Check to see if we can make the LHS or RHS match. 10644 if (LHS == FoundRHS || RHS == FoundLHS) { 10645 if (isa<SCEVConstant>(RHS)) { 10646 std::swap(FoundLHS, FoundRHS); 10647 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10648 } else { 10649 std::swap(LHS, RHS); 10650 Pred = ICmpInst::getSwappedPredicate(Pred); 10651 } 10652 } 10653 10654 // Check whether the found predicate is the same as the desired predicate. 10655 if (FoundPred == Pred) 10656 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10657 10658 // Check whether swapping the found predicate makes it the same as the 10659 // desired predicate. 10660 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10661 // We can write the implication 10662 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10663 // using one of the following ways: 10664 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10665 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10666 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10667 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10668 // Forms 1. and 2. require swapping the operands of one condition. Don't 10669 // do this if it would break canonical constant/addrec ordering. 10670 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10671 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10672 CtxI); 10673 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10674 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 10675 10676 // There's no clear preference between forms 3. and 4., try both. Avoid 10677 // forming getNotSCEV of pointer values as the resulting subtract is 10678 // not legal. 10679 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 10680 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10681 FoundLHS, FoundRHS, CtxI)) 10682 return true; 10683 10684 if (!FoundLHS->getType()->isPointerTy() && 10685 !FoundRHS->getType()->isPointerTy() && 10686 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10687 getNotSCEV(FoundRHS), CtxI)) 10688 return true; 10689 10690 return false; 10691 } 10692 10693 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 10694 CmpInst::Predicate P2) { 10695 assert(P1 != P2 && "Handled earlier!"); 10696 return CmpInst::isRelational(P2) && 10697 P1 == CmpInst::getFlippedSignednessPredicate(P2); 10698 }; 10699 if (IsSignFlippedPredicate(Pred, FoundPred)) { 10700 // Unsigned comparison is the same as signed comparison when both the 10701 // operands are non-negative or negative. 10702 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 10703 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 10704 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10705 // Create local copies that we can freely swap and canonicalize our 10706 // conditions to "le/lt". 10707 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 10708 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 10709 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 10710 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 10711 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 10712 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 10713 std::swap(CanonicalLHS, CanonicalRHS); 10714 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 10715 } 10716 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 10717 "Must be!"); 10718 assert((ICmpInst::isLT(CanonicalFoundPred) || 10719 ICmpInst::isLE(CanonicalFoundPred)) && 10720 "Must be!"); 10721 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 10722 // Use implication: 10723 // x <u y && y >=s 0 --> x <s y. 10724 // If we can prove the left part, the right part is also proven. 10725 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10726 CanonicalRHS, CanonicalFoundLHS, 10727 CanonicalFoundRHS); 10728 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 10729 // Use implication: 10730 // x <s y && y <s 0 --> x <u y. 10731 // If we can prove the left part, the right part is also proven. 10732 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10733 CanonicalRHS, CanonicalFoundLHS, 10734 CanonicalFoundRHS); 10735 } 10736 10737 // Check if we can make progress by sharpening ranges. 10738 if (FoundPred == ICmpInst::ICMP_NE && 10739 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10740 10741 const SCEVConstant *C = nullptr; 10742 const SCEV *V = nullptr; 10743 10744 if (isa<SCEVConstant>(FoundLHS)) { 10745 C = cast<SCEVConstant>(FoundLHS); 10746 V = FoundRHS; 10747 } else { 10748 C = cast<SCEVConstant>(FoundRHS); 10749 V = FoundLHS; 10750 } 10751 10752 // The guarding predicate tells us that C != V. If the known range 10753 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10754 // range we consider has to correspond to same signedness as the 10755 // predicate we're interested in folding. 10756 10757 APInt Min = ICmpInst::isSigned(Pred) ? 10758 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10759 10760 if (Min == C->getAPInt()) { 10761 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10762 // This is true even if (Min + 1) wraps around -- in case of 10763 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10764 10765 APInt SharperMin = Min + 1; 10766 10767 switch (Pred) { 10768 case ICmpInst::ICMP_SGE: 10769 case ICmpInst::ICMP_UGE: 10770 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10771 // RHS, we're done. 10772 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10773 CtxI)) 10774 return true; 10775 LLVM_FALLTHROUGH; 10776 10777 case ICmpInst::ICMP_SGT: 10778 case ICmpInst::ICMP_UGT: 10779 // We know from the range information that (V `Pred` Min || 10780 // V == Min). We know from the guarding condition that !(V 10781 // == Min). This gives us 10782 // 10783 // V `Pred` Min || V == Min && !(V == Min) 10784 // => V `Pred` Min 10785 // 10786 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10787 10788 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 10789 return true; 10790 break; 10791 10792 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10793 case ICmpInst::ICMP_SLE: 10794 case ICmpInst::ICMP_ULE: 10795 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10796 LHS, V, getConstant(SharperMin), CtxI)) 10797 return true; 10798 LLVM_FALLTHROUGH; 10799 10800 case ICmpInst::ICMP_SLT: 10801 case ICmpInst::ICMP_ULT: 10802 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10803 LHS, V, getConstant(Min), CtxI)) 10804 return true; 10805 break; 10806 10807 default: 10808 // No change 10809 break; 10810 } 10811 } 10812 } 10813 10814 // Check whether the actual condition is beyond sufficient. 10815 if (FoundPred == ICmpInst::ICMP_EQ) 10816 if (ICmpInst::isTrueWhenEqual(Pred)) 10817 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10818 return true; 10819 if (Pred == ICmpInst::ICMP_NE) 10820 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10821 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10822 return true; 10823 10824 // Otherwise assume the worst. 10825 return false; 10826 } 10827 10828 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10829 const SCEV *&L, const SCEV *&R, 10830 SCEV::NoWrapFlags &Flags) { 10831 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10832 if (!AE || AE->getNumOperands() != 2) 10833 return false; 10834 10835 L = AE->getOperand(0); 10836 R = AE->getOperand(1); 10837 Flags = AE->getNoWrapFlags(); 10838 return true; 10839 } 10840 10841 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10842 const SCEV *Less) { 10843 // We avoid subtracting expressions here because this function is usually 10844 // fairly deep in the call stack (i.e. is called many times). 10845 10846 // X - X = 0. 10847 if (More == Less) 10848 return APInt(getTypeSizeInBits(More->getType()), 0); 10849 10850 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10851 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10852 const auto *MAR = cast<SCEVAddRecExpr>(More); 10853 10854 if (LAR->getLoop() != MAR->getLoop()) 10855 return None; 10856 10857 // We look at affine expressions only; not for correctness but to keep 10858 // getStepRecurrence cheap. 10859 if (!LAR->isAffine() || !MAR->isAffine()) 10860 return None; 10861 10862 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10863 return None; 10864 10865 Less = LAR->getStart(); 10866 More = MAR->getStart(); 10867 10868 // fall through 10869 } 10870 10871 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10872 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10873 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10874 return M - L; 10875 } 10876 10877 SCEV::NoWrapFlags Flags; 10878 const SCEV *LLess = nullptr, *RLess = nullptr; 10879 const SCEV *LMore = nullptr, *RMore = nullptr; 10880 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10881 // Compare (X + C1) vs X. 10882 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10883 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10884 if (RLess == More) 10885 return -(C1->getAPInt()); 10886 10887 // Compare X vs (X + C2). 10888 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10889 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10890 if (RMore == Less) 10891 return C2->getAPInt(); 10892 10893 // Compare (X + C1) vs (X + C2). 10894 if (C1 && C2 && RLess == RMore) 10895 return C2->getAPInt() - C1->getAPInt(); 10896 10897 return None; 10898 } 10899 10900 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10901 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10902 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 10903 // Try to recognize the following pattern: 10904 // 10905 // FoundRHS = ... 10906 // ... 10907 // loop: 10908 // FoundLHS = {Start,+,W} 10909 // context_bb: // Basic block from the same loop 10910 // known(Pred, FoundLHS, FoundRHS) 10911 // 10912 // If some predicate is known in the context of a loop, it is also known on 10913 // each iteration of this loop, including the first iteration. Therefore, in 10914 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10915 // prove the original pred using this fact. 10916 if (!CtxI) 10917 return false; 10918 const BasicBlock *ContextBB = CtxI->getParent(); 10919 // Make sure AR varies in the context block. 10920 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10921 const Loop *L = AR->getLoop(); 10922 // Make sure that context belongs to the loop and executes on 1st iteration 10923 // (if it ever executes at all). 10924 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10925 return false; 10926 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10927 return false; 10928 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10929 } 10930 10931 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10932 const Loop *L = AR->getLoop(); 10933 // Make sure that context belongs to the loop and executes on 1st iteration 10934 // (if it ever executes at all). 10935 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10936 return false; 10937 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10938 return false; 10939 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10940 } 10941 10942 return false; 10943 } 10944 10945 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10946 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10947 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10948 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10949 return false; 10950 10951 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10952 if (!AddRecLHS) 10953 return false; 10954 10955 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10956 if (!AddRecFoundLHS) 10957 return false; 10958 10959 // We'd like to let SCEV reason about control dependencies, so we constrain 10960 // both the inequalities to be about add recurrences on the same loop. This 10961 // way we can use isLoopEntryGuardedByCond later. 10962 10963 const Loop *L = AddRecFoundLHS->getLoop(); 10964 if (L != AddRecLHS->getLoop()) 10965 return false; 10966 10967 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10968 // 10969 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10970 // ... (2) 10971 // 10972 // Informal proof for (2), assuming (1) [*]: 10973 // 10974 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10975 // 10976 // Then 10977 // 10978 // FoundLHS s< FoundRHS s< INT_MIN - C 10979 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10980 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10981 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10982 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10983 // <=> FoundLHS + C s< FoundRHS + C 10984 // 10985 // [*]: (1) can be proved by ruling out overflow. 10986 // 10987 // [**]: This can be proved by analyzing all the four possibilities: 10988 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10989 // (A s>= 0, B s>= 0). 10990 // 10991 // Note: 10992 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10993 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10994 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10995 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10996 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10997 // C)". 10998 10999 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11000 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11001 if (!LDiff || !RDiff || *LDiff != *RDiff) 11002 return false; 11003 11004 if (LDiff->isMinValue()) 11005 return true; 11006 11007 APInt FoundRHSLimit; 11008 11009 if (Pred == CmpInst::ICMP_ULT) { 11010 FoundRHSLimit = -(*RDiff); 11011 } else { 11012 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11013 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11014 } 11015 11016 // Try to prove (1) or (2), as needed. 11017 return isAvailableAtLoopEntry(FoundRHS, L) && 11018 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11019 getConstant(FoundRHSLimit)); 11020 } 11021 11022 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11023 const SCEV *LHS, const SCEV *RHS, 11024 const SCEV *FoundLHS, 11025 const SCEV *FoundRHS, unsigned Depth) { 11026 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11027 11028 auto ClearOnExit = make_scope_exit([&]() { 11029 if (LPhi) { 11030 bool Erased = PendingMerges.erase(LPhi); 11031 assert(Erased && "Failed to erase LPhi!"); 11032 (void)Erased; 11033 } 11034 if (RPhi) { 11035 bool Erased = PendingMerges.erase(RPhi); 11036 assert(Erased && "Failed to erase RPhi!"); 11037 (void)Erased; 11038 } 11039 }); 11040 11041 // Find respective Phis and check that they are not being pending. 11042 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11043 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11044 if (!PendingMerges.insert(Phi).second) 11045 return false; 11046 LPhi = Phi; 11047 } 11048 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11049 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11050 // If we detect a loop of Phi nodes being processed by this method, for 11051 // example: 11052 // 11053 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11054 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11055 // 11056 // we don't want to deal with a case that complex, so return conservative 11057 // answer false. 11058 if (!PendingMerges.insert(Phi).second) 11059 return false; 11060 RPhi = Phi; 11061 } 11062 11063 // If none of LHS, RHS is a Phi, nothing to do here. 11064 if (!LPhi && !RPhi) 11065 return false; 11066 11067 // If there is a SCEVUnknown Phi we are interested in, make it left. 11068 if (!LPhi) { 11069 std::swap(LHS, RHS); 11070 std::swap(FoundLHS, FoundRHS); 11071 std::swap(LPhi, RPhi); 11072 Pred = ICmpInst::getSwappedPredicate(Pred); 11073 } 11074 11075 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11076 const BasicBlock *LBB = LPhi->getParent(); 11077 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11078 11079 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11080 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11081 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11082 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11083 }; 11084 11085 if (RPhi && RPhi->getParent() == LBB) { 11086 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11087 // If we compare two Phis from the same block, and for each entry block 11088 // the predicate is true for incoming values from this block, then the 11089 // predicate is also true for the Phis. 11090 for (const BasicBlock *IncBB : predecessors(LBB)) { 11091 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11092 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11093 if (!ProvedEasily(L, R)) 11094 return false; 11095 } 11096 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11097 // Case two: RHS is also a Phi from the same basic block, and it is an 11098 // AddRec. It means that there is a loop which has both AddRec and Unknown 11099 // PHIs, for it we can compare incoming values of AddRec from above the loop 11100 // and latch with their respective incoming values of LPhi. 11101 // TODO: Generalize to handle loops with many inputs in a header. 11102 if (LPhi->getNumIncomingValues() != 2) return false; 11103 11104 auto *RLoop = RAR->getLoop(); 11105 auto *Predecessor = RLoop->getLoopPredecessor(); 11106 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11107 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11108 if (!ProvedEasily(L1, RAR->getStart())) 11109 return false; 11110 auto *Latch = RLoop->getLoopLatch(); 11111 assert(Latch && "Loop with AddRec with no latch?"); 11112 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11113 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11114 return false; 11115 } else { 11116 // In all other cases go over inputs of LHS and compare each of them to RHS, 11117 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11118 // At this point RHS is either a non-Phi, or it is a Phi from some block 11119 // different from LBB. 11120 for (const BasicBlock *IncBB : predecessors(LBB)) { 11121 // Check that RHS is available in this block. 11122 if (!dominates(RHS, IncBB)) 11123 return false; 11124 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11125 // Make sure L does not refer to a value from a potentially previous 11126 // iteration of a loop. 11127 if (!properlyDominates(L, IncBB)) 11128 return false; 11129 if (!ProvedEasily(L, RHS)) 11130 return false; 11131 } 11132 } 11133 return true; 11134 } 11135 11136 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11137 const SCEV *LHS, const SCEV *RHS, 11138 const SCEV *FoundLHS, 11139 const SCEV *FoundRHS, 11140 const Instruction *CtxI) { 11141 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11142 return true; 11143 11144 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11145 return true; 11146 11147 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11148 CtxI)) 11149 return true; 11150 11151 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11152 FoundLHS, FoundRHS); 11153 } 11154 11155 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11156 template <typename MinMaxExprType> 11157 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11158 const SCEV *Candidate) { 11159 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11160 if (!MinMaxExpr) 11161 return false; 11162 11163 return is_contained(MinMaxExpr->operands(), Candidate); 11164 } 11165 11166 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11167 ICmpInst::Predicate Pred, 11168 const SCEV *LHS, const SCEV *RHS) { 11169 // If both sides are affine addrecs for the same loop, with equal 11170 // steps, and we know the recurrences don't wrap, then we only 11171 // need to check the predicate on the starting values. 11172 11173 if (!ICmpInst::isRelational(Pred)) 11174 return false; 11175 11176 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11177 if (!LAR) 11178 return false; 11179 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11180 if (!RAR) 11181 return false; 11182 if (LAR->getLoop() != RAR->getLoop()) 11183 return false; 11184 if (!LAR->isAffine() || !RAR->isAffine()) 11185 return false; 11186 11187 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11188 return false; 11189 11190 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11191 SCEV::FlagNSW : SCEV::FlagNUW; 11192 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11193 return false; 11194 11195 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11196 } 11197 11198 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11199 /// expression? 11200 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11201 ICmpInst::Predicate Pred, 11202 const SCEV *LHS, const SCEV *RHS) { 11203 switch (Pred) { 11204 default: 11205 return false; 11206 11207 case ICmpInst::ICMP_SGE: 11208 std::swap(LHS, RHS); 11209 LLVM_FALLTHROUGH; 11210 case ICmpInst::ICMP_SLE: 11211 return 11212 // min(A, ...) <= A 11213 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11214 // A <= max(A, ...) 11215 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11216 11217 case ICmpInst::ICMP_UGE: 11218 std::swap(LHS, RHS); 11219 LLVM_FALLTHROUGH; 11220 case ICmpInst::ICMP_ULE: 11221 return 11222 // min(A, ...) <= A 11223 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11224 // A <= max(A, ...) 11225 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11226 } 11227 11228 llvm_unreachable("covered switch fell through?!"); 11229 } 11230 11231 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11232 const SCEV *LHS, const SCEV *RHS, 11233 const SCEV *FoundLHS, 11234 const SCEV *FoundRHS, 11235 unsigned Depth) { 11236 assert(getTypeSizeInBits(LHS->getType()) == 11237 getTypeSizeInBits(RHS->getType()) && 11238 "LHS and RHS have different sizes?"); 11239 assert(getTypeSizeInBits(FoundLHS->getType()) == 11240 getTypeSizeInBits(FoundRHS->getType()) && 11241 "FoundLHS and FoundRHS have different sizes?"); 11242 // We want to avoid hurting the compile time with analysis of too big trees. 11243 if (Depth > MaxSCEVOperationsImplicationDepth) 11244 return false; 11245 11246 // We only want to work with GT comparison so far. 11247 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11248 Pred = CmpInst::getSwappedPredicate(Pred); 11249 std::swap(LHS, RHS); 11250 std::swap(FoundLHS, FoundRHS); 11251 } 11252 11253 // For unsigned, try to reduce it to corresponding signed comparison. 11254 if (Pred == ICmpInst::ICMP_UGT) 11255 // We can replace unsigned predicate with its signed counterpart if all 11256 // involved values are non-negative. 11257 // TODO: We could have better support for unsigned. 11258 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11259 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11260 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11261 // use this fact to prove that LHS and RHS are non-negative. 11262 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11263 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11264 FoundRHS) && 11265 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11266 FoundRHS)) 11267 Pred = ICmpInst::ICMP_SGT; 11268 } 11269 11270 if (Pred != ICmpInst::ICMP_SGT) 11271 return false; 11272 11273 auto GetOpFromSExt = [&](const SCEV *S) { 11274 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11275 return Ext->getOperand(); 11276 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11277 // the constant in some cases. 11278 return S; 11279 }; 11280 11281 // Acquire values from extensions. 11282 auto *OrigLHS = LHS; 11283 auto *OrigFoundLHS = FoundLHS; 11284 LHS = GetOpFromSExt(LHS); 11285 FoundLHS = GetOpFromSExt(FoundLHS); 11286 11287 // Is the SGT predicate can be proved trivially or using the found context. 11288 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11289 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11290 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11291 FoundRHS, Depth + 1); 11292 }; 11293 11294 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11295 // We want to avoid creation of any new non-constant SCEV. Since we are 11296 // going to compare the operands to RHS, we should be certain that we don't 11297 // need any size extensions for this. So let's decline all cases when the 11298 // sizes of types of LHS and RHS do not match. 11299 // TODO: Maybe try to get RHS from sext to catch more cases? 11300 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11301 return false; 11302 11303 // Should not overflow. 11304 if (!LHSAddExpr->hasNoSignedWrap()) 11305 return false; 11306 11307 auto *LL = LHSAddExpr->getOperand(0); 11308 auto *LR = LHSAddExpr->getOperand(1); 11309 auto *MinusOne = getMinusOne(RHS->getType()); 11310 11311 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11312 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11313 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11314 }; 11315 // Try to prove the following rule: 11316 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11317 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11318 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11319 return true; 11320 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11321 Value *LL, *LR; 11322 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11323 11324 using namespace llvm::PatternMatch; 11325 11326 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11327 // Rules for division. 11328 // We are going to perform some comparisons with Denominator and its 11329 // derivative expressions. In general case, creating a SCEV for it may 11330 // lead to a complex analysis of the entire graph, and in particular it 11331 // can request trip count recalculation for the same loop. This would 11332 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11333 // this, we only want to create SCEVs that are constants in this section. 11334 // So we bail if Denominator is not a constant. 11335 if (!isa<ConstantInt>(LR)) 11336 return false; 11337 11338 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11339 11340 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11341 // then a SCEV for the numerator already exists and matches with FoundLHS. 11342 auto *Numerator = getExistingSCEV(LL); 11343 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11344 return false; 11345 11346 // Make sure that the numerator matches with FoundLHS and the denominator 11347 // is positive. 11348 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11349 return false; 11350 11351 auto *DTy = Denominator->getType(); 11352 auto *FRHSTy = FoundRHS->getType(); 11353 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11354 // One of types is a pointer and another one is not. We cannot extend 11355 // them properly to a wider type, so let us just reject this case. 11356 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11357 // to avoid this check. 11358 return false; 11359 11360 // Given that: 11361 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11362 auto *WTy = getWiderType(DTy, FRHSTy); 11363 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11364 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11365 11366 // Try to prove the following rule: 11367 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11368 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11369 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11370 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11371 if (isKnownNonPositive(RHS) && 11372 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11373 return true; 11374 11375 // Try to prove the following rule: 11376 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11377 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11378 // If we divide it by Denominator > 2, then: 11379 // 1. If FoundLHS is negative, then the result is 0. 11380 // 2. If FoundLHS is non-negative, then the result is non-negative. 11381 // Anyways, the result is non-negative. 11382 auto *MinusOne = getMinusOne(WTy); 11383 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11384 if (isKnownNegative(RHS) && 11385 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11386 return true; 11387 } 11388 } 11389 11390 // If our expression contained SCEVUnknown Phis, and we split it down and now 11391 // need to prove something for them, try to prove the predicate for every 11392 // possible incoming values of those Phis. 11393 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11394 return true; 11395 11396 return false; 11397 } 11398 11399 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11400 const SCEV *LHS, const SCEV *RHS) { 11401 // zext x u<= sext x, sext x s<= zext x 11402 switch (Pred) { 11403 case ICmpInst::ICMP_SGE: 11404 std::swap(LHS, RHS); 11405 LLVM_FALLTHROUGH; 11406 case ICmpInst::ICMP_SLE: { 11407 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11408 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11409 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11410 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11411 return true; 11412 break; 11413 } 11414 case ICmpInst::ICMP_UGE: 11415 std::swap(LHS, RHS); 11416 LLVM_FALLTHROUGH; 11417 case ICmpInst::ICMP_ULE: { 11418 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11419 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11420 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11421 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11422 return true; 11423 break; 11424 } 11425 default: 11426 break; 11427 }; 11428 return false; 11429 } 11430 11431 bool 11432 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11433 const SCEV *LHS, const SCEV *RHS) { 11434 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11435 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11436 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11437 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11438 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11439 } 11440 11441 bool 11442 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11443 const SCEV *LHS, const SCEV *RHS, 11444 const SCEV *FoundLHS, 11445 const SCEV *FoundRHS) { 11446 switch (Pred) { 11447 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11448 case ICmpInst::ICMP_EQ: 11449 case ICmpInst::ICMP_NE: 11450 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11451 return true; 11452 break; 11453 case ICmpInst::ICMP_SLT: 11454 case ICmpInst::ICMP_SLE: 11455 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11456 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11457 return true; 11458 break; 11459 case ICmpInst::ICMP_SGT: 11460 case ICmpInst::ICMP_SGE: 11461 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11462 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11463 return true; 11464 break; 11465 case ICmpInst::ICMP_ULT: 11466 case ICmpInst::ICMP_ULE: 11467 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11468 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11469 return true; 11470 break; 11471 case ICmpInst::ICMP_UGT: 11472 case ICmpInst::ICMP_UGE: 11473 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11474 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11475 return true; 11476 break; 11477 } 11478 11479 // Maybe it can be proved via operations? 11480 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11481 return true; 11482 11483 return false; 11484 } 11485 11486 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11487 const SCEV *LHS, 11488 const SCEV *RHS, 11489 const SCEV *FoundLHS, 11490 const SCEV *FoundRHS) { 11491 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11492 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11493 // reduce the compile time impact of this optimization. 11494 return false; 11495 11496 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11497 if (!Addend) 11498 return false; 11499 11500 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11501 11502 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11503 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11504 ConstantRange FoundLHSRange = 11505 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11506 11507 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11508 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11509 11510 // We can also compute the range of values for `LHS` that satisfy the 11511 // consequent, "`LHS` `Pred` `RHS`": 11512 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11513 // The antecedent implies the consequent if every value of `LHS` that 11514 // satisfies the antecedent also satisfies the consequent. 11515 return LHSRange.icmp(Pred, ConstRHS); 11516 } 11517 11518 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11519 bool IsSigned) { 11520 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11521 11522 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11523 const SCEV *One = getOne(Stride->getType()); 11524 11525 if (IsSigned) { 11526 APInt MaxRHS = getSignedRangeMax(RHS); 11527 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11528 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11529 11530 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11531 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11532 } 11533 11534 APInt MaxRHS = getUnsignedRangeMax(RHS); 11535 APInt MaxValue = APInt::getMaxValue(BitWidth); 11536 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11537 11538 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11539 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11540 } 11541 11542 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11543 bool IsSigned) { 11544 11545 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11546 const SCEV *One = getOne(Stride->getType()); 11547 11548 if (IsSigned) { 11549 APInt MinRHS = getSignedRangeMin(RHS); 11550 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11551 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11552 11553 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11554 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11555 } 11556 11557 APInt MinRHS = getUnsignedRangeMin(RHS); 11558 APInt MinValue = APInt::getMinValue(BitWidth); 11559 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11560 11561 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11562 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11563 } 11564 11565 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11566 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11567 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11568 // expression fixes the case of N=0. 11569 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11570 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11571 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11572 } 11573 11574 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11575 const SCEV *Stride, 11576 const SCEV *End, 11577 unsigned BitWidth, 11578 bool IsSigned) { 11579 // The logic in this function assumes we can represent a positive stride. 11580 // If we can't, the backedge-taken count must be zero. 11581 if (IsSigned && BitWidth == 1) 11582 return getZero(Stride->getType()); 11583 11584 // This code has only been closely audited for negative strides in the 11585 // unsigned comparison case, it may be correct for signed comparison, but 11586 // that needs to be established. 11587 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11588 "Stride is expected strictly positive for signed case!"); 11589 11590 // Calculate the maximum backedge count based on the range of values 11591 // permitted by Start, End, and Stride. 11592 APInt MinStart = 11593 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11594 11595 APInt MinStride = 11596 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11597 11598 // We assume either the stride is positive, or the backedge-taken count 11599 // is zero. So force StrideForMaxBECount to be at least one. 11600 APInt One(BitWidth, 1); 11601 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11602 : APIntOps::umax(One, MinStride); 11603 11604 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11605 : APInt::getMaxValue(BitWidth); 11606 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11607 11608 // Although End can be a MAX expression we estimate MaxEnd considering only 11609 // the case End = RHS of the loop termination condition. This is safe because 11610 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11611 // taken count. 11612 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11613 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11614 11615 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11616 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11617 : APIntOps::umax(MaxEnd, MinStart); 11618 11619 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11620 getConstant(StrideForMaxBECount) /* Step */); 11621 } 11622 11623 ScalarEvolution::ExitLimit 11624 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11625 const Loop *L, bool IsSigned, 11626 bool ControlsExit, bool AllowPredicates) { 11627 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11628 11629 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11630 bool PredicatedIV = false; 11631 11632 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11633 // Can we prove this loop *must* be UB if overflow of IV occurs? 11634 // Reasoning goes as follows: 11635 // * Suppose the IV did self wrap. 11636 // * If Stride evenly divides the iteration space, then once wrap 11637 // occurs, the loop must revisit the same values. 11638 // * We know that RHS is invariant, and that none of those values 11639 // caused this exit to be taken previously. Thus, this exit is 11640 // dynamically dead. 11641 // * If this is the sole exit, then a dead exit implies the loop 11642 // must be infinite if there are no abnormal exits. 11643 // * If the loop were infinite, then it must either not be mustprogress 11644 // or have side effects. Otherwise, it must be UB. 11645 // * It can't (by assumption), be UB so we have contradicted our 11646 // premise and can conclude the IV did not in fact self-wrap. 11647 if (!isLoopInvariant(RHS, L)) 11648 return false; 11649 11650 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11651 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11652 return false; 11653 11654 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11655 return false; 11656 11657 return loopIsFiniteByAssumption(L); 11658 }; 11659 11660 if (!IV) { 11661 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11662 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11663 if (AR && AR->getLoop() == L && AR->isAffine()) { 11664 auto Flags = AR->getNoWrapFlags(); 11665 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11666 Flags = setFlags(Flags, SCEV::FlagNW); 11667 11668 SmallVector<const SCEV*> Operands{AR->operands()}; 11669 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11670 11671 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11672 } 11673 if (AR->hasNoUnsignedWrap()) { 11674 // Emulate what getZeroExtendExpr would have done during construction 11675 // if we'd been able to infer the fact just above at that time. 11676 const SCEV *Step = AR->getStepRecurrence(*this); 11677 Type *Ty = ZExt->getType(); 11678 auto *S = getAddRecExpr( 11679 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11680 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11681 IV = dyn_cast<SCEVAddRecExpr>(S); 11682 } 11683 } 11684 } 11685 } 11686 11687 11688 if (!IV && AllowPredicates) { 11689 // Try to make this an AddRec using runtime tests, in the first X 11690 // iterations of this loop, where X is the SCEV expression found by the 11691 // algorithm below. 11692 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11693 PredicatedIV = true; 11694 } 11695 11696 // Avoid weird loops 11697 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11698 return getCouldNotCompute(); 11699 11700 // A precondition of this method is that the condition being analyzed 11701 // reaches an exiting branch which dominates the latch. Given that, we can 11702 // assume that an increment which violates the nowrap specification and 11703 // produces poison must cause undefined behavior when the resulting poison 11704 // value is branched upon and thus we can conclude that the backedge is 11705 // taken no more often than would be required to produce that poison value. 11706 // Note that a well defined loop can exit on the iteration which violates 11707 // the nowrap specification if there is another exit (either explicit or 11708 // implicit/exceptional) which causes the loop to execute before the 11709 // exiting instruction we're analyzing would trigger UB. 11710 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11711 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11712 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11713 11714 const SCEV *Stride = IV->getStepRecurrence(*this); 11715 11716 bool PositiveStride = isKnownPositive(Stride); 11717 11718 // Avoid negative or zero stride values. 11719 if (!PositiveStride) { 11720 // We can compute the correct backedge taken count for loops with unknown 11721 // strides if we can prove that the loop is not an infinite loop with side 11722 // effects. Here's the loop structure we are trying to handle - 11723 // 11724 // i = start 11725 // do { 11726 // A[i] = i; 11727 // i += s; 11728 // } while (i < end); 11729 // 11730 // The backedge taken count for such loops is evaluated as - 11731 // (max(end, start + stride) - start - 1) /u stride 11732 // 11733 // The additional preconditions that we need to check to prove correctness 11734 // of the above formula is as follows - 11735 // 11736 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11737 // NoWrap flag). 11738 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11739 // no side effects within the loop) 11740 // c) loop has a single static exit (with no abnormal exits) 11741 // 11742 // Precondition a) implies that if the stride is negative, this is a single 11743 // trip loop. The backedge taken count formula reduces to zero in this case. 11744 // 11745 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11746 // then a zero stride means the backedge can't be taken without executing 11747 // undefined behavior. 11748 // 11749 // The positive stride case is the same as isKnownPositive(Stride) returning 11750 // true (original behavior of the function). 11751 // 11752 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 11753 !loopHasNoAbnormalExits(L)) 11754 return getCouldNotCompute(); 11755 11756 // This bailout is protecting the logic in computeMaxBECountForLT which 11757 // has not yet been sufficiently auditted or tested with negative strides. 11758 // We used to filter out all known-non-positive cases here, we're in the 11759 // process of being less restrictive bit by bit. 11760 if (IsSigned && isKnownNonPositive(Stride)) 11761 return getCouldNotCompute(); 11762 11763 if (!isKnownNonZero(Stride)) { 11764 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11765 // if it might eventually be greater than start and if so, on which 11766 // iteration. We can't even produce a useful upper bound. 11767 if (!isLoopInvariant(RHS, L)) 11768 return getCouldNotCompute(); 11769 11770 // We allow a potentially zero stride, but we need to divide by stride 11771 // below. Since the loop can't be infinite and this check must control 11772 // the sole exit, we can infer the exit must be taken on the first 11773 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11774 // we know the numerator in the divides below must be zero, so we can 11775 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11776 // and produce the right result. 11777 // FIXME: Handle the case where Stride is poison? 11778 auto wouldZeroStrideBeUB = [&]() { 11779 // Proof by contradiction. Suppose the stride were zero. If we can 11780 // prove that the backedge *is* taken on the first iteration, then since 11781 // we know this condition controls the sole exit, we must have an 11782 // infinite loop. We can't have a (well defined) infinite loop per 11783 // check just above. 11784 // Note: The (Start - Stride) term is used to get the start' term from 11785 // (start' + stride,+,stride). Remember that we only care about the 11786 // result of this expression when stride == 0 at runtime. 11787 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11788 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11789 }; 11790 if (!wouldZeroStrideBeUB()) { 11791 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11792 } 11793 } 11794 } else if (!Stride->isOne() && !NoWrap) { 11795 auto isUBOnWrap = [&]() { 11796 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11797 // follows trivially from the fact that every (un)signed-wrapped, but 11798 // not self-wrapped value must be LT than the last value before 11799 // (un)signed wrap. Since we know that last value didn't exit, nor 11800 // will any smaller one. 11801 return canAssumeNoSelfWrap(IV); 11802 }; 11803 11804 // Avoid proven overflow cases: this will ensure that the backedge taken 11805 // count will not generate any unsigned overflow. Relaxed no-overflow 11806 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11807 // undefined behaviors like the case of C language. 11808 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11809 return getCouldNotCompute(); 11810 } 11811 11812 // On all paths just preceeding, we established the following invariant: 11813 // IV can be assumed not to overflow up to and including the exiting 11814 // iteration. We proved this in one of two ways: 11815 // 1) We can show overflow doesn't occur before the exiting iteration 11816 // 1a) canIVOverflowOnLT, and b) step of one 11817 // 2) We can show that if overflow occurs, the loop must execute UB 11818 // before any possible exit. 11819 // Note that we have not yet proved RHS invariant (in general). 11820 11821 const SCEV *Start = IV->getStart(); 11822 11823 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11824 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 11825 // Use integer-typed versions for actual computation; we can't subtract 11826 // pointers in general. 11827 const SCEV *OrigStart = Start; 11828 const SCEV *OrigRHS = RHS; 11829 if (Start->getType()->isPointerTy()) { 11830 Start = getLosslessPtrToIntExpr(Start); 11831 if (isa<SCEVCouldNotCompute>(Start)) 11832 return Start; 11833 } 11834 if (RHS->getType()->isPointerTy()) { 11835 RHS = getLosslessPtrToIntExpr(RHS); 11836 if (isa<SCEVCouldNotCompute>(RHS)) 11837 return RHS; 11838 } 11839 11840 // When the RHS is not invariant, we do not know the end bound of the loop and 11841 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11842 // calculate the MaxBECount, given the start, stride and max value for the end 11843 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11844 // checked above). 11845 if (!isLoopInvariant(RHS, L)) { 11846 const SCEV *MaxBECount = computeMaxBECountForLT( 11847 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11848 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11849 false /*MaxOrZero*/, Predicates); 11850 } 11851 11852 // We use the expression (max(End,Start)-Start)/Stride to describe the 11853 // backedge count, as if the backedge is taken at least once max(End,Start) 11854 // is End and so the result is as above, and if not max(End,Start) is Start 11855 // so we get a backedge count of zero. 11856 const SCEV *BECount = nullptr; 11857 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 11858 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 11859 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 11860 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 11861 // Can we prove (max(RHS,Start) > Start - Stride? 11862 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 11863 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 11864 // In this case, we can use a refined formula for computing backedge taken 11865 // count. The general formula remains: 11866 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11867 // We want to use the alternate formula: 11868 // "((End - 1) - (Start - Stride)) /u Stride" 11869 // Let's do a quick case analysis to show these are equivalent under 11870 // our precondition that max(RHS,Start) > Start - Stride. 11871 // * For RHS <= Start, the backedge-taken count must be zero. 11872 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11873 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11874 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11875 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11876 // this to the stride of 1 case. 11877 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11878 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11879 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11880 // "((RHS - (Start - Stride) - 1) /u Stride". 11881 // Our preconditions trivially imply no overflow in that form. 11882 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11883 const SCEV *Numerator = 11884 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 11885 BECount = getUDivExpr(Numerator, Stride); 11886 } 11887 11888 const SCEV *BECountIfBackedgeTaken = nullptr; 11889 if (!BECount) { 11890 auto canProveRHSGreaterThanEqualStart = [&]() { 11891 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11892 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11893 return true; 11894 11895 // (RHS > Start - 1) implies RHS >= Start. 11896 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11897 // "Start - 1" doesn't overflow. 11898 // * For signed comparison, if Start - 1 does overflow, it's equal 11899 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11900 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11901 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11902 // 11903 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11904 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11905 auto *StartMinusOne = getAddExpr(OrigStart, 11906 getMinusOne(OrigStart->getType())); 11907 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11908 }; 11909 11910 // If we know that RHS >= Start in the context of loop, then we know that 11911 // max(RHS, Start) = RHS at this point. 11912 const SCEV *End; 11913 if (canProveRHSGreaterThanEqualStart()) { 11914 End = RHS; 11915 } else { 11916 // If RHS < Start, the backedge will be taken zero times. So in 11917 // general, we can write the backedge-taken count as: 11918 // 11919 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11920 // 11921 // We convert it to the following to make it more convenient for SCEV: 11922 // 11923 // ceil(max(RHS, Start) - Start) / Stride 11924 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11925 11926 // See what would happen if we assume the backedge is taken. This is 11927 // used to compute MaxBECount. 11928 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11929 } 11930 11931 // At this point, we know: 11932 // 11933 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11934 // 2. The index variable doesn't overflow. 11935 // 11936 // Therefore, we know N exists such that 11937 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11938 // doesn't overflow. 11939 // 11940 // Using this information, try to prove whether the addition in 11941 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11942 const SCEV *One = getOne(Stride->getType()); 11943 bool MayAddOverflow = [&] { 11944 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11945 if (StrideC->getAPInt().isPowerOf2()) { 11946 // Suppose Stride is a power of two, and Start/End are unsigned 11947 // integers. Let UMAX be the largest representable unsigned 11948 // integer. 11949 // 11950 // By the preconditions of this function, we know 11951 // "(Start + Stride * N) >= End", and this doesn't overflow. 11952 // As a formula: 11953 // 11954 // End <= (Start + Stride * N) <= UMAX 11955 // 11956 // Subtracting Start from all the terms: 11957 // 11958 // End - Start <= Stride * N <= UMAX - Start 11959 // 11960 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11961 // 11962 // End - Start <= Stride * N <= UMAX 11963 // 11964 // Stride * N is a multiple of Stride. Therefore, 11965 // 11966 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11967 // 11968 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11969 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11970 // 11971 // End - Start <= Stride * N <= UMAX - Stride - 1 11972 // 11973 // Dropping the middle term: 11974 // 11975 // End - Start <= UMAX - Stride - 1 11976 // 11977 // Adding Stride - 1 to both sides: 11978 // 11979 // (End - Start) + (Stride - 1) <= UMAX 11980 // 11981 // In other words, the addition doesn't have unsigned overflow. 11982 // 11983 // A similar proof works if we treat Start/End as signed values. 11984 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11985 // use signed max instead of unsigned max. Note that we're trying 11986 // to prove a lack of unsigned overflow in either case. 11987 return false; 11988 } 11989 } 11990 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 11991 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 11992 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 11993 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 11994 // 11995 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 11996 return false; 11997 } 11998 return true; 11999 }(); 12000 12001 const SCEV *Delta = getMinusSCEV(End, Start); 12002 if (!MayAddOverflow) { 12003 // floor((D + (S - 1)) / S) 12004 // We prefer this formulation if it's legal because it's fewer operations. 12005 BECount = 12006 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12007 } else { 12008 BECount = getUDivCeilSCEV(Delta, Stride); 12009 } 12010 } 12011 12012 const SCEV *MaxBECount; 12013 bool MaxOrZero = false; 12014 if (isa<SCEVConstant>(BECount)) { 12015 MaxBECount = BECount; 12016 } else if (BECountIfBackedgeTaken && 12017 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12018 // If we know exactly how many times the backedge will be taken if it's 12019 // taken at least once, then the backedge count will either be that or 12020 // zero. 12021 MaxBECount = BECountIfBackedgeTaken; 12022 MaxOrZero = true; 12023 } else { 12024 MaxBECount = computeMaxBECountForLT( 12025 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12026 } 12027 12028 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12029 !isa<SCEVCouldNotCompute>(BECount)) 12030 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12031 12032 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12033 } 12034 12035 ScalarEvolution::ExitLimit 12036 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12037 const Loop *L, bool IsSigned, 12038 bool ControlsExit, bool AllowPredicates) { 12039 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12040 // We handle only IV > Invariant 12041 if (!isLoopInvariant(RHS, L)) 12042 return getCouldNotCompute(); 12043 12044 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12045 if (!IV && AllowPredicates) 12046 // Try to make this an AddRec using runtime tests, in the first X 12047 // iterations of this loop, where X is the SCEV expression found by the 12048 // algorithm below. 12049 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12050 12051 // Avoid weird loops 12052 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12053 return getCouldNotCompute(); 12054 12055 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12056 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12057 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12058 12059 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12060 12061 // Avoid negative or zero stride values 12062 if (!isKnownPositive(Stride)) 12063 return getCouldNotCompute(); 12064 12065 // Avoid proven overflow cases: this will ensure that the backedge taken count 12066 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12067 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12068 // behaviors like the case of C language. 12069 if (!Stride->isOne() && !NoWrap) 12070 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12071 return getCouldNotCompute(); 12072 12073 const SCEV *Start = IV->getStart(); 12074 const SCEV *End = RHS; 12075 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12076 // If we know that Start >= RHS in the context of loop, then we know that 12077 // min(RHS, Start) = RHS at this point. 12078 if (isLoopEntryGuardedByCond( 12079 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12080 End = RHS; 12081 else 12082 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12083 } 12084 12085 if (Start->getType()->isPointerTy()) { 12086 Start = getLosslessPtrToIntExpr(Start); 12087 if (isa<SCEVCouldNotCompute>(Start)) 12088 return Start; 12089 } 12090 if (End->getType()->isPointerTy()) { 12091 End = getLosslessPtrToIntExpr(End); 12092 if (isa<SCEVCouldNotCompute>(End)) 12093 return End; 12094 } 12095 12096 // Compute ((Start - End) + (Stride - 1)) / Stride. 12097 // FIXME: This can overflow. Holding off on fixing this for now; 12098 // howManyGreaterThans will hopefully be gone soon. 12099 const SCEV *One = getOne(Stride->getType()); 12100 const SCEV *BECount = getUDivExpr( 12101 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12102 12103 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12104 : getUnsignedRangeMax(Start); 12105 12106 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12107 : getUnsignedRangeMin(Stride); 12108 12109 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12110 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12111 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12112 12113 // Although End can be a MIN expression we estimate MinEnd considering only 12114 // the case End = RHS. This is safe because in the other case (Start - End) 12115 // is zero, leading to a zero maximum backedge taken count. 12116 APInt MinEnd = 12117 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12118 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12119 12120 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12121 ? BECount 12122 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12123 getConstant(MinStride)); 12124 12125 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12126 MaxBECount = BECount; 12127 12128 return ExitLimit(BECount, MaxBECount, false, Predicates); 12129 } 12130 12131 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12132 ScalarEvolution &SE) const { 12133 if (Range.isFullSet()) // Infinite loop. 12134 return SE.getCouldNotCompute(); 12135 12136 // If the start is a non-zero constant, shift the range to simplify things. 12137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12138 if (!SC->getValue()->isZero()) { 12139 SmallVector<const SCEV *, 4> Operands(operands()); 12140 Operands[0] = SE.getZero(SC->getType()); 12141 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12142 getNoWrapFlags(FlagNW)); 12143 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12144 return ShiftedAddRec->getNumIterationsInRange( 12145 Range.subtract(SC->getAPInt()), SE); 12146 // This is strange and shouldn't happen. 12147 return SE.getCouldNotCompute(); 12148 } 12149 12150 // The only time we can solve this is when we have all constant indices. 12151 // Otherwise, we cannot determine the overflow conditions. 12152 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12153 return SE.getCouldNotCompute(); 12154 12155 // Okay at this point we know that all elements of the chrec are constants and 12156 // that the start element is zero. 12157 12158 // First check to see if the range contains zero. If not, the first 12159 // iteration exits. 12160 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12161 if (!Range.contains(APInt(BitWidth, 0))) 12162 return SE.getZero(getType()); 12163 12164 if (isAffine()) { 12165 // If this is an affine expression then we have this situation: 12166 // Solve {0,+,A} in Range === Ax in Range 12167 12168 // We know that zero is in the range. If A is positive then we know that 12169 // the upper value of the range must be the first possible exit value. 12170 // If A is negative then the lower of the range is the last possible loop 12171 // value. Also note that we already checked for a full range. 12172 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12173 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12174 12175 // The exit value should be (End+A)/A. 12176 APInt ExitVal = (End + A).udiv(A); 12177 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12178 12179 // Evaluate at the exit value. If we really did fall out of the valid 12180 // range, then we computed our trip count, otherwise wrap around or other 12181 // things must have happened. 12182 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12183 if (Range.contains(Val->getValue())) 12184 return SE.getCouldNotCompute(); // Something strange happened 12185 12186 // Ensure that the previous value is in the range. This is a sanity check. 12187 assert(Range.contains( 12188 EvaluateConstantChrecAtConstant(this, 12189 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12190 "Linear scev computation is off in a bad way!"); 12191 return SE.getConstant(ExitValue); 12192 } 12193 12194 if (isQuadratic()) { 12195 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12196 return SE.getConstant(S.getValue()); 12197 } 12198 12199 return SE.getCouldNotCompute(); 12200 } 12201 12202 const SCEVAddRecExpr * 12203 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12204 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12205 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12206 // but in this case we cannot guarantee that the value returned will be an 12207 // AddRec because SCEV does not have a fixed point where it stops 12208 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12209 // may happen if we reach arithmetic depth limit while simplifying. So we 12210 // construct the returned value explicitly. 12211 SmallVector<const SCEV *, 3> Ops; 12212 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12213 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12214 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12215 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12216 // We know that the last operand is not a constant zero (otherwise it would 12217 // have been popped out earlier). This guarantees us that if the result has 12218 // the same last operand, then it will also not be popped out, meaning that 12219 // the returned value will be an AddRec. 12220 const SCEV *Last = getOperand(getNumOperands() - 1); 12221 assert(!Last->isZero() && "Recurrency with zero step?"); 12222 Ops.push_back(Last); 12223 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12224 SCEV::FlagAnyWrap)); 12225 } 12226 12227 // Return true when S contains at least an undef value. 12228 static inline bool containsUndefs(const SCEV *S) { 12229 return SCEVExprContains(S, [](const SCEV *S) { 12230 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12231 return isa<UndefValue>(SU->getValue()); 12232 return false; 12233 }); 12234 } 12235 12236 /// Return the size of an element read or written by Inst. 12237 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12238 Type *Ty; 12239 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12240 Ty = Store->getValueOperand()->getType(); 12241 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12242 Ty = Load->getType(); 12243 else 12244 return nullptr; 12245 12246 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12247 return getSizeOfExpr(ETy, Ty); 12248 } 12249 12250 //===----------------------------------------------------------------------===// 12251 // SCEVCallbackVH Class Implementation 12252 //===----------------------------------------------------------------------===// 12253 12254 void ScalarEvolution::SCEVCallbackVH::deleted() { 12255 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12256 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12257 SE->ConstantEvolutionLoopExitValue.erase(PN); 12258 SE->eraseValueFromMap(getValPtr()); 12259 // this now dangles! 12260 } 12261 12262 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12263 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12264 12265 // Forget all the expressions associated with users of the old value, 12266 // so that future queries will recompute the expressions using the new 12267 // value. 12268 Value *Old = getValPtr(); 12269 SmallVector<User *, 16> Worklist(Old->users()); 12270 SmallPtrSet<User *, 8> Visited; 12271 while (!Worklist.empty()) { 12272 User *U = Worklist.pop_back_val(); 12273 // Deleting the Old value will cause this to dangle. Postpone 12274 // that until everything else is done. 12275 if (U == Old) 12276 continue; 12277 if (!Visited.insert(U).second) 12278 continue; 12279 if (PHINode *PN = dyn_cast<PHINode>(U)) 12280 SE->ConstantEvolutionLoopExitValue.erase(PN); 12281 SE->eraseValueFromMap(U); 12282 llvm::append_range(Worklist, U->users()); 12283 } 12284 // Delete the Old value. 12285 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12286 SE->ConstantEvolutionLoopExitValue.erase(PN); 12287 SE->eraseValueFromMap(Old); 12288 // this now dangles! 12289 } 12290 12291 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12292 : CallbackVH(V), SE(se) {} 12293 12294 //===----------------------------------------------------------------------===// 12295 // ScalarEvolution Class Implementation 12296 //===----------------------------------------------------------------------===// 12297 12298 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12299 AssumptionCache &AC, DominatorTree &DT, 12300 LoopInfo &LI) 12301 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12302 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12303 LoopDispositions(64), BlockDispositions(64) { 12304 // To use guards for proving predicates, we need to scan every instruction in 12305 // relevant basic blocks, and not just terminators. Doing this is a waste of 12306 // time if the IR does not actually contain any calls to 12307 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12308 // 12309 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12310 // to _add_ guards to the module when there weren't any before, and wants 12311 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12312 // efficient in lieu of being smart in that rather obscure case. 12313 12314 auto *GuardDecl = F.getParent()->getFunction( 12315 Intrinsic::getName(Intrinsic::experimental_guard)); 12316 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12317 } 12318 12319 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12320 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12321 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12322 ValueExprMap(std::move(Arg.ValueExprMap)), 12323 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12324 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12325 PendingMerges(std::move(Arg.PendingMerges)), 12326 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12327 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12328 PredicatedBackedgeTakenCounts( 12329 std::move(Arg.PredicatedBackedgeTakenCounts)), 12330 ConstantEvolutionLoopExitValue( 12331 std::move(Arg.ConstantEvolutionLoopExitValue)), 12332 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12333 LoopDispositions(std::move(Arg.LoopDispositions)), 12334 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12335 BlockDispositions(std::move(Arg.BlockDispositions)), 12336 SCEVUsers(std::move(Arg.SCEVUsers)), 12337 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12338 SignedRanges(std::move(Arg.SignedRanges)), 12339 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12340 UniquePreds(std::move(Arg.UniquePreds)), 12341 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12342 LoopUsers(std::move(Arg.LoopUsers)), 12343 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12344 FirstUnknown(Arg.FirstUnknown) { 12345 Arg.FirstUnknown = nullptr; 12346 } 12347 12348 ScalarEvolution::~ScalarEvolution() { 12349 // Iterate through all the SCEVUnknown instances and call their 12350 // destructors, so that they release their references to their values. 12351 for (SCEVUnknown *U = FirstUnknown; U;) { 12352 SCEVUnknown *Tmp = U; 12353 U = U->Next; 12354 Tmp->~SCEVUnknown(); 12355 } 12356 FirstUnknown = nullptr; 12357 12358 ExprValueMap.clear(); 12359 ValueExprMap.clear(); 12360 HasRecMap.clear(); 12361 BackedgeTakenCounts.clear(); 12362 PredicatedBackedgeTakenCounts.clear(); 12363 12364 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12365 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12366 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12367 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12368 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12369 } 12370 12371 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12372 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12373 } 12374 12375 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12376 const Loop *L) { 12377 // Print all inner loops first 12378 for (Loop *I : *L) 12379 PrintLoopInfo(OS, SE, I); 12380 12381 OS << "Loop "; 12382 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12383 OS << ": "; 12384 12385 SmallVector<BasicBlock *, 8> ExitingBlocks; 12386 L->getExitingBlocks(ExitingBlocks); 12387 if (ExitingBlocks.size() != 1) 12388 OS << "<multiple exits> "; 12389 12390 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12391 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12392 else 12393 OS << "Unpredictable backedge-taken count.\n"; 12394 12395 if (ExitingBlocks.size() > 1) 12396 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12397 OS << " exit count for " << ExitingBlock->getName() << ": " 12398 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12399 } 12400 12401 OS << "Loop "; 12402 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12403 OS << ": "; 12404 12405 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12406 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12407 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12408 OS << ", actual taken count either this or zero."; 12409 } else { 12410 OS << "Unpredictable max backedge-taken count. "; 12411 } 12412 12413 OS << "\n" 12414 "Loop "; 12415 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12416 OS << ": "; 12417 12418 SCEVUnionPredicate Pred; 12419 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12420 if (!isa<SCEVCouldNotCompute>(PBT)) { 12421 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12422 OS << " Predicates:\n"; 12423 Pred.print(OS, 4); 12424 } else { 12425 OS << "Unpredictable predicated backedge-taken count. "; 12426 } 12427 OS << "\n"; 12428 12429 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12430 OS << "Loop "; 12431 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12432 OS << ": "; 12433 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12434 } 12435 } 12436 12437 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12438 switch (LD) { 12439 case ScalarEvolution::LoopVariant: 12440 return "Variant"; 12441 case ScalarEvolution::LoopInvariant: 12442 return "Invariant"; 12443 case ScalarEvolution::LoopComputable: 12444 return "Computable"; 12445 } 12446 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12447 } 12448 12449 void ScalarEvolution::print(raw_ostream &OS) const { 12450 // ScalarEvolution's implementation of the print method is to print 12451 // out SCEV values of all instructions that are interesting. Doing 12452 // this potentially causes it to create new SCEV objects though, 12453 // which technically conflicts with the const qualifier. This isn't 12454 // observable from outside the class though, so casting away the 12455 // const isn't dangerous. 12456 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12457 12458 if (ClassifyExpressions) { 12459 OS << "Classifying expressions for: "; 12460 F.printAsOperand(OS, /*PrintType=*/false); 12461 OS << "\n"; 12462 for (Instruction &I : instructions(F)) 12463 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12464 OS << I << '\n'; 12465 OS << " --> "; 12466 const SCEV *SV = SE.getSCEV(&I); 12467 SV->print(OS); 12468 if (!isa<SCEVCouldNotCompute>(SV)) { 12469 OS << " U: "; 12470 SE.getUnsignedRange(SV).print(OS); 12471 OS << " S: "; 12472 SE.getSignedRange(SV).print(OS); 12473 } 12474 12475 const Loop *L = LI.getLoopFor(I.getParent()); 12476 12477 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12478 if (AtUse != SV) { 12479 OS << " --> "; 12480 AtUse->print(OS); 12481 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12482 OS << " U: "; 12483 SE.getUnsignedRange(AtUse).print(OS); 12484 OS << " S: "; 12485 SE.getSignedRange(AtUse).print(OS); 12486 } 12487 } 12488 12489 if (L) { 12490 OS << "\t\t" "Exits: "; 12491 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12492 if (!SE.isLoopInvariant(ExitValue, L)) { 12493 OS << "<<Unknown>>"; 12494 } else { 12495 OS << *ExitValue; 12496 } 12497 12498 bool First = true; 12499 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12500 if (First) { 12501 OS << "\t\t" "LoopDispositions: { "; 12502 First = false; 12503 } else { 12504 OS << ", "; 12505 } 12506 12507 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12508 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12509 } 12510 12511 for (auto *InnerL : depth_first(L)) { 12512 if (InnerL == L) 12513 continue; 12514 if (First) { 12515 OS << "\t\t" "LoopDispositions: { "; 12516 First = false; 12517 } else { 12518 OS << ", "; 12519 } 12520 12521 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12522 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12523 } 12524 12525 OS << " }"; 12526 } 12527 12528 OS << "\n"; 12529 } 12530 } 12531 12532 OS << "Determining loop execution counts for: "; 12533 F.printAsOperand(OS, /*PrintType=*/false); 12534 OS << "\n"; 12535 for (Loop *I : LI) 12536 PrintLoopInfo(OS, &SE, I); 12537 } 12538 12539 ScalarEvolution::LoopDisposition 12540 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12541 auto &Values = LoopDispositions[S]; 12542 for (auto &V : Values) { 12543 if (V.getPointer() == L) 12544 return V.getInt(); 12545 } 12546 Values.emplace_back(L, LoopVariant); 12547 LoopDisposition D = computeLoopDisposition(S, L); 12548 auto &Values2 = LoopDispositions[S]; 12549 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12550 if (V.getPointer() == L) { 12551 V.setInt(D); 12552 break; 12553 } 12554 } 12555 return D; 12556 } 12557 12558 ScalarEvolution::LoopDisposition 12559 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12560 switch (S->getSCEVType()) { 12561 case scConstant: 12562 return LoopInvariant; 12563 case scPtrToInt: 12564 case scTruncate: 12565 case scZeroExtend: 12566 case scSignExtend: 12567 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12568 case scAddRecExpr: { 12569 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12570 12571 // If L is the addrec's loop, it's computable. 12572 if (AR->getLoop() == L) 12573 return LoopComputable; 12574 12575 // Add recurrences are never invariant in the function-body (null loop). 12576 if (!L) 12577 return LoopVariant; 12578 12579 // Everything that is not defined at loop entry is variant. 12580 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12581 return LoopVariant; 12582 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12583 " dominate the contained loop's header?"); 12584 12585 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12586 if (AR->getLoop()->contains(L)) 12587 return LoopInvariant; 12588 12589 // This recurrence is variant w.r.t. L if any of its operands 12590 // are variant. 12591 for (auto *Op : AR->operands()) 12592 if (!isLoopInvariant(Op, L)) 12593 return LoopVariant; 12594 12595 // Otherwise it's loop-invariant. 12596 return LoopInvariant; 12597 } 12598 case scAddExpr: 12599 case scMulExpr: 12600 case scUMaxExpr: 12601 case scSMaxExpr: 12602 case scUMinExpr: 12603 case scSMinExpr: { 12604 bool HasVarying = false; 12605 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12606 LoopDisposition D = getLoopDisposition(Op, L); 12607 if (D == LoopVariant) 12608 return LoopVariant; 12609 if (D == LoopComputable) 12610 HasVarying = true; 12611 } 12612 return HasVarying ? LoopComputable : LoopInvariant; 12613 } 12614 case scUDivExpr: { 12615 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12616 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12617 if (LD == LoopVariant) 12618 return LoopVariant; 12619 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12620 if (RD == LoopVariant) 12621 return LoopVariant; 12622 return (LD == LoopInvariant && RD == LoopInvariant) ? 12623 LoopInvariant : LoopComputable; 12624 } 12625 case scUnknown: 12626 // All non-instruction values are loop invariant. All instructions are loop 12627 // invariant if they are not contained in the specified loop. 12628 // Instructions are never considered invariant in the function body 12629 // (null loop) because they are defined within the "loop". 12630 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12631 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12632 return LoopInvariant; 12633 case scCouldNotCompute: 12634 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12635 } 12636 llvm_unreachable("Unknown SCEV kind!"); 12637 } 12638 12639 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12640 return getLoopDisposition(S, L) == LoopInvariant; 12641 } 12642 12643 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12644 return getLoopDisposition(S, L) == LoopComputable; 12645 } 12646 12647 ScalarEvolution::BlockDisposition 12648 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12649 auto &Values = BlockDispositions[S]; 12650 for (auto &V : Values) { 12651 if (V.getPointer() == BB) 12652 return V.getInt(); 12653 } 12654 Values.emplace_back(BB, DoesNotDominateBlock); 12655 BlockDisposition D = computeBlockDisposition(S, BB); 12656 auto &Values2 = BlockDispositions[S]; 12657 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12658 if (V.getPointer() == BB) { 12659 V.setInt(D); 12660 break; 12661 } 12662 } 12663 return D; 12664 } 12665 12666 ScalarEvolution::BlockDisposition 12667 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12668 switch (S->getSCEVType()) { 12669 case scConstant: 12670 return ProperlyDominatesBlock; 12671 case scPtrToInt: 12672 case scTruncate: 12673 case scZeroExtend: 12674 case scSignExtend: 12675 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12676 case scAddRecExpr: { 12677 // This uses a "dominates" query instead of "properly dominates" query 12678 // to test for proper dominance too, because the instruction which 12679 // produces the addrec's value is a PHI, and a PHI effectively properly 12680 // dominates its entire containing block. 12681 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12682 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12683 return DoesNotDominateBlock; 12684 12685 // Fall through into SCEVNAryExpr handling. 12686 LLVM_FALLTHROUGH; 12687 } 12688 case scAddExpr: 12689 case scMulExpr: 12690 case scUMaxExpr: 12691 case scSMaxExpr: 12692 case scUMinExpr: 12693 case scSMinExpr: { 12694 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12695 bool Proper = true; 12696 for (const SCEV *NAryOp : NAry->operands()) { 12697 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12698 if (D == DoesNotDominateBlock) 12699 return DoesNotDominateBlock; 12700 if (D == DominatesBlock) 12701 Proper = false; 12702 } 12703 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12704 } 12705 case scUDivExpr: { 12706 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12707 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12708 BlockDisposition LD = getBlockDisposition(LHS, BB); 12709 if (LD == DoesNotDominateBlock) 12710 return DoesNotDominateBlock; 12711 BlockDisposition RD = getBlockDisposition(RHS, BB); 12712 if (RD == DoesNotDominateBlock) 12713 return DoesNotDominateBlock; 12714 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12715 ProperlyDominatesBlock : DominatesBlock; 12716 } 12717 case scUnknown: 12718 if (Instruction *I = 12719 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12720 if (I->getParent() == BB) 12721 return DominatesBlock; 12722 if (DT.properlyDominates(I->getParent(), BB)) 12723 return ProperlyDominatesBlock; 12724 return DoesNotDominateBlock; 12725 } 12726 return ProperlyDominatesBlock; 12727 case scCouldNotCompute: 12728 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12729 } 12730 llvm_unreachable("Unknown SCEV kind!"); 12731 } 12732 12733 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12734 return getBlockDisposition(S, BB) >= DominatesBlock; 12735 } 12736 12737 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12738 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12739 } 12740 12741 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12742 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12743 } 12744 12745 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 12746 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 12747 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end()); 12748 12749 while (!Worklist.empty()) { 12750 const SCEV *Curr = Worklist.pop_back_val(); 12751 auto Users = SCEVUsers.find(Curr); 12752 if (Users != SCEVUsers.end()) 12753 for (auto *User : Users->second) 12754 if (ToForget.insert(User).second) 12755 Worklist.push_back(User); 12756 } 12757 12758 for (auto *S : ToForget) 12759 forgetMemoizedResultsImpl(S); 12760 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::verify() const { 12818 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12819 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12820 12821 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12822 12823 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12824 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12825 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12826 12827 const SCEV *visitConstant(const SCEVConstant *Constant) { 12828 return SE.getConstant(Constant->getAPInt()); 12829 } 12830 12831 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12832 return SE.getUnknown(Expr->getValue()); 12833 } 12834 12835 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12836 return SE.getCouldNotCompute(); 12837 } 12838 }; 12839 12840 SCEVMapper SCM(SE2); 12841 12842 while (!LoopStack.empty()) { 12843 auto *L = LoopStack.pop_back_val(); 12844 llvm::append_range(LoopStack, *L); 12845 12846 auto *CurBECount = SCM.visit( 12847 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12848 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12849 12850 if (CurBECount == SE2.getCouldNotCompute() || 12851 NewBECount == SE2.getCouldNotCompute()) { 12852 // NB! This situation is legal, but is very suspicious -- whatever pass 12853 // change the loop to make a trip count go from could not compute to 12854 // computable or vice-versa *should have* invalidated SCEV. However, we 12855 // choose not to assert here (for now) since we don't want false 12856 // positives. 12857 continue; 12858 } 12859 12860 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12861 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12862 // not propagate undef aggressively). This means we can (and do) fail 12863 // verification in cases where a transform makes the trip count of a loop 12864 // go from "undef" to "undef+1" (say). The transform is fine, since in 12865 // both cases the loop iterates "undef" times, but SCEV thinks we 12866 // increased the trip count of the loop by 1 incorrectly. 12867 continue; 12868 } 12869 12870 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12871 SE.getTypeSizeInBits(NewBECount->getType())) 12872 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12873 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12874 SE.getTypeSizeInBits(NewBECount->getType())) 12875 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12876 12877 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12878 12879 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12880 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12881 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12882 dbgs() << "Old: " << *CurBECount << "\n"; 12883 dbgs() << "New: " << *NewBECount << "\n"; 12884 dbgs() << "Delta: " << *Delta << "\n"; 12885 std::abort(); 12886 } 12887 } 12888 12889 // Collect all valid loops currently in LoopInfo. 12890 SmallPtrSet<Loop *, 32> ValidLoops; 12891 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12892 while (!Worklist.empty()) { 12893 Loop *L = Worklist.pop_back_val(); 12894 if (ValidLoops.contains(L)) 12895 continue; 12896 ValidLoops.insert(L); 12897 Worklist.append(L->begin(), L->end()); 12898 } 12899 // Check for SCEV expressions referencing invalid/deleted loops. 12900 for (auto &KV : ValueExprMap) { 12901 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12902 if (!AR) 12903 continue; 12904 assert(ValidLoops.contains(AR->getLoop()) && 12905 "AddRec references invalid loop"); 12906 } 12907 12908 // Verify intergity of SCEV users. 12909 for (const auto &S : UniqueSCEVs) { 12910 SmallVector<const SCEV *, 4> Ops; 12911 collectUniqueOps(&S, Ops); 12912 for (const auto *Op : Ops) { 12913 // We do not store dependencies of constants. 12914 if (isa<SCEVConstant>(Op)) 12915 continue; 12916 auto It = SCEVUsers.find(Op); 12917 if (It != SCEVUsers.end() && It->second.count(&S)) 12918 continue; 12919 dbgs() << "Use of operand " << *Op << " by user " << S 12920 << " is not being tracked!\n"; 12921 std::abort(); 12922 } 12923 } 12924 } 12925 12926 bool ScalarEvolution::invalidate( 12927 Function &F, const PreservedAnalyses &PA, 12928 FunctionAnalysisManager::Invalidator &Inv) { 12929 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12930 // of its dependencies is invalidated. 12931 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12932 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12933 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12934 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12935 Inv.invalidate<LoopAnalysis>(F, PA); 12936 } 12937 12938 AnalysisKey ScalarEvolutionAnalysis::Key; 12939 12940 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12941 FunctionAnalysisManager &AM) { 12942 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12943 AM.getResult<AssumptionAnalysis>(F), 12944 AM.getResult<DominatorTreeAnalysis>(F), 12945 AM.getResult<LoopAnalysis>(F)); 12946 } 12947 12948 PreservedAnalyses 12949 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12950 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12951 return PreservedAnalyses::all(); 12952 } 12953 12954 PreservedAnalyses 12955 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12956 // For compatibility with opt's -analyze feature under legacy pass manager 12957 // which was not ported to NPM. This keeps tests using 12958 // update_analyze_test_checks.py working. 12959 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12960 << F.getName() << "':\n"; 12961 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12962 return PreservedAnalyses::all(); 12963 } 12964 12965 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12966 "Scalar Evolution Analysis", false, true) 12967 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12968 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12969 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12970 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12971 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12972 "Scalar Evolution Analysis", false, true) 12973 12974 char ScalarEvolutionWrapperPass::ID = 0; 12975 12976 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12977 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12978 } 12979 12980 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12981 SE.reset(new ScalarEvolution( 12982 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12983 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12984 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12985 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12986 return false; 12987 } 12988 12989 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12990 12991 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12992 SE->print(OS); 12993 } 12994 12995 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12996 if (!VerifySCEV) 12997 return; 12998 12999 SE->verify(); 13000 } 13001 13002 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13003 AU.setPreservesAll(); 13004 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13005 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13006 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13007 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13008 } 13009 13010 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13011 const SCEV *RHS) { 13012 FoldingSetNodeID ID; 13013 assert(LHS->getType() == RHS->getType() && 13014 "Type mismatch between LHS and RHS"); 13015 // Unique this node based on the arguments 13016 ID.AddInteger(SCEVPredicate::P_Equal); 13017 ID.AddPointer(LHS); 13018 ID.AddPointer(RHS); 13019 void *IP = nullptr; 13020 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13021 return S; 13022 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13023 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13024 UniquePreds.InsertNode(Eq, IP); 13025 return Eq; 13026 } 13027 13028 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13029 const SCEVAddRecExpr *AR, 13030 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13031 FoldingSetNodeID ID; 13032 // Unique this node based on the arguments 13033 ID.AddInteger(SCEVPredicate::P_Wrap); 13034 ID.AddPointer(AR); 13035 ID.AddInteger(AddedFlags); 13036 void *IP = nullptr; 13037 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13038 return S; 13039 auto *OF = new (SCEVAllocator) 13040 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13041 UniquePreds.InsertNode(OF, IP); 13042 return OF; 13043 } 13044 13045 namespace { 13046 13047 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13048 public: 13049 13050 /// Rewrites \p S in the context of a loop L and the SCEV predication 13051 /// infrastructure. 13052 /// 13053 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13054 /// equivalences present in \p Pred. 13055 /// 13056 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13057 /// \p NewPreds such that the result will be an AddRecExpr. 13058 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13059 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13060 SCEVUnionPredicate *Pred) { 13061 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13062 return Rewriter.visit(S); 13063 } 13064 13065 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13066 if (Pred) { 13067 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13068 for (auto *Pred : ExprPreds) 13069 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13070 if (IPred->getLHS() == Expr) 13071 return IPred->getRHS(); 13072 } 13073 return convertToAddRecWithPreds(Expr); 13074 } 13075 13076 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13077 const SCEV *Operand = visit(Expr->getOperand()); 13078 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13079 if (AR && AR->getLoop() == L && AR->isAffine()) { 13080 // This couldn't be folded because the operand didn't have the nuw 13081 // flag. Add the nusw flag as an assumption that we could make. 13082 const SCEV *Step = AR->getStepRecurrence(SE); 13083 Type *Ty = Expr->getType(); 13084 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13085 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13086 SE.getSignExtendExpr(Step, Ty), L, 13087 AR->getNoWrapFlags()); 13088 } 13089 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13090 } 13091 13092 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13093 const SCEV *Operand = visit(Expr->getOperand()); 13094 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13095 if (AR && AR->getLoop() == L && AR->isAffine()) { 13096 // This couldn't be folded because the operand didn't have the nsw 13097 // flag. Add the nssw flag as an assumption that we could make. 13098 const SCEV *Step = AR->getStepRecurrence(SE); 13099 Type *Ty = Expr->getType(); 13100 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13101 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13102 SE.getSignExtendExpr(Step, Ty), L, 13103 AR->getNoWrapFlags()); 13104 } 13105 return SE.getSignExtendExpr(Operand, Expr->getType()); 13106 } 13107 13108 private: 13109 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13110 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13111 SCEVUnionPredicate *Pred) 13112 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13113 13114 bool addOverflowAssumption(const SCEVPredicate *P) { 13115 if (!NewPreds) { 13116 // Check if we've already made this assumption. 13117 return Pred && Pred->implies(P); 13118 } 13119 NewPreds->insert(P); 13120 return true; 13121 } 13122 13123 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13124 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13125 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13126 return addOverflowAssumption(A); 13127 } 13128 13129 // If \p Expr represents a PHINode, we try to see if it can be represented 13130 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13131 // to add this predicate as a runtime overflow check, we return the AddRec. 13132 // If \p Expr does not meet these conditions (is not a PHI node, or we 13133 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13134 // return \p Expr. 13135 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13136 if (!isa<PHINode>(Expr->getValue())) 13137 return Expr; 13138 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13139 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13140 if (!PredicatedRewrite) 13141 return Expr; 13142 for (auto *P : PredicatedRewrite->second){ 13143 // Wrap predicates from outer loops are not supported. 13144 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13145 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13146 if (L != AR->getLoop()) 13147 return Expr; 13148 } 13149 if (!addOverflowAssumption(P)) 13150 return Expr; 13151 } 13152 return PredicatedRewrite->first; 13153 } 13154 13155 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13156 SCEVUnionPredicate *Pred; 13157 const Loop *L; 13158 }; 13159 13160 } // end anonymous namespace 13161 13162 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13163 SCEVUnionPredicate &Preds) { 13164 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13165 } 13166 13167 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13168 const SCEV *S, const Loop *L, 13169 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13170 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13171 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13172 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13173 13174 if (!AddRec) 13175 return nullptr; 13176 13177 // Since the transformation was successful, we can now transfer the SCEV 13178 // predicates. 13179 for (auto *P : TransformPreds) 13180 Preds.insert(P); 13181 13182 return AddRec; 13183 } 13184 13185 /// SCEV predicates 13186 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13187 SCEVPredicateKind Kind) 13188 : FastID(ID), Kind(Kind) {} 13189 13190 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13191 const SCEV *LHS, const SCEV *RHS) 13192 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13193 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13194 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13195 } 13196 13197 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13198 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13199 13200 if (!Op) 13201 return false; 13202 13203 return Op->LHS == LHS && Op->RHS == RHS; 13204 } 13205 13206 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13207 13208 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13209 13210 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13211 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13212 } 13213 13214 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13215 const SCEVAddRecExpr *AR, 13216 IncrementWrapFlags Flags) 13217 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13218 13219 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13220 13221 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13222 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13223 13224 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13225 } 13226 13227 bool SCEVWrapPredicate::isAlwaysTrue() const { 13228 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13229 IncrementWrapFlags IFlags = Flags; 13230 13231 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13232 IFlags = clearFlags(IFlags, IncrementNSSW); 13233 13234 return IFlags == IncrementAnyWrap; 13235 } 13236 13237 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13238 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13239 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13240 OS << "<nusw>"; 13241 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13242 OS << "<nssw>"; 13243 OS << "\n"; 13244 } 13245 13246 SCEVWrapPredicate::IncrementWrapFlags 13247 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13248 ScalarEvolution &SE) { 13249 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13250 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13251 13252 // We can safely transfer the NSW flag as NSSW. 13253 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13254 ImpliedFlags = IncrementNSSW; 13255 13256 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13257 // If the increment is positive, the SCEV NUW flag will also imply the 13258 // WrapPredicate NUSW flag. 13259 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13260 if (Step->getValue()->getValue().isNonNegative()) 13261 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13262 } 13263 13264 return ImpliedFlags; 13265 } 13266 13267 /// Union predicates don't get cached so create a dummy set ID for it. 13268 SCEVUnionPredicate::SCEVUnionPredicate() 13269 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13270 13271 bool SCEVUnionPredicate::isAlwaysTrue() const { 13272 return all_of(Preds, 13273 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13274 } 13275 13276 ArrayRef<const SCEVPredicate *> 13277 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13278 auto I = SCEVToPreds.find(Expr); 13279 if (I == SCEVToPreds.end()) 13280 return ArrayRef<const SCEVPredicate *>(); 13281 return I->second; 13282 } 13283 13284 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13285 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13286 return all_of(Set->Preds, 13287 [this](const SCEVPredicate *I) { return this->implies(I); }); 13288 13289 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13290 if (ScevPredsIt == SCEVToPreds.end()) 13291 return false; 13292 auto &SCEVPreds = ScevPredsIt->second; 13293 13294 return any_of(SCEVPreds, 13295 [N](const SCEVPredicate *I) { return I->implies(N); }); 13296 } 13297 13298 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13299 13300 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13301 for (auto Pred : Preds) 13302 Pred->print(OS, Depth); 13303 } 13304 13305 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13306 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13307 for (auto Pred : Set->Preds) 13308 add(Pred); 13309 return; 13310 } 13311 13312 if (implies(N)) 13313 return; 13314 13315 const SCEV *Key = N->getExpr(); 13316 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13317 " associated expression!"); 13318 13319 SCEVToPreds[Key].push_back(N); 13320 Preds.push_back(N); 13321 } 13322 13323 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13324 Loop &L) 13325 : SE(SE), L(L) {} 13326 13327 void ScalarEvolution::registerUser(const SCEV *User, 13328 ArrayRef<const SCEV *> Ops) { 13329 for (auto *Op : Ops) 13330 // We do not expect that forgetting cached data for SCEVConstants will ever 13331 // open any prospects for sharpening or introduce any correctness issues, 13332 // so we don't bother storing their dependencies. 13333 if (!isa<SCEVConstant>(Op)) 13334 SCEVUsers[Op].insert(User); 13335 } 13336 13337 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13338 const SCEV *Expr = SE.getSCEV(V); 13339 RewriteEntry &Entry = RewriteMap[Expr]; 13340 13341 // If we already have an entry and the version matches, return it. 13342 if (Entry.second && Generation == Entry.first) 13343 return Entry.second; 13344 13345 // We found an entry but it's stale. Rewrite the stale entry 13346 // according to the current predicate. 13347 if (Entry.second) 13348 Expr = Entry.second; 13349 13350 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13351 Entry = {Generation, NewSCEV}; 13352 13353 return NewSCEV; 13354 } 13355 13356 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13357 if (!BackedgeCount) { 13358 SCEVUnionPredicate BackedgePred; 13359 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13360 addPredicate(BackedgePred); 13361 } 13362 return BackedgeCount; 13363 } 13364 13365 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13366 if (Preds.implies(&Pred)) 13367 return; 13368 Preds.add(&Pred); 13369 updateGeneration(); 13370 } 13371 13372 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13373 return Preds; 13374 } 13375 13376 void PredicatedScalarEvolution::updateGeneration() { 13377 // If the generation number wrapped recompute everything. 13378 if (++Generation == 0) { 13379 for (auto &II : RewriteMap) { 13380 const SCEV *Rewritten = II.second.second; 13381 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13382 } 13383 } 13384 } 13385 13386 void PredicatedScalarEvolution::setNoOverflow( 13387 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13388 const SCEV *Expr = getSCEV(V); 13389 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13390 13391 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13392 13393 // Clear the statically implied flags. 13394 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13395 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13396 13397 auto II = FlagsMap.insert({V, Flags}); 13398 if (!II.second) 13399 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13400 } 13401 13402 bool PredicatedScalarEvolution::hasNoOverflow( 13403 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13404 const SCEV *Expr = getSCEV(V); 13405 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13406 13407 Flags = SCEVWrapPredicate::clearFlags( 13408 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13409 13410 auto II = FlagsMap.find(V); 13411 13412 if (II != FlagsMap.end()) 13413 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13414 13415 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13416 } 13417 13418 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13419 const SCEV *Expr = this->getSCEV(V); 13420 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13421 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13422 13423 if (!New) 13424 return nullptr; 13425 13426 for (auto *P : NewPreds) 13427 Preds.add(P); 13428 13429 updateGeneration(); 13430 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13431 return New; 13432 } 13433 13434 PredicatedScalarEvolution::PredicatedScalarEvolution( 13435 const PredicatedScalarEvolution &Init) 13436 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13437 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13438 for (auto I : Init.FlagsMap) 13439 FlagsMap.insert(I); 13440 } 13441 13442 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13443 // For each block. 13444 for (auto *BB : L.getBlocks()) 13445 for (auto &I : *BB) { 13446 if (!SE.isSCEVable(I.getType())) 13447 continue; 13448 13449 auto *Expr = SE.getSCEV(&I); 13450 auto II = RewriteMap.find(Expr); 13451 13452 if (II == RewriteMap.end()) 13453 continue; 13454 13455 // Don't print things that are not interesting. 13456 if (II->second.second == Expr) 13457 continue; 13458 13459 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13460 OS.indent(Depth + 2) << *Expr << "\n"; 13461 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13462 } 13463 } 13464 13465 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13466 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13467 // for URem with constant power-of-2 second operands. 13468 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13469 // 4, A / B becomes X / 8). 13470 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13471 const SCEV *&RHS) { 13472 // Try to match 'zext (trunc A to iB) to iY', which is used 13473 // for URem with constant power-of-2 second operands. Make sure the size of 13474 // the operand A matches the size of the whole expressions. 13475 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13476 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13477 LHS = Trunc->getOperand(); 13478 // Bail out if the type of the LHS is larger than the type of the 13479 // expression for now. 13480 if (getTypeSizeInBits(LHS->getType()) > 13481 getTypeSizeInBits(Expr->getType())) 13482 return false; 13483 if (LHS->getType() != Expr->getType()) 13484 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13485 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13486 << getTypeSizeInBits(Trunc->getType())); 13487 return true; 13488 } 13489 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13490 if (Add == nullptr || Add->getNumOperands() != 2) 13491 return false; 13492 13493 const SCEV *A = Add->getOperand(1); 13494 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13495 13496 if (Mul == nullptr) 13497 return false; 13498 13499 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13500 // (SomeExpr + (-(SomeExpr / B) * B)). 13501 if (Expr == getURemExpr(A, B)) { 13502 LHS = A; 13503 RHS = B; 13504 return true; 13505 } 13506 return false; 13507 }; 13508 13509 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13510 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13511 return MatchURemWithDivisor(Mul->getOperand(1)) || 13512 MatchURemWithDivisor(Mul->getOperand(2)); 13513 13514 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13515 if (Mul->getNumOperands() == 2) 13516 return MatchURemWithDivisor(Mul->getOperand(1)) || 13517 MatchURemWithDivisor(Mul->getOperand(0)) || 13518 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13519 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13520 return false; 13521 } 13522 13523 const SCEV * 13524 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13525 SmallVector<BasicBlock*, 16> ExitingBlocks; 13526 L->getExitingBlocks(ExitingBlocks); 13527 13528 // Form an expression for the maximum exit count possible for this loop. We 13529 // merge the max and exact information to approximate a version of 13530 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13531 SmallVector<const SCEV*, 4> ExitCounts; 13532 for (BasicBlock *ExitingBB : ExitingBlocks) { 13533 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13534 if (isa<SCEVCouldNotCompute>(ExitCount)) 13535 ExitCount = getExitCount(L, ExitingBB, 13536 ScalarEvolution::ConstantMaximum); 13537 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13538 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13539 "We should only have known counts for exiting blocks that " 13540 "dominate latch!"); 13541 ExitCounts.push_back(ExitCount); 13542 } 13543 } 13544 if (ExitCounts.empty()) 13545 return getCouldNotCompute(); 13546 return getUMinFromMismatchedTypes(ExitCounts); 13547 } 13548 13549 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13550 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13551 /// we cannot guarantee that the replacement is loop invariant in the loop of 13552 /// the AddRec. 13553 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13554 ValueToSCEVMapTy ⤅ 13555 13556 public: 13557 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13558 : SCEVRewriteVisitor(SE), Map(M) {} 13559 13560 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13561 13562 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13563 auto I = Map.find(Expr->getValue()); 13564 if (I == Map.end()) 13565 return Expr; 13566 return I->second; 13567 } 13568 }; 13569 13570 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13571 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13572 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13573 // WARNING: It is generally unsound to apply any wrap flags to the proposed 13574 // replacement SCEV which isn't directly implied by the structure of that 13575 // SCEV. In particular, using contextual facts to imply flags is *NOT* 13576 // legal. See the scoping rules for flags in the header to understand why. 13577 13578 // If we have LHS == 0, check if LHS is computing a property of some unknown 13579 // SCEV %v which we can rewrite %v to express explicitly. 13580 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13581 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13582 RHSC->getValue()->isNullValue()) { 13583 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13584 // explicitly express that. 13585 const SCEV *URemLHS = nullptr; 13586 const SCEV *URemRHS = nullptr; 13587 if (matchURem(LHS, URemLHS, URemRHS)) { 13588 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13589 Value *V = LHSUnknown->getValue(); 13590 RewriteMap[V] = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 13591 return; 13592 } 13593 } 13594 } 13595 13596 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13597 std::swap(LHS, RHS); 13598 Predicate = CmpInst::getSwappedPredicate(Predicate); 13599 } 13600 13601 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13602 // create this form when combining two checks of the form (X u< C2 + C1) and 13603 // (X >=u C1). 13604 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13605 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13606 if (!AddExpr || AddExpr->getNumOperands() != 2) 13607 return false; 13608 13609 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13610 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13611 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13612 if (!C1 || !C2 || !LHSUnknown) 13613 return false; 13614 13615 auto ExactRegion = 13616 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13617 .sub(C1->getAPInt()); 13618 13619 // Bail out, unless we have a non-wrapping, monotonic range. 13620 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13621 return false; 13622 auto I = RewriteMap.find(LHSUnknown->getValue()); 13623 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13624 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13625 getConstant(ExactRegion.getUnsignedMin()), 13626 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13627 return true; 13628 }; 13629 if (MatchRangeCheckIdiom()) 13630 return; 13631 13632 // For now, limit to conditions that provide information about unknown 13633 // expressions. RHS also cannot contain add recurrences. 13634 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13635 if (!LHSUnknown || containsAddRecurrence(RHS)) 13636 return; 13637 13638 // Check whether LHS has already been rewritten. In that case we want to 13639 // chain further rewrites onto the already rewritten value. 13640 auto I = RewriteMap.find(LHSUnknown->getValue()); 13641 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13642 const SCEV *RewrittenRHS = nullptr; 13643 switch (Predicate) { 13644 case CmpInst::ICMP_ULT: 13645 RewrittenRHS = 13646 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13647 break; 13648 case CmpInst::ICMP_SLT: 13649 RewrittenRHS = 13650 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13651 break; 13652 case CmpInst::ICMP_ULE: 13653 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13654 break; 13655 case CmpInst::ICMP_SLE: 13656 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13657 break; 13658 case CmpInst::ICMP_UGT: 13659 RewrittenRHS = 13660 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13661 break; 13662 case CmpInst::ICMP_SGT: 13663 RewrittenRHS = 13664 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13665 break; 13666 case CmpInst::ICMP_UGE: 13667 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13668 break; 13669 case CmpInst::ICMP_SGE: 13670 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13671 break; 13672 case CmpInst::ICMP_EQ: 13673 if (isa<SCEVConstant>(RHS)) 13674 RewrittenRHS = RHS; 13675 break; 13676 case CmpInst::ICMP_NE: 13677 if (isa<SCEVConstant>(RHS) && 13678 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13679 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13680 break; 13681 default: 13682 break; 13683 } 13684 13685 if (RewrittenRHS) 13686 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13687 }; 13688 // Starting at the loop predecessor, climb up the predecessor chain, as long 13689 // as there are predecessors that can be found that have unique successors 13690 // leading to the original header. 13691 // TODO: share this logic with isLoopEntryGuardedByCond. 13692 ValueToSCEVMapTy RewriteMap; 13693 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13694 L->getLoopPredecessor(), L->getHeader()); 13695 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13696 13697 const BranchInst *LoopEntryPredicate = 13698 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13699 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13700 continue; 13701 13702 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13703 SmallVector<Value *, 8> Worklist; 13704 SmallPtrSet<Value *, 8> Visited; 13705 Worklist.push_back(LoopEntryPredicate->getCondition()); 13706 while (!Worklist.empty()) { 13707 Value *Cond = Worklist.pop_back_val(); 13708 if (!Visited.insert(Cond).second) 13709 continue; 13710 13711 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13712 auto Predicate = 13713 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13714 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13715 getSCEV(Cmp->getOperand(1)), RewriteMap); 13716 continue; 13717 } 13718 13719 Value *L, *R; 13720 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13721 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13722 Worklist.push_back(L); 13723 Worklist.push_back(R); 13724 } 13725 } 13726 } 13727 13728 // Also collect information from assumptions dominating the loop. 13729 for (auto &AssumeVH : AC.assumptions()) { 13730 if (!AssumeVH) 13731 continue; 13732 auto *AssumeI = cast<CallInst>(AssumeVH); 13733 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13734 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13735 continue; 13736 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13737 getSCEV(Cmp->getOperand(1)), RewriteMap); 13738 } 13739 13740 if (RewriteMap.empty()) 13741 return Expr; 13742 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13743 return Rewriter.visit(Expr); 13744 } 13745