1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 static cl::opt<bool> 224 ClassifyExpressions("scalar-evolution-classify-expressions", 225 cl::Hidden, cl::init(true), 226 cl::desc("When printing analysis, include information on every instruction")); 227 228 static cl::opt<bool> UseExpensiveRangeSharpening( 229 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 230 cl::init(false), 231 cl::desc("Use more powerful methods of sharpening expression ranges. May " 232 "be costly in terms of compile time")); 233 234 //===----------------------------------------------------------------------===// 235 // SCEV class definitions 236 //===----------------------------------------------------------------------===// 237 238 //===----------------------------------------------------------------------===// 239 // Implementation of the SCEV class. 240 // 241 242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 243 LLVM_DUMP_METHOD void SCEV::dump() const { 244 print(dbgs()); 245 dbgs() << '\n'; 246 } 247 #endif 248 249 void SCEV::print(raw_ostream &OS) const { 250 switch (getSCEVType()) { 251 case scConstant: 252 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 253 return; 254 case scPtrToInt: { 255 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 256 const SCEV *Op = PtrToInt->getOperand(); 257 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 258 << *PtrToInt->getType() << ")"; 259 return; 260 } 261 case scTruncate: { 262 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 263 const SCEV *Op = Trunc->getOperand(); 264 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 265 << *Trunc->getType() << ")"; 266 return; 267 } 268 case scZeroExtend: { 269 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 270 const SCEV *Op = ZExt->getOperand(); 271 OS << "(zext " << *Op->getType() << " " << *Op << " to " 272 << *ZExt->getType() << ")"; 273 return; 274 } 275 case scSignExtend: { 276 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 277 const SCEV *Op = SExt->getOperand(); 278 OS << "(sext " << *Op->getType() << " " << *Op << " to " 279 << *SExt->getType() << ")"; 280 return; 281 } 282 case scAddRecExpr: { 283 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 284 OS << "{" << *AR->getOperand(0); 285 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 286 OS << ",+," << *AR->getOperand(i); 287 OS << "}<"; 288 if (AR->hasNoUnsignedWrap()) 289 OS << "nuw><"; 290 if (AR->hasNoSignedWrap()) 291 OS << "nsw><"; 292 if (AR->hasNoSelfWrap() && 293 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 294 OS << "nw><"; 295 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 296 OS << ">"; 297 return; 298 } 299 case scAddExpr: 300 case scMulExpr: 301 case scUMaxExpr: 302 case scSMaxExpr: 303 case scUMinExpr: 304 case scSMinExpr: { 305 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 306 const char *OpStr = nullptr; 307 switch (NAry->getSCEVType()) { 308 case scAddExpr: OpStr = " + "; break; 309 case scMulExpr: OpStr = " * "; break; 310 case scUMaxExpr: OpStr = " umax "; break; 311 case scSMaxExpr: OpStr = " smax "; break; 312 case scUMinExpr: 313 OpStr = " umin "; 314 break; 315 case scSMinExpr: 316 OpStr = " smin "; 317 break; 318 default: 319 llvm_unreachable("There are no other nary expression types."); 320 } 321 OS << "("; 322 ListSeparator LS(OpStr); 323 for (const SCEV *Op : NAry->operands()) 324 OS << LS << *Op; 325 OS << ")"; 326 switch (NAry->getSCEVType()) { 327 case scAddExpr: 328 case scMulExpr: 329 if (NAry->hasNoUnsignedWrap()) 330 OS << "<nuw>"; 331 if (NAry->hasNoSignedWrap()) 332 OS << "<nsw>"; 333 break; 334 default: 335 // Nothing to print for other nary expressions. 336 break; 337 } 338 return; 339 } 340 case scUDivExpr: { 341 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 342 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 343 return; 344 } 345 case scUnknown: { 346 const SCEVUnknown *U = cast<SCEVUnknown>(this); 347 Type *AllocTy; 348 if (U->isSizeOf(AllocTy)) { 349 OS << "sizeof(" << *AllocTy << ")"; 350 return; 351 } 352 if (U->isAlignOf(AllocTy)) { 353 OS << "alignof(" << *AllocTy << ")"; 354 return; 355 } 356 357 Type *CTy; 358 Constant *FieldNo; 359 if (U->isOffsetOf(CTy, FieldNo)) { 360 OS << "offsetof(" << *CTy << ", "; 361 FieldNo->printAsOperand(OS, false); 362 OS << ")"; 363 return; 364 } 365 366 // Otherwise just print it normally. 367 U->getValue()->printAsOperand(OS, false); 368 return; 369 } 370 case scCouldNotCompute: 371 OS << "***COULDNOTCOMPUTE***"; 372 return; 373 } 374 llvm_unreachable("Unknown SCEV kind!"); 375 } 376 377 Type *SCEV::getType() const { 378 switch (getSCEVType()) { 379 case scConstant: 380 return cast<SCEVConstant>(this)->getType(); 381 case scPtrToInt: 382 case scTruncate: 383 case scZeroExtend: 384 case scSignExtend: 385 return cast<SCEVCastExpr>(this)->getType(); 386 case scAddRecExpr: 387 return cast<SCEVAddRecExpr>(this)->getType(); 388 case scMulExpr: 389 return cast<SCEVMulExpr>(this)->getType(); 390 case scUMaxExpr: 391 case scSMaxExpr: 392 case scUMinExpr: 393 case scSMinExpr: 394 return cast<SCEVMinMaxExpr>(this)->getType(); 395 case scAddExpr: 396 return cast<SCEVAddExpr>(this)->getType(); 397 case scUDivExpr: 398 return cast<SCEVUDivExpr>(this)->getType(); 399 case scUnknown: 400 return cast<SCEVUnknown>(this)->getType(); 401 case scCouldNotCompute: 402 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 403 } 404 llvm_unreachable("Unknown SCEV kind!"); 405 } 406 407 bool SCEV::isZero() const { 408 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 409 return SC->getValue()->isZero(); 410 return false; 411 } 412 413 bool SCEV::isOne() const { 414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 415 return SC->getValue()->isOne(); 416 return false; 417 } 418 419 bool SCEV::isAllOnesValue() const { 420 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 421 return SC->getValue()->isMinusOne(); 422 return false; 423 } 424 425 bool SCEV::isNonConstantNegative() const { 426 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 427 if (!Mul) return false; 428 429 // If there is a constant factor, it will be first. 430 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 431 if (!SC) return false; 432 433 // Return true if the value is negative, this matches things like (-42 * V). 434 return SC->getAPInt().isNegative(); 435 } 436 437 SCEVCouldNotCompute::SCEVCouldNotCompute() : 438 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 439 440 bool SCEVCouldNotCompute::classof(const SCEV *S) { 441 return S->getSCEVType() == scCouldNotCompute; 442 } 443 444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 445 FoldingSetNodeID ID; 446 ID.AddInteger(scConstant); 447 ID.AddPointer(V); 448 void *IP = nullptr; 449 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 450 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 451 UniqueSCEVs.InsertNode(S, IP); 452 return S; 453 } 454 455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 456 return getConstant(ConstantInt::get(getContext(), Val)); 457 } 458 459 const SCEV * 460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 461 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 462 return getConstant(ConstantInt::get(ITy, V, isSigned)); 463 } 464 465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 466 const SCEV *op, Type *ty) 467 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 468 Operands[0] = op; 469 } 470 471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 472 Type *ITy) 473 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 474 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 475 "Must be a non-bit-width-changing pointer-to-integer cast!"); 476 } 477 478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 479 SCEVTypes SCEVTy, const SCEV *op, 480 Type *ty) 481 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 482 483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 484 Type *ty) 485 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 486 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 487 "Cannot truncate non-integer value!"); 488 } 489 490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 491 const SCEV *op, Type *ty) 492 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 493 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 494 "Cannot zero extend non-integer value!"); 495 } 496 497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 498 const SCEV *op, Type *ty) 499 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 500 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 501 "Cannot sign extend non-integer value!"); 502 } 503 504 void SCEVUnknown::deleted() { 505 // Clear this SCEVUnknown from various maps. 506 SE->forgetMemoizedResults(this); 507 508 // Remove this SCEVUnknown from the uniquing map. 509 SE->UniqueSCEVs.RemoveNode(this); 510 511 // Release the value. 512 setValPtr(nullptr); 513 } 514 515 void SCEVUnknown::allUsesReplacedWith(Value *New) { 516 // Remove this SCEVUnknown from the uniquing map. 517 SE->UniqueSCEVs.RemoveNode(this); 518 519 // Update this SCEVUnknown to point to the new value. This is needed 520 // because there may still be outstanding SCEVs which still point to 521 // this SCEVUnknown. 522 setValPtr(New); 523 } 524 525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 526 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 527 if (VCE->getOpcode() == Instruction::PtrToInt) 528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 529 if (CE->getOpcode() == Instruction::GetElementPtr && 530 CE->getOperand(0)->isNullValue() && 531 CE->getNumOperands() == 2) 532 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 533 if (CI->isOne()) { 534 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 535 return true; 536 } 537 538 return false; 539 } 540 541 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 542 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 543 if (VCE->getOpcode() == Instruction::PtrToInt) 544 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 545 if (CE->getOpcode() == Instruction::GetElementPtr && 546 CE->getOperand(0)->isNullValue()) { 547 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 548 if (StructType *STy = dyn_cast<StructType>(Ty)) 549 if (!STy->isPacked() && 550 CE->getNumOperands() == 3 && 551 CE->getOperand(1)->isNullValue()) { 552 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 553 if (CI->isOne() && 554 STy->getNumElements() == 2 && 555 STy->getElementType(0)->isIntegerTy(1)) { 556 AllocTy = STy->getElementType(1); 557 return true; 558 } 559 } 560 } 561 562 return false; 563 } 564 565 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 566 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 567 if (VCE->getOpcode() == Instruction::PtrToInt) 568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 569 if (CE->getOpcode() == Instruction::GetElementPtr && 570 CE->getNumOperands() == 3 && 571 CE->getOperand(0)->isNullValue() && 572 CE->getOperand(1)->isNullValue()) { 573 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 574 // Ignore vector types here so that ScalarEvolutionExpander doesn't 575 // emit getelementptrs that index into vectors. 576 if (Ty->isStructTy() || Ty->isArrayTy()) { 577 CTy = Ty; 578 FieldNo = CE->getOperand(2); 579 return true; 580 } 581 } 582 583 return false; 584 } 585 586 //===----------------------------------------------------------------------===// 587 // SCEV Utilities 588 //===----------------------------------------------------------------------===// 589 590 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 591 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 592 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 593 /// have been previously deemed to be "equally complex" by this routine. It is 594 /// intended to avoid exponential time complexity in cases like: 595 /// 596 /// %a = f(%x, %y) 597 /// %b = f(%a, %a) 598 /// %c = f(%b, %b) 599 /// 600 /// %d = f(%x, %y) 601 /// %e = f(%d, %d) 602 /// %f = f(%e, %e) 603 /// 604 /// CompareValueComplexity(%f, %c) 605 /// 606 /// Since we do not continue running this routine on expression trees once we 607 /// have seen unequal values, there is no need to track them in the cache. 608 static int 609 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 610 const LoopInfo *const LI, Value *LV, Value *RV, 611 unsigned Depth) { 612 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 613 return 0; 614 615 // Order pointer values after integer values. This helps SCEVExpander form 616 // GEPs. 617 bool LIsPointer = LV->getType()->isPointerTy(), 618 RIsPointer = RV->getType()->isPointerTy(); 619 if (LIsPointer != RIsPointer) 620 return (int)LIsPointer - (int)RIsPointer; 621 622 // Compare getValueID values. 623 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 624 if (LID != RID) 625 return (int)LID - (int)RID; 626 627 // Sort arguments by their position. 628 if (const auto *LA = dyn_cast<Argument>(LV)) { 629 const auto *RA = cast<Argument>(RV); 630 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 631 return (int)LArgNo - (int)RArgNo; 632 } 633 634 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 635 const auto *RGV = cast<GlobalValue>(RV); 636 637 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 638 auto LT = GV->getLinkage(); 639 return !(GlobalValue::isPrivateLinkage(LT) || 640 GlobalValue::isInternalLinkage(LT)); 641 }; 642 643 // Use the names to distinguish the two values, but only if the 644 // names are semantically important. 645 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 646 return LGV->getName().compare(RGV->getName()); 647 } 648 649 // For instructions, compare their loop depth, and their operand count. This 650 // is pretty loose. 651 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 652 const auto *RInst = cast<Instruction>(RV); 653 654 // Compare loop depths. 655 const BasicBlock *LParent = LInst->getParent(), 656 *RParent = RInst->getParent(); 657 if (LParent != RParent) { 658 unsigned LDepth = LI->getLoopDepth(LParent), 659 RDepth = LI->getLoopDepth(RParent); 660 if (LDepth != RDepth) 661 return (int)LDepth - (int)RDepth; 662 } 663 664 // Compare the number of operands. 665 unsigned LNumOps = LInst->getNumOperands(), 666 RNumOps = RInst->getNumOperands(); 667 if (LNumOps != RNumOps) 668 return (int)LNumOps - (int)RNumOps; 669 670 for (unsigned Idx : seq(0u, LNumOps)) { 671 int Result = 672 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 673 RInst->getOperand(Idx), Depth + 1); 674 if (Result != 0) 675 return Result; 676 } 677 } 678 679 EqCacheValue.unionSets(LV, RV); 680 return 0; 681 } 682 683 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 684 // than RHS, respectively. A three-way result allows recursive comparisons to be 685 // more efficient. 686 // If the max analysis depth was reached, return None, assuming we do not know 687 // if they are equivalent for sure. 688 static Optional<int> 689 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 690 EquivalenceClasses<const Value *> &EqCacheValue, 691 const LoopInfo *const LI, const SCEV *LHS, 692 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 693 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 694 if (LHS == RHS) 695 return 0; 696 697 // Primarily, sort the SCEVs by their getSCEVType(). 698 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 699 if (LType != RType) 700 return (int)LType - (int)RType; 701 702 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 703 return 0; 704 705 if (Depth > MaxSCEVCompareDepth) 706 return None; 707 708 // Aside from the getSCEVType() ordering, the particular ordering 709 // isn't very important except that it's beneficial to be consistent, 710 // so that (a + b) and (b + a) don't end up as different expressions. 711 switch (LType) { 712 case scUnknown: { 713 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 714 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 715 716 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 717 RU->getValue(), Depth + 1); 718 if (X == 0) 719 EqCacheSCEV.unionSets(LHS, RHS); 720 return X; 721 } 722 723 case scConstant: { 724 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 725 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 726 727 // Compare constant values. 728 const APInt &LA = LC->getAPInt(); 729 const APInt &RA = RC->getAPInt(); 730 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 731 if (LBitWidth != RBitWidth) 732 return (int)LBitWidth - (int)RBitWidth; 733 return LA.ult(RA) ? -1 : 1; 734 } 735 736 case scAddRecExpr: { 737 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 738 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 739 740 // There is always a dominance between two recs that are used by one SCEV, 741 // so we can safely sort recs by loop header dominance. We require such 742 // order in getAddExpr. 743 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 744 if (LLoop != RLoop) { 745 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 746 assert(LHead != RHead && "Two loops share the same header?"); 747 if (DT.dominates(LHead, RHead)) 748 return 1; 749 else 750 assert(DT.dominates(RHead, LHead) && 751 "No dominance between recurrences used by one SCEV?"); 752 return -1; 753 } 754 755 // Addrec complexity grows with operand count. 756 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 757 if (LNumOps != RNumOps) 758 return (int)LNumOps - (int)RNumOps; 759 760 // Lexicographically compare. 761 for (unsigned i = 0; i != LNumOps; ++i) { 762 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 763 LA->getOperand(i), RA->getOperand(i), DT, 764 Depth + 1); 765 if (X != 0) 766 return X; 767 } 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return 0; 770 } 771 772 case scAddExpr: 773 case scMulExpr: 774 case scSMaxExpr: 775 case scUMaxExpr: 776 case scSMinExpr: 777 case scUMinExpr: { 778 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 779 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 780 781 // Lexicographically compare n-ary expressions. 782 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 783 if (LNumOps != RNumOps) 784 return (int)LNumOps - (int)RNumOps; 785 786 for (unsigned i = 0; i != LNumOps; ++i) { 787 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 788 LC->getOperand(i), RC->getOperand(i), DT, 789 Depth + 1); 790 if (X != 0) 791 return X; 792 } 793 EqCacheSCEV.unionSets(LHS, RHS); 794 return 0; 795 } 796 797 case scUDivExpr: { 798 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 799 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 800 801 // Lexicographically compare udiv expressions. 802 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 803 RC->getLHS(), DT, Depth + 1); 804 if (X != 0) 805 return X; 806 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 807 RC->getRHS(), DT, Depth + 1); 808 if (X == 0) 809 EqCacheSCEV.unionSets(LHS, RHS); 810 return X; 811 } 812 813 case scPtrToInt: 814 case scTruncate: 815 case scZeroExtend: 816 case scSignExtend: { 817 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 818 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 819 820 // Compare cast expressions by operand. 821 auto X = 822 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 823 RC->getOperand(), DT, Depth + 1); 824 if (X == 0) 825 EqCacheSCEV.unionSets(LHS, RHS); 826 return X; 827 } 828 829 case scCouldNotCompute: 830 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 831 } 832 llvm_unreachable("Unknown SCEV kind!"); 833 } 834 835 /// Given a list of SCEV objects, order them by their complexity, and group 836 /// objects of the same complexity together by value. When this routine is 837 /// finished, we know that any duplicates in the vector are consecutive and that 838 /// complexity is monotonically increasing. 839 /// 840 /// Note that we go take special precautions to ensure that we get deterministic 841 /// results from this routine. In other words, we don't want the results of 842 /// this to depend on where the addresses of various SCEV objects happened to 843 /// land in memory. 844 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 845 LoopInfo *LI, DominatorTree &DT) { 846 if (Ops.size() < 2) return; // Noop 847 848 EquivalenceClasses<const SCEV *> EqCacheSCEV; 849 EquivalenceClasses<const Value *> EqCacheValue; 850 851 // Whether LHS has provably less complexity than RHS. 852 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 853 auto Complexity = 854 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 855 return Complexity && *Complexity < 0; 856 }; 857 if (Ops.size() == 2) { 858 // This is the common case, which also happens to be trivially simple. 859 // Special case it. 860 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 861 if (IsLessComplex(RHS, LHS)) 862 std::swap(LHS, RHS); 863 return; 864 } 865 866 // Do the rough sort by complexity. 867 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 868 return IsLessComplex(LHS, RHS); 869 }); 870 871 // Now that we are sorted by complexity, group elements of the same 872 // complexity. Note that this is, at worst, N^2, but the vector is likely to 873 // be extremely short in practice. Note that we take this approach because we 874 // do not want to depend on the addresses of the objects we are grouping. 875 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 876 const SCEV *S = Ops[i]; 877 unsigned Complexity = S->getSCEVType(); 878 879 // If there are any objects of the same complexity and same value as this 880 // one, group them. 881 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 882 if (Ops[j] == S) { // Found a duplicate. 883 // Move it to immediately after i'th element. 884 std::swap(Ops[i+1], Ops[j]); 885 ++i; // no need to rescan it. 886 if (i == e-2) return; // Done! 887 } 888 } 889 } 890 } 891 892 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 893 /// least HugeExprThreshold nodes). 894 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 895 return any_of(Ops, [](const SCEV *S) { 896 return S->getExpressionSize() >= HugeExprThreshold; 897 }); 898 } 899 900 //===----------------------------------------------------------------------===// 901 // Simple SCEV method implementations 902 //===----------------------------------------------------------------------===// 903 904 /// Compute BC(It, K). The result has width W. Assume, K > 0. 905 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 906 ScalarEvolution &SE, 907 Type *ResultTy) { 908 // Handle the simplest case efficiently. 909 if (K == 1) 910 return SE.getTruncateOrZeroExtend(It, ResultTy); 911 912 // We are using the following formula for BC(It, K): 913 // 914 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 915 // 916 // Suppose, W is the bitwidth of the return value. We must be prepared for 917 // overflow. Hence, we must assure that the result of our computation is 918 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 919 // safe in modular arithmetic. 920 // 921 // However, this code doesn't use exactly that formula; the formula it uses 922 // is something like the following, where T is the number of factors of 2 in 923 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 924 // exponentiation: 925 // 926 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 927 // 928 // This formula is trivially equivalent to the previous formula. However, 929 // this formula can be implemented much more efficiently. The trick is that 930 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 931 // arithmetic. To do exact division in modular arithmetic, all we have 932 // to do is multiply by the inverse. Therefore, this step can be done at 933 // width W. 934 // 935 // The next issue is how to safely do the division by 2^T. The way this 936 // is done is by doing the multiplication step at a width of at least W + T 937 // bits. This way, the bottom W+T bits of the product are accurate. Then, 938 // when we perform the division by 2^T (which is equivalent to a right shift 939 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 940 // truncated out after the division by 2^T. 941 // 942 // In comparison to just directly using the first formula, this technique 943 // is much more efficient; using the first formula requires W * K bits, 944 // but this formula less than W + K bits. Also, the first formula requires 945 // a division step, whereas this formula only requires multiplies and shifts. 946 // 947 // It doesn't matter whether the subtraction step is done in the calculation 948 // width or the input iteration count's width; if the subtraction overflows, 949 // the result must be zero anyway. We prefer here to do it in the width of 950 // the induction variable because it helps a lot for certain cases; CodeGen 951 // isn't smart enough to ignore the overflow, which leads to much less 952 // efficient code if the width of the subtraction is wider than the native 953 // register width. 954 // 955 // (It's possible to not widen at all by pulling out factors of 2 before 956 // the multiplication; for example, K=2 can be calculated as 957 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 958 // extra arithmetic, so it's not an obvious win, and it gets 959 // much more complicated for K > 3.) 960 961 // Protection from insane SCEVs; this bound is conservative, 962 // but it probably doesn't matter. 963 if (K > 1000) 964 return SE.getCouldNotCompute(); 965 966 unsigned W = SE.getTypeSizeInBits(ResultTy); 967 968 // Calculate K! / 2^T and T; we divide out the factors of two before 969 // multiplying for calculating K! / 2^T to avoid overflow. 970 // Other overflow doesn't matter because we only care about the bottom 971 // W bits of the result. 972 APInt OddFactorial(W, 1); 973 unsigned T = 1; 974 for (unsigned i = 3; i <= K; ++i) { 975 APInt Mult(W, i); 976 unsigned TwoFactors = Mult.countTrailingZeros(); 977 T += TwoFactors; 978 Mult.lshrInPlace(TwoFactors); 979 OddFactorial *= Mult; 980 } 981 982 // We need at least W + T bits for the multiplication step 983 unsigned CalculationBits = W + T; 984 985 // Calculate 2^T, at width T+W. 986 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 987 988 // Calculate the multiplicative inverse of K! / 2^T; 989 // this multiplication factor will perform the exact division by 990 // K! / 2^T. 991 APInt Mod = APInt::getSignedMinValue(W+1); 992 APInt MultiplyFactor = OddFactorial.zext(W+1); 993 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 994 MultiplyFactor = MultiplyFactor.trunc(W); 995 996 // Calculate the product, at width T+W 997 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 998 CalculationBits); 999 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1000 for (unsigned i = 1; i != K; ++i) { 1001 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1002 Dividend = SE.getMulExpr(Dividend, 1003 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1004 } 1005 1006 // Divide by 2^T 1007 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1008 1009 // Truncate the result, and divide by K! / 2^T. 1010 1011 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1012 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1013 } 1014 1015 /// Return the value of this chain of recurrences at the specified iteration 1016 /// number. We can evaluate this recurrence by multiplying each element in the 1017 /// chain by the binomial coefficient corresponding to it. In other words, we 1018 /// can evaluate {A,+,B,+,C,+,D} as: 1019 /// 1020 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1021 /// 1022 /// where BC(It, k) stands for binomial coefficient. 1023 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1024 ScalarEvolution &SE) const { 1025 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1026 } 1027 1028 const SCEV * 1029 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1030 const SCEV *It, ScalarEvolution &SE) { 1031 assert(Operands.size() > 0); 1032 const SCEV *Result = Operands[0]; 1033 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1034 // The computation is correct in the face of overflow provided that the 1035 // multiplication is performed _after_ the evaluation of the binomial 1036 // coefficient. 1037 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1038 if (isa<SCEVCouldNotCompute>(Coeff)) 1039 return Coeff; 1040 1041 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1042 } 1043 return Result; 1044 } 1045 1046 //===----------------------------------------------------------------------===// 1047 // SCEV Expression folder implementations 1048 //===----------------------------------------------------------------------===// 1049 1050 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1051 unsigned Depth) { 1052 assert(Depth <= 1 && 1053 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1054 1055 // We could be called with an integer-typed operands during SCEV rewrites. 1056 // Since the operand is an integer already, just perform zext/trunc/self cast. 1057 if (!Op->getType()->isPointerTy()) 1058 return Op; 1059 1060 // What would be an ID for such a SCEV cast expression? 1061 FoldingSetNodeID ID; 1062 ID.AddInteger(scPtrToInt); 1063 ID.AddPointer(Op); 1064 1065 void *IP = nullptr; 1066 1067 // Is there already an expression for such a cast? 1068 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1069 return S; 1070 1071 // It isn't legal for optimizations to construct new ptrtoint expressions 1072 // for non-integral pointers. 1073 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1074 return getCouldNotCompute(); 1075 1076 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1077 1078 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1079 // is sufficiently wide to represent all possible pointer values. 1080 // We could theoretically teach SCEV to truncate wider pointers, but 1081 // that isn't implemented for now. 1082 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1083 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1084 return getCouldNotCompute(); 1085 1086 // If not, is this expression something we can't reduce any further? 1087 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1088 // Perform some basic constant folding. If the operand of the ptr2int cast 1089 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1090 // left as-is), but produce a zero constant. 1091 // NOTE: We could handle a more general case, but lack motivational cases. 1092 if (isa<ConstantPointerNull>(U->getValue())) 1093 return getZero(IntPtrTy); 1094 1095 // Create an explicit cast node. 1096 // We can reuse the existing insert position since if we get here, 1097 // we won't have made any changes which would invalidate it. 1098 SCEV *S = new (SCEVAllocator) 1099 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1100 UniqueSCEVs.InsertNode(S, IP); 1101 addToLoopUseLists(S); 1102 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 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 addToLoopUseLists(S); 2918 } 2919 setNoWrapFlags(S, Flags); 2920 return S; 2921 } 2922 2923 const SCEV * 2924 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2925 SCEV::NoWrapFlags Flags) { 2926 FoldingSetNodeID ID; 2927 ID.AddInteger(scMulExpr); 2928 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2929 ID.AddPointer(Ops[i]); 2930 void *IP = nullptr; 2931 SCEVMulExpr *S = 2932 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2933 if (!S) { 2934 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2935 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2936 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2937 O, Ops.size()); 2938 UniqueSCEVs.InsertNode(S, IP); 2939 addToLoopUseLists(S); 2940 } 2941 S->setNoWrapFlags(Flags); 2942 return S; 2943 } 2944 2945 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2946 uint64_t k = i*j; 2947 if (j > 1 && k / j != i) Overflow = true; 2948 return k; 2949 } 2950 2951 /// Compute the result of "n choose k", the binomial coefficient. If an 2952 /// intermediate computation overflows, Overflow will be set and the return will 2953 /// be garbage. Overflow is not cleared on absence of overflow. 2954 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2955 // We use the multiplicative formula: 2956 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2957 // At each iteration, we take the n-th term of the numeral and divide by the 2958 // (k-n)th term of the denominator. This division will always produce an 2959 // integral result, and helps reduce the chance of overflow in the 2960 // intermediate computations. However, we can still overflow even when the 2961 // final result would fit. 2962 2963 if (n == 0 || n == k) return 1; 2964 if (k > n) return 0; 2965 2966 if (k > n/2) 2967 k = n-k; 2968 2969 uint64_t r = 1; 2970 for (uint64_t i = 1; i <= k; ++i) { 2971 r = umul_ov(r, n-(i-1), Overflow); 2972 r /= i; 2973 } 2974 return r; 2975 } 2976 2977 /// Determine if any of the operands in this SCEV are a constant or if 2978 /// any of the add or multiply expressions in this SCEV contain a constant. 2979 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2980 struct FindConstantInAddMulChain { 2981 bool FoundConstant = false; 2982 2983 bool follow(const SCEV *S) { 2984 FoundConstant |= isa<SCEVConstant>(S); 2985 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2986 } 2987 2988 bool isDone() const { 2989 return FoundConstant; 2990 } 2991 }; 2992 2993 FindConstantInAddMulChain F; 2994 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2995 ST.visitAll(StartExpr); 2996 return F.FoundConstant; 2997 } 2998 2999 /// Get a canonical multiply expression, or something simpler if possible. 3000 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3001 SCEV::NoWrapFlags OrigFlags, 3002 unsigned Depth) { 3003 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3004 "only nuw or nsw allowed"); 3005 assert(!Ops.empty() && "Cannot get empty mul!"); 3006 if (Ops.size() == 1) return Ops[0]; 3007 #ifndef NDEBUG 3008 Type *ETy = Ops[0]->getType(); 3009 assert(!ETy->isPointerTy()); 3010 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3011 assert(Ops[i]->getType() == ETy && 3012 "SCEVMulExpr operand types don't match!"); 3013 #endif 3014 3015 // Sort by complexity, this groups all similar expression types together. 3016 GroupByComplexity(Ops, &LI, DT); 3017 3018 // If there are any constants, fold them together. 3019 unsigned Idx = 0; 3020 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3021 ++Idx; 3022 assert(Idx < Ops.size()); 3023 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3024 // We found two constants, fold them together! 3025 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3026 if (Ops.size() == 2) return Ops[0]; 3027 Ops.erase(Ops.begin()+1); // Erase the folded element 3028 LHSC = cast<SCEVConstant>(Ops[0]); 3029 } 3030 3031 // If we have a multiply of zero, it will always be zero. 3032 if (LHSC->getValue()->isZero()) 3033 return LHSC; 3034 3035 // If we are left with a constant one being multiplied, strip it off. 3036 if (LHSC->getValue()->isOne()) { 3037 Ops.erase(Ops.begin()); 3038 --Idx; 3039 } 3040 3041 if (Ops.size() == 1) 3042 return Ops[0]; 3043 } 3044 3045 // Delay expensive flag strengthening until necessary. 3046 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3047 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3048 }; 3049 3050 // Limit recursion calls depth. 3051 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3052 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3053 3054 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3055 // Don't strengthen flags if we have no new information. 3056 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3057 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3058 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3059 return S; 3060 } 3061 3062 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3063 if (Ops.size() == 2) { 3064 // C1*(C2+V) -> C1*C2 + C1*V 3065 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3066 // If any of Add's ops are Adds or Muls with a constant, apply this 3067 // transformation as well. 3068 // 3069 // TODO: There are some cases where this transformation is not 3070 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3071 // this transformation should be narrowed down. 3072 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3073 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3074 SCEV::FlagAnyWrap, Depth + 1), 3075 getMulExpr(LHSC, Add->getOperand(1), 3076 SCEV::FlagAnyWrap, Depth + 1), 3077 SCEV::FlagAnyWrap, Depth + 1); 3078 3079 if (Ops[0]->isAllOnesValue()) { 3080 // If we have a mul by -1 of an add, try distributing the -1 among the 3081 // add operands. 3082 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3083 SmallVector<const SCEV *, 4> NewOps; 3084 bool AnyFolded = false; 3085 for (const SCEV *AddOp : Add->operands()) { 3086 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3087 Depth + 1); 3088 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3089 NewOps.push_back(Mul); 3090 } 3091 if (AnyFolded) 3092 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3093 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3094 // Negation preserves a recurrence's no self-wrap property. 3095 SmallVector<const SCEV *, 4> Operands; 3096 for (const SCEV *AddRecOp : AddRec->operands()) 3097 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3098 Depth + 1)); 3099 3100 return getAddRecExpr(Operands, AddRec->getLoop(), 3101 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3102 } 3103 } 3104 } 3105 } 3106 3107 // Skip over the add expression until we get to a multiply. 3108 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3109 ++Idx; 3110 3111 // If there are mul operands inline them all into this expression. 3112 if (Idx < Ops.size()) { 3113 bool DeletedMul = false; 3114 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3115 if (Ops.size() > MulOpsInlineThreshold) 3116 break; 3117 // If we have an mul, expand the mul operands onto the end of the 3118 // operands list. 3119 Ops.erase(Ops.begin()+Idx); 3120 Ops.append(Mul->op_begin(), Mul->op_end()); 3121 DeletedMul = true; 3122 } 3123 3124 // If we deleted at least one mul, we added operands to the end of the 3125 // list, and they are not necessarily sorted. Recurse to resort and 3126 // resimplify any operands we just acquired. 3127 if (DeletedMul) 3128 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3129 } 3130 3131 // If there are any add recurrences in the operands list, see if any other 3132 // added values are loop invariant. If so, we can fold them into the 3133 // recurrence. 3134 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3135 ++Idx; 3136 3137 // Scan over all recurrences, trying to fold loop invariants into them. 3138 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3139 // Scan all of the other operands to this mul and add them to the vector 3140 // if they are loop invariant w.r.t. the recurrence. 3141 SmallVector<const SCEV *, 8> LIOps; 3142 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3143 const Loop *AddRecLoop = AddRec->getLoop(); 3144 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3145 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3146 LIOps.push_back(Ops[i]); 3147 Ops.erase(Ops.begin()+i); 3148 --i; --e; 3149 } 3150 3151 // If we found some loop invariants, fold them into the recurrence. 3152 if (!LIOps.empty()) { 3153 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3154 SmallVector<const SCEV *, 4> NewOps; 3155 NewOps.reserve(AddRec->getNumOperands()); 3156 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3157 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3158 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3159 SCEV::FlagAnyWrap, Depth + 1)); 3160 3161 // Build the new addrec. Propagate the NUW and NSW flags if both the 3162 // outer mul and the inner addrec are guaranteed to have no overflow. 3163 // 3164 // No self-wrap cannot be guaranteed after changing the step size, but 3165 // will be inferred if either NUW or NSW is true. 3166 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3167 const SCEV *NewRec = getAddRecExpr( 3168 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3169 3170 // If all of the other operands were loop invariant, we are done. 3171 if (Ops.size() == 1) return NewRec; 3172 3173 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3174 for (unsigned i = 0;; ++i) 3175 if (Ops[i] == AddRec) { 3176 Ops[i] = NewRec; 3177 break; 3178 } 3179 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3180 } 3181 3182 // Okay, if there weren't any loop invariants to be folded, check to see 3183 // if there are multiple AddRec's with the same loop induction variable 3184 // being multiplied together. If so, we can fold them. 3185 3186 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3187 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3188 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3189 // ]]],+,...up to x=2n}. 3190 // Note that the arguments to choose() are always integers with values 3191 // known at compile time, never SCEV objects. 3192 // 3193 // The implementation avoids pointless extra computations when the two 3194 // addrec's are of different length (mathematically, it's equivalent to 3195 // an infinite stream of zeros on the right). 3196 bool OpsModified = false; 3197 for (unsigned OtherIdx = Idx+1; 3198 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3199 ++OtherIdx) { 3200 const SCEVAddRecExpr *OtherAddRec = 3201 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3202 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3203 continue; 3204 3205 // Limit max number of arguments to avoid creation of unreasonably big 3206 // SCEVAddRecs with very complex operands. 3207 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3208 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3209 continue; 3210 3211 bool Overflow = false; 3212 Type *Ty = AddRec->getType(); 3213 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3214 SmallVector<const SCEV*, 7> AddRecOps; 3215 for (int x = 0, xe = AddRec->getNumOperands() + 3216 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3217 SmallVector <const SCEV *, 7> SumOps; 3218 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3219 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3220 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3221 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3222 z < ze && !Overflow; ++z) { 3223 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3224 uint64_t Coeff; 3225 if (LargerThan64Bits) 3226 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3227 else 3228 Coeff = Coeff1*Coeff2; 3229 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3230 const SCEV *Term1 = AddRec->getOperand(y-z); 3231 const SCEV *Term2 = OtherAddRec->getOperand(z); 3232 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3233 SCEV::FlagAnyWrap, Depth + 1)); 3234 } 3235 } 3236 if (SumOps.empty()) 3237 SumOps.push_back(getZero(Ty)); 3238 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3239 } 3240 if (!Overflow) { 3241 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3242 SCEV::FlagAnyWrap); 3243 if (Ops.size() == 2) return NewAddRec; 3244 Ops[Idx] = NewAddRec; 3245 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3246 OpsModified = true; 3247 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3248 if (!AddRec) 3249 break; 3250 } 3251 } 3252 if (OpsModified) 3253 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3254 3255 // Otherwise couldn't fold anything into this recurrence. Move onto the 3256 // next one. 3257 } 3258 3259 // Okay, it looks like we really DO need an mul expr. Check to see if we 3260 // already have one, otherwise create a new one. 3261 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3262 } 3263 3264 /// Represents an unsigned remainder expression based on unsigned division. 3265 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3266 const SCEV *RHS) { 3267 assert(getEffectiveSCEVType(LHS->getType()) == 3268 getEffectiveSCEVType(RHS->getType()) && 3269 "SCEVURemExpr operand types don't match!"); 3270 3271 // Short-circuit easy cases 3272 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3273 // If constant is one, the result is trivial 3274 if (RHSC->getValue()->isOne()) 3275 return getZero(LHS->getType()); // X urem 1 --> 0 3276 3277 // If constant is a power of two, fold into a zext(trunc(LHS)). 3278 if (RHSC->getAPInt().isPowerOf2()) { 3279 Type *FullTy = LHS->getType(); 3280 Type *TruncTy = 3281 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3282 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3283 } 3284 } 3285 3286 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3287 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3288 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3289 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3290 } 3291 3292 /// Get a canonical unsigned division expression, or something simpler if 3293 /// possible. 3294 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3295 const SCEV *RHS) { 3296 assert(!LHS->getType()->isPointerTy() && 3297 "SCEVUDivExpr operand can't be pointer!"); 3298 assert(LHS->getType() == RHS->getType() && 3299 "SCEVUDivExpr operand types don't match!"); 3300 3301 FoldingSetNodeID ID; 3302 ID.AddInteger(scUDivExpr); 3303 ID.AddPointer(LHS); 3304 ID.AddPointer(RHS); 3305 void *IP = nullptr; 3306 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3307 return S; 3308 3309 // 0 udiv Y == 0 3310 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3311 if (LHSC->getValue()->isZero()) 3312 return LHS; 3313 3314 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3315 if (RHSC->getValue()->isOne()) 3316 return LHS; // X udiv 1 --> x 3317 // If the denominator is zero, the result of the udiv is undefined. Don't 3318 // try to analyze it, because the resolution chosen here may differ from 3319 // the resolution chosen in other parts of the compiler. 3320 if (!RHSC->getValue()->isZero()) { 3321 // Determine if the division can be folded into the operands of 3322 // its operands. 3323 // TODO: Generalize this to non-constants by using known-bits information. 3324 Type *Ty = LHS->getType(); 3325 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3326 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3327 // For non-power-of-two values, effectively round the value up to the 3328 // nearest power of two. 3329 if (!RHSC->getAPInt().isPowerOf2()) 3330 ++MaxShiftAmt; 3331 IntegerType *ExtTy = 3332 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3333 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3334 if (const SCEVConstant *Step = 3335 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3336 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3337 const APInt &StepInt = Step->getAPInt(); 3338 const APInt &DivInt = RHSC->getAPInt(); 3339 if (!StepInt.urem(DivInt) && 3340 getZeroExtendExpr(AR, ExtTy) == 3341 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3342 getZeroExtendExpr(Step, ExtTy), 3343 AR->getLoop(), SCEV::FlagAnyWrap)) { 3344 SmallVector<const SCEV *, 4> Operands; 3345 for (const SCEV *Op : AR->operands()) 3346 Operands.push_back(getUDivExpr(Op, RHS)); 3347 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3348 } 3349 /// Get a canonical UDivExpr for a recurrence. 3350 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3351 // We can currently only fold X%N if X is constant. 3352 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3353 if (StartC && !DivInt.urem(StepInt) && 3354 getZeroExtendExpr(AR, ExtTy) == 3355 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3356 getZeroExtendExpr(Step, ExtTy), 3357 AR->getLoop(), SCEV::FlagAnyWrap)) { 3358 const APInt &StartInt = StartC->getAPInt(); 3359 const APInt &StartRem = StartInt.urem(StepInt); 3360 if (StartRem != 0) { 3361 const SCEV *NewLHS = 3362 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3363 AR->getLoop(), SCEV::FlagNW); 3364 if (LHS != NewLHS) { 3365 LHS = NewLHS; 3366 3367 // Reset the ID to include the new LHS, and check if it is 3368 // already cached. 3369 ID.clear(); 3370 ID.AddInteger(scUDivExpr); 3371 ID.AddPointer(LHS); 3372 ID.AddPointer(RHS); 3373 IP = nullptr; 3374 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3375 return S; 3376 } 3377 } 3378 } 3379 } 3380 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3381 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3382 SmallVector<const SCEV *, 4> Operands; 3383 for (const SCEV *Op : M->operands()) 3384 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3385 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3386 // Find an operand that's safely divisible. 3387 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3388 const SCEV *Op = M->getOperand(i); 3389 const SCEV *Div = getUDivExpr(Op, RHSC); 3390 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3391 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3392 Operands[i] = Div; 3393 return getMulExpr(Operands); 3394 } 3395 } 3396 } 3397 3398 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3399 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3400 if (auto *DivisorConstant = 3401 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3402 bool Overflow = false; 3403 APInt NewRHS = 3404 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3405 if (Overflow) { 3406 return getConstant(RHSC->getType(), 0, false); 3407 } 3408 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3409 } 3410 } 3411 3412 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3413 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3414 SmallVector<const SCEV *, 4> Operands; 3415 for (const SCEV *Op : A->operands()) 3416 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3417 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3418 Operands.clear(); 3419 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3420 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3421 if (isa<SCEVUDivExpr>(Op) || 3422 getMulExpr(Op, RHS) != A->getOperand(i)) 3423 break; 3424 Operands.push_back(Op); 3425 } 3426 if (Operands.size() == A->getNumOperands()) 3427 return getAddExpr(Operands); 3428 } 3429 } 3430 3431 // Fold if both operands are constant. 3432 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3433 Constant *LHSCV = LHSC->getValue(); 3434 Constant *RHSCV = RHSC->getValue(); 3435 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3436 RHSCV))); 3437 } 3438 } 3439 } 3440 3441 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3442 // changes). Make sure we get a new one. 3443 IP = nullptr; 3444 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3445 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3446 LHS, RHS); 3447 UniqueSCEVs.InsertNode(S, IP); 3448 addToLoopUseLists(S); 3449 return S; 3450 } 3451 3452 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3453 APInt A = C1->getAPInt().abs(); 3454 APInt B = C2->getAPInt().abs(); 3455 uint32_t ABW = A.getBitWidth(); 3456 uint32_t BBW = B.getBitWidth(); 3457 3458 if (ABW > BBW) 3459 B = B.zext(ABW); 3460 else if (ABW < BBW) 3461 A = A.zext(BBW); 3462 3463 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3464 } 3465 3466 /// Get a canonical unsigned division expression, or something simpler if 3467 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3468 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3469 /// it's not exact because the udiv may be clearing bits. 3470 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3471 const SCEV *RHS) { 3472 // TODO: we could try to find factors in all sorts of things, but for now we 3473 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3474 // end of this file for inspiration. 3475 3476 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3477 if (!Mul || !Mul->hasNoUnsignedWrap()) 3478 return getUDivExpr(LHS, RHS); 3479 3480 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3481 // If the mulexpr multiplies by a constant, then that constant must be the 3482 // first element of the mulexpr. 3483 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3484 if (LHSCst == RHSCst) { 3485 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3486 return getMulExpr(Operands); 3487 } 3488 3489 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3490 // that there's a factor provided by one of the other terms. We need to 3491 // check. 3492 APInt Factor = gcd(LHSCst, RHSCst); 3493 if (!Factor.isIntN(1)) { 3494 LHSCst = 3495 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3496 RHSCst = 3497 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3498 SmallVector<const SCEV *, 2> Operands; 3499 Operands.push_back(LHSCst); 3500 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3501 LHS = getMulExpr(Operands); 3502 RHS = RHSCst; 3503 Mul = dyn_cast<SCEVMulExpr>(LHS); 3504 if (!Mul) 3505 return getUDivExactExpr(LHS, RHS); 3506 } 3507 } 3508 } 3509 3510 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3511 if (Mul->getOperand(i) == RHS) { 3512 SmallVector<const SCEV *, 2> Operands; 3513 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3514 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3515 return getMulExpr(Operands); 3516 } 3517 } 3518 3519 return getUDivExpr(LHS, RHS); 3520 } 3521 3522 /// Get an add recurrence expression for the specified loop. Simplify the 3523 /// expression as much as possible. 3524 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3525 const Loop *L, 3526 SCEV::NoWrapFlags Flags) { 3527 SmallVector<const SCEV *, 4> Operands; 3528 Operands.push_back(Start); 3529 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3530 if (StepChrec->getLoop() == L) { 3531 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3532 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3533 } 3534 3535 Operands.push_back(Step); 3536 return getAddRecExpr(Operands, L, Flags); 3537 } 3538 3539 /// Get an add recurrence expression for the specified loop. Simplify the 3540 /// expression as much as possible. 3541 const SCEV * 3542 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3543 const Loop *L, SCEV::NoWrapFlags Flags) { 3544 if (Operands.size() == 1) return Operands[0]; 3545 #ifndef NDEBUG 3546 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3547 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3548 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3549 "SCEVAddRecExpr operand types don't match!"); 3550 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3551 } 3552 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3553 assert(isLoopInvariant(Operands[i], L) && 3554 "SCEVAddRecExpr operand is not loop-invariant!"); 3555 #endif 3556 3557 if (Operands.back()->isZero()) { 3558 Operands.pop_back(); 3559 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3560 } 3561 3562 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3563 // use that information to infer NUW and NSW flags. However, computing a 3564 // BE count requires calling getAddRecExpr, so we may not yet have a 3565 // meaningful BE count at this point (and if we don't, we'd be stuck 3566 // with a SCEVCouldNotCompute as the cached BE count). 3567 3568 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3569 3570 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3571 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3572 const Loop *NestedLoop = NestedAR->getLoop(); 3573 if (L->contains(NestedLoop) 3574 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3575 : (!NestedLoop->contains(L) && 3576 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3577 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3578 Operands[0] = NestedAR->getStart(); 3579 // AddRecs require their operands be loop-invariant with respect to their 3580 // loops. Don't perform this transformation if it would break this 3581 // requirement. 3582 bool AllInvariant = all_of( 3583 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3584 3585 if (AllInvariant) { 3586 // Create a recurrence for the outer loop with the same step size. 3587 // 3588 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3589 // inner recurrence has the same property. 3590 SCEV::NoWrapFlags OuterFlags = 3591 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3592 3593 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3594 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3595 return isLoopInvariant(Op, NestedLoop); 3596 }); 3597 3598 if (AllInvariant) { 3599 // Ok, both add recurrences are valid after the transformation. 3600 // 3601 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3602 // the outer recurrence has the same property. 3603 SCEV::NoWrapFlags InnerFlags = 3604 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3605 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3606 } 3607 } 3608 // Reset Operands to its original state. 3609 Operands[0] = NestedAR; 3610 } 3611 } 3612 3613 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3614 // already have one, otherwise create a new one. 3615 return getOrCreateAddRecExpr(Operands, L, Flags); 3616 } 3617 3618 const SCEV * 3619 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3620 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3621 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3622 // getSCEV(Base)->getType() has the same address space as Base->getType() 3623 // because SCEV::getType() preserves the address space. 3624 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3625 const bool AssumeInBoundsFlags = [&]() { 3626 if (!GEP->isInBounds()) 3627 return false; 3628 3629 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3630 // but to do that, we have to ensure that said flag is valid in the entire 3631 // defined scope of the SCEV. 3632 auto *GEPI = dyn_cast<Instruction>(GEP); 3633 // TODO: non-instructions have global scope. We might be able to prove 3634 // some global scope cases 3635 return GEPI && isSCEVExprNeverPoison(GEPI); 3636 }(); 3637 3638 SCEV::NoWrapFlags OffsetWrap = 3639 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3640 3641 Type *CurTy = GEP->getType(); 3642 bool FirstIter = true; 3643 SmallVector<const SCEV *, 4> Offsets; 3644 for (const SCEV *IndexExpr : IndexExprs) { 3645 // Compute the (potentially symbolic) offset in bytes for this index. 3646 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3647 // For a struct, add the member offset. 3648 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3649 unsigned FieldNo = Index->getZExtValue(); 3650 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3651 Offsets.push_back(FieldOffset); 3652 3653 // Update CurTy to the type of the field at Index. 3654 CurTy = STy->getTypeAtIndex(Index); 3655 } else { 3656 // Update CurTy to its element type. 3657 if (FirstIter) { 3658 assert(isa<PointerType>(CurTy) && 3659 "The first index of a GEP indexes a pointer"); 3660 CurTy = GEP->getSourceElementType(); 3661 FirstIter = false; 3662 } else { 3663 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3664 } 3665 // For an array, add the element offset, explicitly scaled. 3666 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3667 // Getelementptr indices are signed. 3668 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3669 3670 // Multiply the index by the element size to compute the element offset. 3671 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3672 Offsets.push_back(LocalOffset); 3673 } 3674 } 3675 3676 // Handle degenerate case of GEP without offsets. 3677 if (Offsets.empty()) 3678 return BaseExpr; 3679 3680 // Add the offsets together, assuming nsw if inbounds. 3681 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3682 // Add the base address and the offset. We cannot use the nsw flag, as the 3683 // base address is unsigned. However, if we know that the offset is 3684 // non-negative, we can use nuw. 3685 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3686 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3687 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3688 assert(BaseExpr->getType() == GEPExpr->getType() && 3689 "GEP should not change type mid-flight."); 3690 return GEPExpr; 3691 } 3692 3693 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3694 ArrayRef<const SCEV *> Ops) { 3695 FoldingSetNodeID ID; 3696 ID.AddInteger(SCEVType); 3697 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3698 ID.AddPointer(Ops[i]); 3699 void *IP = nullptr; 3700 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3701 } 3702 3703 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3704 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3705 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3706 } 3707 3708 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3709 SmallVectorImpl<const SCEV *> &Ops) { 3710 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3711 if (Ops.size() == 1) return Ops[0]; 3712 #ifndef NDEBUG 3713 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3714 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3715 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3716 "Operand types don't match!"); 3717 assert(Ops[0]->getType()->isPointerTy() == 3718 Ops[i]->getType()->isPointerTy() && 3719 "min/max should be consistently pointerish"); 3720 } 3721 #endif 3722 3723 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3724 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3725 3726 // Sort by complexity, this groups all similar expression types together. 3727 GroupByComplexity(Ops, &LI, DT); 3728 3729 // Check if we have created the same expression before. 3730 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3731 return S; 3732 } 3733 3734 // If there are any constants, fold them together. 3735 unsigned Idx = 0; 3736 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3737 ++Idx; 3738 assert(Idx < Ops.size()); 3739 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3740 if (Kind == scSMaxExpr) 3741 return APIntOps::smax(LHS, RHS); 3742 else if (Kind == scSMinExpr) 3743 return APIntOps::smin(LHS, RHS); 3744 else if (Kind == scUMaxExpr) 3745 return APIntOps::umax(LHS, RHS); 3746 else if (Kind == scUMinExpr) 3747 return APIntOps::umin(LHS, RHS); 3748 llvm_unreachable("Unknown SCEV min/max opcode"); 3749 }; 3750 3751 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3752 // We found two constants, fold them together! 3753 ConstantInt *Fold = ConstantInt::get( 3754 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3755 Ops[0] = getConstant(Fold); 3756 Ops.erase(Ops.begin()+1); // Erase the folded element 3757 if (Ops.size() == 1) return Ops[0]; 3758 LHSC = cast<SCEVConstant>(Ops[0]); 3759 } 3760 3761 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3762 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3763 3764 if (IsMax ? IsMinV : IsMaxV) { 3765 // If we are left with a constant minimum(/maximum)-int, strip it off. 3766 Ops.erase(Ops.begin()); 3767 --Idx; 3768 } else if (IsMax ? IsMaxV : IsMinV) { 3769 // If we have a max(/min) with a constant maximum(/minimum)-int, 3770 // it will always be the extremum. 3771 return LHSC; 3772 } 3773 3774 if (Ops.size() == 1) return Ops[0]; 3775 } 3776 3777 // Find the first operation of the same kind 3778 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3779 ++Idx; 3780 3781 // Check to see if one of the operands is of the same kind. If so, expand its 3782 // operands onto our operand list, and recurse to simplify. 3783 if (Idx < Ops.size()) { 3784 bool DeletedAny = false; 3785 while (Ops[Idx]->getSCEVType() == Kind) { 3786 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3787 Ops.erase(Ops.begin()+Idx); 3788 Ops.append(SMME->op_begin(), SMME->op_end()); 3789 DeletedAny = true; 3790 } 3791 3792 if (DeletedAny) 3793 return getMinMaxExpr(Kind, Ops); 3794 } 3795 3796 // Okay, check to see if the same value occurs in the operand list twice. If 3797 // so, delete one. Since we sorted the list, these values are required to 3798 // be adjacent. 3799 llvm::CmpInst::Predicate GEPred = 3800 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3801 llvm::CmpInst::Predicate LEPred = 3802 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3803 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3804 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3805 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3806 if (Ops[i] == Ops[i + 1] || 3807 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3808 // X op Y op Y --> X op Y 3809 // X op Y --> X, if we know X, Y are ordered appropriately 3810 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3811 --i; 3812 --e; 3813 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3814 Ops[i + 1])) { 3815 // X op Y --> Y, if we know X, Y are ordered appropriately 3816 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3817 --i; 3818 --e; 3819 } 3820 } 3821 3822 if (Ops.size() == 1) return Ops[0]; 3823 3824 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3825 3826 // Okay, it looks like we really DO need an expr. Check to see if we 3827 // already have one, otherwise create a new one. 3828 FoldingSetNodeID ID; 3829 ID.AddInteger(Kind); 3830 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3831 ID.AddPointer(Ops[i]); 3832 void *IP = nullptr; 3833 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3834 if (ExistingSCEV) 3835 return ExistingSCEV; 3836 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3837 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3838 SCEV *S = new (SCEVAllocator) 3839 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3840 3841 UniqueSCEVs.InsertNode(S, IP); 3842 addToLoopUseLists(S); 3843 return S; 3844 } 3845 3846 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3847 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3848 return getSMaxExpr(Ops); 3849 } 3850 3851 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3852 return getMinMaxExpr(scSMaxExpr, Ops); 3853 } 3854 3855 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3856 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3857 return getUMaxExpr(Ops); 3858 } 3859 3860 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3861 return getMinMaxExpr(scUMaxExpr, Ops); 3862 } 3863 3864 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3865 const SCEV *RHS) { 3866 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3867 return getSMinExpr(Ops); 3868 } 3869 3870 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3871 return getMinMaxExpr(scSMinExpr, Ops); 3872 } 3873 3874 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3875 const SCEV *RHS) { 3876 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3877 return getUMinExpr(Ops); 3878 } 3879 3880 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3881 return getMinMaxExpr(scUMinExpr, Ops); 3882 } 3883 3884 const SCEV * 3885 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3886 ScalableVectorType *ScalableTy) { 3887 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3888 Constant *One = ConstantInt::get(IntTy, 1); 3889 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3890 // Note that the expression we created is the final expression, we don't 3891 // want to simplify it any further Also, if we call a normal getSCEV(), 3892 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3893 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3894 } 3895 3896 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3897 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3898 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3899 // We can bypass creating a target-independent constant expression and then 3900 // folding it back into a ConstantInt. This is just a compile-time 3901 // optimization. 3902 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3903 } 3904 3905 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3906 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3907 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3908 // We can bypass creating a target-independent constant expression and then 3909 // folding it back into a ConstantInt. This is just a compile-time 3910 // optimization. 3911 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3912 } 3913 3914 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3915 StructType *STy, 3916 unsigned FieldNo) { 3917 // We can bypass creating a target-independent constant expression and then 3918 // folding it back into a ConstantInt. This is just a compile-time 3919 // optimization. 3920 return getConstant( 3921 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3922 } 3923 3924 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3925 // Don't attempt to do anything other than create a SCEVUnknown object 3926 // here. createSCEV only calls getUnknown after checking for all other 3927 // interesting possibilities, and any other code that calls getUnknown 3928 // is doing so in order to hide a value from SCEV canonicalization. 3929 3930 FoldingSetNodeID ID; 3931 ID.AddInteger(scUnknown); 3932 ID.AddPointer(V); 3933 void *IP = nullptr; 3934 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3935 assert(cast<SCEVUnknown>(S)->getValue() == V && 3936 "Stale SCEVUnknown in uniquing map!"); 3937 return S; 3938 } 3939 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3940 FirstUnknown); 3941 FirstUnknown = cast<SCEVUnknown>(S); 3942 UniqueSCEVs.InsertNode(S, IP); 3943 return S; 3944 } 3945 3946 //===----------------------------------------------------------------------===// 3947 // Basic SCEV Analysis and PHI Idiom Recognition Code 3948 // 3949 3950 /// Test if values of the given type are analyzable within the SCEV 3951 /// framework. This primarily includes integer types, and it can optionally 3952 /// include pointer types if the ScalarEvolution class has access to 3953 /// target-specific information. 3954 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3955 // Integers and pointers are always SCEVable. 3956 return Ty->isIntOrPtrTy(); 3957 } 3958 3959 /// Return the size in bits of the specified type, for which isSCEVable must 3960 /// return true. 3961 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3962 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3963 if (Ty->isPointerTy()) 3964 return getDataLayout().getIndexTypeSizeInBits(Ty); 3965 return getDataLayout().getTypeSizeInBits(Ty); 3966 } 3967 3968 /// Return a type with the same bitwidth as the given type and which represents 3969 /// how SCEV will treat the given type, for which isSCEVable must return 3970 /// true. For pointer types, this is the pointer index sized integer type. 3971 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3972 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3973 3974 if (Ty->isIntegerTy()) 3975 return Ty; 3976 3977 // The only other support type is pointer. 3978 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3979 return getDataLayout().getIndexType(Ty); 3980 } 3981 3982 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3983 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3984 } 3985 3986 const SCEV *ScalarEvolution::getCouldNotCompute() { 3987 return CouldNotCompute.get(); 3988 } 3989 3990 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3991 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3992 auto *SU = dyn_cast<SCEVUnknown>(S); 3993 return SU && SU->getValue() == nullptr; 3994 }); 3995 3996 return !ContainsNulls; 3997 } 3998 3999 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4000 HasRecMapType::iterator I = HasRecMap.find(S); 4001 if (I != HasRecMap.end()) 4002 return I->second; 4003 4004 bool FoundAddRec = 4005 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4006 HasRecMap.insert({S, FoundAddRec}); 4007 return FoundAddRec; 4008 } 4009 4010 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 4011 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 4012 /// offset I, then return {S', I}, else return {\p S, nullptr}. 4013 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4014 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4015 if (!Add) 4016 return {S, nullptr}; 4017 4018 if (Add->getNumOperands() != 2) 4019 return {S, nullptr}; 4020 4021 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4022 if (!ConstOp) 4023 return {S, nullptr}; 4024 4025 return {Add->getOperand(1), ConstOp->getValue()}; 4026 } 4027 4028 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4029 /// by the value and offset from any ValueOffsetPair in the set. 4030 ScalarEvolution::ValueOffsetPairSetVector * 4031 ScalarEvolution::getSCEVValues(const SCEV *S) { 4032 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4033 if (SI == ExprValueMap.end()) 4034 return nullptr; 4035 #ifndef NDEBUG 4036 if (VerifySCEVMap) { 4037 // Check there is no dangling Value in the set returned. 4038 for (const auto &VE : SI->second) 4039 assert(ValueExprMap.count(VE.first)); 4040 } 4041 #endif 4042 return &SI->second; 4043 } 4044 4045 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4046 /// cannot be used separately. eraseValueFromMap should be used to remove 4047 /// V from ValueExprMap and ExprValueMap at the same time. 4048 void ScalarEvolution::eraseValueFromMap(Value *V) { 4049 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4050 if (I != ValueExprMap.end()) { 4051 const SCEV *S = I->second; 4052 // Remove {V, 0} from the set of ExprValueMap[S] 4053 if (auto *SV = getSCEVValues(S)) 4054 SV->remove({V, nullptr}); 4055 4056 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4057 const SCEV *Stripped; 4058 ConstantInt *Offset; 4059 std::tie(Stripped, Offset) = splitAddExpr(S); 4060 if (Offset != nullptr) { 4061 if (auto *SV = getSCEVValues(Stripped)) 4062 SV->remove({V, Offset}); 4063 } 4064 ValueExprMap.erase(V); 4065 } 4066 } 4067 4068 /// Check whether value has nuw/nsw/exact set but SCEV does not. 4069 /// TODO: In reality it is better to check the poison recursively 4070 /// but this is better than nothing. 4071 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 4072 if (auto *I = dyn_cast<Instruction>(V)) { 4073 if (isa<OverflowingBinaryOperator>(I)) { 4074 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 4075 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 4076 return true; 4077 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 4078 return true; 4079 } 4080 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 4081 return true; 4082 } 4083 return false; 4084 } 4085 4086 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4087 /// create a new one. 4088 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4089 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4090 4091 const SCEV *S = getExistingSCEV(V); 4092 if (S == nullptr) { 4093 S = createSCEV(V); 4094 // During PHI resolution, it is possible to create two SCEVs for the same 4095 // V, so it is needed to double check whether V->S is inserted into 4096 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4097 std::pair<ValueExprMapType::iterator, bool> Pair = 4098 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4099 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 4100 ExprValueMap[S].insert({V, nullptr}); 4101 4102 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4103 // ExprValueMap. 4104 const SCEV *Stripped = S; 4105 ConstantInt *Offset = nullptr; 4106 std::tie(Stripped, Offset) = splitAddExpr(S); 4107 // If stripped is SCEVUnknown, don't bother to save 4108 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4109 // increase the complexity of the expansion code. 4110 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4111 // because it may generate add/sub instead of GEP in SCEV expansion. 4112 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4113 !isa<GetElementPtrInst>(V)) 4114 ExprValueMap[Stripped].insert({V, Offset}); 4115 } 4116 } 4117 return S; 4118 } 4119 4120 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4121 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4122 4123 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4124 if (I != ValueExprMap.end()) { 4125 const SCEV *S = I->second; 4126 if (checkValidity(S)) 4127 return S; 4128 eraseValueFromMap(V); 4129 forgetMemoizedResults(S); 4130 } 4131 return nullptr; 4132 } 4133 4134 /// Return a SCEV corresponding to -V = -1*V 4135 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4136 SCEV::NoWrapFlags Flags) { 4137 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4138 return getConstant( 4139 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4140 4141 Type *Ty = V->getType(); 4142 Ty = getEffectiveSCEVType(Ty); 4143 return getMulExpr(V, getMinusOne(Ty), Flags); 4144 } 4145 4146 /// If Expr computes ~A, return A else return nullptr 4147 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4148 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4149 if (!Add || Add->getNumOperands() != 2 || 4150 !Add->getOperand(0)->isAllOnesValue()) 4151 return nullptr; 4152 4153 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4154 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4155 !AddRHS->getOperand(0)->isAllOnesValue()) 4156 return nullptr; 4157 4158 return AddRHS->getOperand(1); 4159 } 4160 4161 /// Return a SCEV corresponding to ~V = -1-V 4162 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4163 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4164 4165 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4166 return getConstant( 4167 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4168 4169 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4170 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4171 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4172 SmallVector<const SCEV *, 2> MatchedOperands; 4173 for (const SCEV *Operand : MME->operands()) { 4174 const SCEV *Matched = MatchNotExpr(Operand); 4175 if (!Matched) 4176 return (const SCEV *)nullptr; 4177 MatchedOperands.push_back(Matched); 4178 } 4179 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4180 MatchedOperands); 4181 }; 4182 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4183 return Replaced; 4184 } 4185 4186 Type *Ty = V->getType(); 4187 Ty = getEffectiveSCEVType(Ty); 4188 return getMinusSCEV(getMinusOne(Ty), V); 4189 } 4190 4191 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4192 assert(P->getType()->isPointerTy()); 4193 4194 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4195 // The base of an AddRec is the first operand. 4196 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4197 Ops[0] = removePointerBase(Ops[0]); 4198 // Don't try to transfer nowrap flags for now. We could in some cases 4199 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4200 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4201 } 4202 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4203 // The base of an Add is the pointer operand. 4204 SmallVector<const SCEV *> Ops{Add->operands()}; 4205 const SCEV **PtrOp = nullptr; 4206 for (const SCEV *&AddOp : Ops) { 4207 if (AddOp->getType()->isPointerTy()) { 4208 assert(!PtrOp && "Cannot have multiple pointer ops"); 4209 PtrOp = &AddOp; 4210 } 4211 } 4212 *PtrOp = removePointerBase(*PtrOp); 4213 // Don't try to transfer nowrap flags for now. We could in some cases 4214 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4215 return getAddExpr(Ops); 4216 } 4217 // Any other expression must be a pointer base. 4218 return getZero(P->getType()); 4219 } 4220 4221 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4222 SCEV::NoWrapFlags Flags, 4223 unsigned Depth) { 4224 // Fast path: X - X --> 0. 4225 if (LHS == RHS) 4226 return getZero(LHS->getType()); 4227 4228 // If we subtract two pointers with different pointer bases, bail. 4229 // Eventually, we're going to add an assertion to getMulExpr that we 4230 // can't multiply by a pointer. 4231 if (RHS->getType()->isPointerTy()) { 4232 if (!LHS->getType()->isPointerTy() || 4233 getPointerBase(LHS) != getPointerBase(RHS)) 4234 return getCouldNotCompute(); 4235 LHS = removePointerBase(LHS); 4236 RHS = removePointerBase(RHS); 4237 } 4238 4239 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4240 // makes it so that we cannot make much use of NUW. 4241 auto AddFlags = SCEV::FlagAnyWrap; 4242 const bool RHSIsNotMinSigned = 4243 !getSignedRangeMin(RHS).isMinSignedValue(); 4244 if (hasFlags(Flags, SCEV::FlagNSW)) { 4245 // Let M be the minimum representable signed value. Then (-1)*RHS 4246 // signed-wraps if and only if RHS is M. That can happen even for 4247 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4248 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4249 // (-1)*RHS, we need to prove that RHS != M. 4250 // 4251 // If LHS is non-negative and we know that LHS - RHS does not 4252 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4253 // either by proving that RHS > M or that LHS >= 0. 4254 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4255 AddFlags = SCEV::FlagNSW; 4256 } 4257 } 4258 4259 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4260 // RHS is NSW and LHS >= 0. 4261 // 4262 // The difficulty here is that the NSW flag may have been proven 4263 // relative to a loop that is to be found in a recurrence in LHS and 4264 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4265 // larger scope than intended. 4266 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4267 4268 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4269 } 4270 4271 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4272 unsigned Depth) { 4273 Type *SrcTy = V->getType(); 4274 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4275 "Cannot truncate or zero extend with non-integer arguments!"); 4276 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4277 return V; // No conversion 4278 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4279 return getTruncateExpr(V, Ty, Depth); 4280 return getZeroExtendExpr(V, Ty, Depth); 4281 } 4282 4283 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4284 unsigned Depth) { 4285 Type *SrcTy = V->getType(); 4286 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4287 "Cannot truncate or zero extend with non-integer arguments!"); 4288 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4289 return V; // No conversion 4290 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4291 return getTruncateExpr(V, Ty, Depth); 4292 return getSignExtendExpr(V, Ty, Depth); 4293 } 4294 4295 const SCEV * 4296 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4297 Type *SrcTy = V->getType(); 4298 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4299 "Cannot noop or zero extend with non-integer arguments!"); 4300 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4301 "getNoopOrZeroExtend cannot truncate!"); 4302 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4303 return V; // No conversion 4304 return getZeroExtendExpr(V, Ty); 4305 } 4306 4307 const SCEV * 4308 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4309 Type *SrcTy = V->getType(); 4310 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4311 "Cannot noop or sign extend with non-integer arguments!"); 4312 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4313 "getNoopOrSignExtend cannot truncate!"); 4314 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4315 return V; // No conversion 4316 return getSignExtendExpr(V, Ty); 4317 } 4318 4319 const SCEV * 4320 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4321 Type *SrcTy = V->getType(); 4322 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4323 "Cannot noop or any extend with non-integer arguments!"); 4324 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4325 "getNoopOrAnyExtend cannot truncate!"); 4326 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4327 return V; // No conversion 4328 return getAnyExtendExpr(V, Ty); 4329 } 4330 4331 const SCEV * 4332 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4333 Type *SrcTy = V->getType(); 4334 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4335 "Cannot truncate or noop with non-integer arguments!"); 4336 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4337 "getTruncateOrNoop cannot extend!"); 4338 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4339 return V; // No conversion 4340 return getTruncateExpr(V, Ty); 4341 } 4342 4343 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4344 const SCEV *RHS) { 4345 const SCEV *PromotedLHS = LHS; 4346 const SCEV *PromotedRHS = RHS; 4347 4348 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4349 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4350 else 4351 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4352 4353 return getUMaxExpr(PromotedLHS, PromotedRHS); 4354 } 4355 4356 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4357 const SCEV *RHS) { 4358 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4359 return getUMinFromMismatchedTypes(Ops); 4360 } 4361 4362 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4363 SmallVectorImpl<const SCEV *> &Ops) { 4364 assert(!Ops.empty() && "At least one operand must be!"); 4365 // Trivial case. 4366 if (Ops.size() == 1) 4367 return Ops[0]; 4368 4369 // Find the max type first. 4370 Type *MaxType = nullptr; 4371 for (auto *S : Ops) 4372 if (MaxType) 4373 MaxType = getWiderType(MaxType, S->getType()); 4374 else 4375 MaxType = S->getType(); 4376 assert(MaxType && "Failed to find maximum type!"); 4377 4378 // Extend all ops to max type. 4379 SmallVector<const SCEV *, 2> PromotedOps; 4380 for (auto *S : Ops) 4381 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4382 4383 // Generate umin. 4384 return getUMinExpr(PromotedOps); 4385 } 4386 4387 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4388 // A pointer operand may evaluate to a nonpointer expression, such as null. 4389 if (!V->getType()->isPointerTy()) 4390 return V; 4391 4392 while (true) { 4393 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4394 V = AddRec->getStart(); 4395 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4396 const SCEV *PtrOp = nullptr; 4397 for (const SCEV *AddOp : Add->operands()) { 4398 if (AddOp->getType()->isPointerTy()) { 4399 assert(!PtrOp && "Cannot have multiple pointer ops"); 4400 PtrOp = AddOp; 4401 } 4402 } 4403 assert(PtrOp && "Must have pointer op"); 4404 V = PtrOp; 4405 } else // Not something we can look further into. 4406 return V; 4407 } 4408 } 4409 4410 /// Push users of the given Instruction onto the given Worklist. 4411 static void PushDefUseChildren(Instruction *I, 4412 SmallVectorImpl<Instruction *> &Worklist, 4413 SmallPtrSetImpl<Instruction *> &Visited) { 4414 // Push the def-use children onto the Worklist stack. 4415 for (User *U : I->users()) { 4416 auto *UserInsn = cast<Instruction>(U); 4417 if (Visited.insert(UserInsn).second) 4418 Worklist.push_back(UserInsn); 4419 } 4420 } 4421 4422 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4423 SmallVector<Instruction *, 16> Worklist; 4424 SmallPtrSet<Instruction *, 8> Visited; 4425 Visited.insert(PN); 4426 Worklist.push_back(PN); 4427 while (!Worklist.empty()) { 4428 Instruction *I = Worklist.pop_back_val(); 4429 4430 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4431 if (It != ValueExprMap.end()) { 4432 const SCEV *Old = It->second; 4433 4434 // Short-circuit the def-use traversal if the symbolic name 4435 // ceases to appear in expressions. 4436 if (Old != SymName && !hasOperand(Old, SymName)) 4437 continue; 4438 4439 // SCEVUnknown for a PHI either means that it has an unrecognized 4440 // structure, it's a PHI that's in the progress of being computed 4441 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4442 // additional loop trip count information isn't going to change anything. 4443 // In the second case, createNodeForPHI will perform the necessary 4444 // updates on its own when it gets to that point. In the third, we do 4445 // want to forget the SCEVUnknown. 4446 if (!isa<PHINode>(I) || 4447 !isa<SCEVUnknown>(Old) || 4448 (I != PN && Old == SymName)) { 4449 eraseValueFromMap(It->first); 4450 forgetMemoizedResults(Old); 4451 } 4452 } 4453 4454 PushDefUseChildren(I, Worklist, Visited); 4455 } 4456 } 4457 4458 namespace { 4459 4460 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4461 /// expression in case its Loop is L. If it is not L then 4462 /// if IgnoreOtherLoops is true then use AddRec itself 4463 /// otherwise rewrite cannot be done. 4464 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4465 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4466 public: 4467 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4468 bool IgnoreOtherLoops = true) { 4469 SCEVInitRewriter Rewriter(L, SE); 4470 const SCEV *Result = Rewriter.visit(S); 4471 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4472 return SE.getCouldNotCompute(); 4473 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4474 ? SE.getCouldNotCompute() 4475 : Result; 4476 } 4477 4478 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4479 if (!SE.isLoopInvariant(Expr, L)) 4480 SeenLoopVariantSCEVUnknown = true; 4481 return Expr; 4482 } 4483 4484 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4485 // Only re-write AddRecExprs for this loop. 4486 if (Expr->getLoop() == L) 4487 return Expr->getStart(); 4488 SeenOtherLoops = true; 4489 return Expr; 4490 } 4491 4492 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4493 4494 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4495 4496 private: 4497 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4498 : SCEVRewriteVisitor(SE), L(L) {} 4499 4500 const Loop *L; 4501 bool SeenLoopVariantSCEVUnknown = false; 4502 bool SeenOtherLoops = false; 4503 }; 4504 4505 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4506 /// increment expression in case its Loop is L. If it is not L then 4507 /// use AddRec itself. 4508 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4509 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4510 public: 4511 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4512 SCEVPostIncRewriter Rewriter(L, SE); 4513 const SCEV *Result = Rewriter.visit(S); 4514 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4515 ? SE.getCouldNotCompute() 4516 : Result; 4517 } 4518 4519 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4520 if (!SE.isLoopInvariant(Expr, L)) 4521 SeenLoopVariantSCEVUnknown = true; 4522 return Expr; 4523 } 4524 4525 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4526 // Only re-write AddRecExprs for this loop. 4527 if (Expr->getLoop() == L) 4528 return Expr->getPostIncExpr(SE); 4529 SeenOtherLoops = true; 4530 return Expr; 4531 } 4532 4533 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4534 4535 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4536 4537 private: 4538 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4539 : SCEVRewriteVisitor(SE), L(L) {} 4540 4541 const Loop *L; 4542 bool SeenLoopVariantSCEVUnknown = false; 4543 bool SeenOtherLoops = false; 4544 }; 4545 4546 /// This class evaluates the compare condition by matching it against the 4547 /// condition of loop latch. If there is a match we assume a true value 4548 /// for the condition while building SCEV nodes. 4549 class SCEVBackedgeConditionFolder 4550 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4551 public: 4552 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4553 ScalarEvolution &SE) { 4554 bool IsPosBECond = false; 4555 Value *BECond = nullptr; 4556 if (BasicBlock *Latch = L->getLoopLatch()) { 4557 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4558 if (BI && BI->isConditional()) { 4559 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4560 "Both outgoing branches should not target same header!"); 4561 BECond = BI->getCondition(); 4562 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4563 } else { 4564 return S; 4565 } 4566 } 4567 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4568 return Rewriter.visit(S); 4569 } 4570 4571 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4572 const SCEV *Result = Expr; 4573 bool InvariantF = SE.isLoopInvariant(Expr, L); 4574 4575 if (!InvariantF) { 4576 Instruction *I = cast<Instruction>(Expr->getValue()); 4577 switch (I->getOpcode()) { 4578 case Instruction::Select: { 4579 SelectInst *SI = cast<SelectInst>(I); 4580 Optional<const SCEV *> Res = 4581 compareWithBackedgeCondition(SI->getCondition()); 4582 if (Res.hasValue()) { 4583 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4584 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4585 } 4586 break; 4587 } 4588 default: { 4589 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4590 if (Res.hasValue()) 4591 Result = Res.getValue(); 4592 break; 4593 } 4594 } 4595 } 4596 return Result; 4597 } 4598 4599 private: 4600 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4601 bool IsPosBECond, ScalarEvolution &SE) 4602 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4603 IsPositiveBECond(IsPosBECond) {} 4604 4605 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4606 4607 const Loop *L; 4608 /// Loop back condition. 4609 Value *BackedgeCond = nullptr; 4610 /// Set to true if loop back is on positive branch condition. 4611 bool IsPositiveBECond; 4612 }; 4613 4614 Optional<const SCEV *> 4615 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4616 4617 // If value matches the backedge condition for loop latch, 4618 // then return a constant evolution node based on loopback 4619 // branch taken. 4620 if (BackedgeCond == IC) 4621 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4622 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4623 return None; 4624 } 4625 4626 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4627 public: 4628 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4629 ScalarEvolution &SE) { 4630 SCEVShiftRewriter Rewriter(L, SE); 4631 const SCEV *Result = Rewriter.visit(S); 4632 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4633 } 4634 4635 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4636 // Only allow AddRecExprs for this loop. 4637 if (!SE.isLoopInvariant(Expr, L)) 4638 Valid = false; 4639 return Expr; 4640 } 4641 4642 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4643 if (Expr->getLoop() == L && Expr->isAffine()) 4644 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4645 Valid = false; 4646 return Expr; 4647 } 4648 4649 bool isValid() { return Valid; } 4650 4651 private: 4652 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4653 : SCEVRewriteVisitor(SE), L(L) {} 4654 4655 const Loop *L; 4656 bool Valid = true; 4657 }; 4658 4659 } // end anonymous namespace 4660 4661 SCEV::NoWrapFlags 4662 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4663 if (!AR->isAffine()) 4664 return SCEV::FlagAnyWrap; 4665 4666 using OBO = OverflowingBinaryOperator; 4667 4668 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4669 4670 if (!AR->hasNoSignedWrap()) { 4671 ConstantRange AddRecRange = getSignedRange(AR); 4672 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4673 4674 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4675 Instruction::Add, IncRange, OBO::NoSignedWrap); 4676 if (NSWRegion.contains(AddRecRange)) 4677 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4678 } 4679 4680 if (!AR->hasNoUnsignedWrap()) { 4681 ConstantRange AddRecRange = getUnsignedRange(AR); 4682 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4683 4684 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4685 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4686 if (NUWRegion.contains(AddRecRange)) 4687 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4688 } 4689 4690 return Result; 4691 } 4692 4693 SCEV::NoWrapFlags 4694 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4695 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4696 4697 if (AR->hasNoSignedWrap()) 4698 return Result; 4699 4700 if (!AR->isAffine()) 4701 return Result; 4702 4703 const SCEV *Step = AR->getStepRecurrence(*this); 4704 const Loop *L = AR->getLoop(); 4705 4706 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4707 // Note that this serves two purposes: It filters out loops that are 4708 // simply not analyzable, and it covers the case where this code is 4709 // being called from within backedge-taken count analysis, such that 4710 // attempting to ask for the backedge-taken count would likely result 4711 // in infinite recursion. In the later case, the analysis code will 4712 // cope with a conservative value, and it will take care to purge 4713 // that value once it has finished. 4714 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4715 4716 // Normally, in the cases we can prove no-overflow via a 4717 // backedge guarding condition, we can also compute a backedge 4718 // taken count for the loop. The exceptions are assumptions and 4719 // guards present in the loop -- SCEV is not great at exploiting 4720 // these to compute max backedge taken counts, but can still use 4721 // these to prove lack of overflow. Use this fact to avoid 4722 // doing extra work that may not pay off. 4723 4724 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4725 AC.assumptions().empty()) 4726 return Result; 4727 4728 // If the backedge is guarded by a comparison with the pre-inc value the 4729 // addrec is safe. Also, if the entry is guarded by a comparison with the 4730 // start value and the backedge is guarded by a comparison with the post-inc 4731 // value, the addrec is safe. 4732 ICmpInst::Predicate Pred; 4733 const SCEV *OverflowLimit = 4734 getSignedOverflowLimitForStep(Step, &Pred, this); 4735 if (OverflowLimit && 4736 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4737 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4738 Result = setFlags(Result, SCEV::FlagNSW); 4739 } 4740 return Result; 4741 } 4742 SCEV::NoWrapFlags 4743 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4744 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4745 4746 if (AR->hasNoUnsignedWrap()) 4747 return Result; 4748 4749 if (!AR->isAffine()) 4750 return Result; 4751 4752 const SCEV *Step = AR->getStepRecurrence(*this); 4753 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4754 const Loop *L = AR->getLoop(); 4755 4756 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4757 // Note that this serves two purposes: It filters out loops that are 4758 // simply not analyzable, and it covers the case where this code is 4759 // being called from within backedge-taken count analysis, such that 4760 // attempting to ask for the backedge-taken count would likely result 4761 // in infinite recursion. In the later case, the analysis code will 4762 // cope with a conservative value, and it will take care to purge 4763 // that value once it has finished. 4764 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4765 4766 // Normally, in the cases we can prove no-overflow via a 4767 // backedge guarding condition, we can also compute a backedge 4768 // taken count for the loop. The exceptions are assumptions and 4769 // guards present in the loop -- SCEV is not great at exploiting 4770 // these to compute max backedge taken counts, but can still use 4771 // these to prove lack of overflow. Use this fact to avoid 4772 // doing extra work that may not pay off. 4773 4774 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4775 AC.assumptions().empty()) 4776 return Result; 4777 4778 // If the backedge is guarded by a comparison with the pre-inc value the 4779 // addrec is safe. Also, if the entry is guarded by a comparison with the 4780 // start value and the backedge is guarded by a comparison with the post-inc 4781 // value, the addrec is safe. 4782 if (isKnownPositive(Step)) { 4783 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4784 getUnsignedRangeMax(Step)); 4785 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4786 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4787 Result = setFlags(Result, SCEV::FlagNUW); 4788 } 4789 } 4790 4791 return Result; 4792 } 4793 4794 namespace { 4795 4796 /// Represents an abstract binary operation. This may exist as a 4797 /// normal instruction or constant expression, or may have been 4798 /// derived from an expression tree. 4799 struct BinaryOp { 4800 unsigned Opcode; 4801 Value *LHS; 4802 Value *RHS; 4803 bool IsNSW = false; 4804 bool IsNUW = false; 4805 4806 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4807 /// constant expression. 4808 Operator *Op = nullptr; 4809 4810 explicit BinaryOp(Operator *Op) 4811 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4812 Op(Op) { 4813 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4814 IsNSW = OBO->hasNoSignedWrap(); 4815 IsNUW = OBO->hasNoUnsignedWrap(); 4816 } 4817 } 4818 4819 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4820 bool IsNUW = false) 4821 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4822 }; 4823 4824 } // end anonymous namespace 4825 4826 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4827 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4828 auto *Op = dyn_cast<Operator>(V); 4829 if (!Op) 4830 return None; 4831 4832 // Implementation detail: all the cleverness here should happen without 4833 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4834 // SCEV expressions when possible, and we should not break that. 4835 4836 switch (Op->getOpcode()) { 4837 case Instruction::Add: 4838 case Instruction::Sub: 4839 case Instruction::Mul: 4840 case Instruction::UDiv: 4841 case Instruction::URem: 4842 case Instruction::And: 4843 case Instruction::Or: 4844 case Instruction::AShr: 4845 case Instruction::Shl: 4846 return BinaryOp(Op); 4847 4848 case Instruction::Xor: 4849 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4850 // If the RHS of the xor is a signmask, then this is just an add. 4851 // Instcombine turns add of signmask into xor as a strength reduction step. 4852 if (RHSC->getValue().isSignMask()) 4853 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4854 return BinaryOp(Op); 4855 4856 case Instruction::LShr: 4857 // Turn logical shift right of a constant into a unsigned divide. 4858 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4859 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4860 4861 // If the shift count is not less than the bitwidth, the result of 4862 // the shift is undefined. Don't try to analyze it, because the 4863 // resolution chosen here may differ from the resolution chosen in 4864 // other parts of the compiler. 4865 if (SA->getValue().ult(BitWidth)) { 4866 Constant *X = 4867 ConstantInt::get(SA->getContext(), 4868 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4869 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4870 } 4871 } 4872 return BinaryOp(Op); 4873 4874 case Instruction::ExtractValue: { 4875 auto *EVI = cast<ExtractValueInst>(Op); 4876 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4877 break; 4878 4879 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4880 if (!WO) 4881 break; 4882 4883 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4884 bool Signed = WO->isSigned(); 4885 // TODO: Should add nuw/nsw flags for mul as well. 4886 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4887 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4888 4889 // Now that we know that all uses of the arithmetic-result component of 4890 // CI are guarded by the overflow check, we can go ahead and pretend 4891 // that the arithmetic is non-overflowing. 4892 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4893 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4894 } 4895 4896 default: 4897 break; 4898 } 4899 4900 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4901 // semantics as a Sub, return a binary sub expression. 4902 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4903 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4904 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4905 4906 return None; 4907 } 4908 4909 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4910 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4911 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4912 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4913 /// follows one of the following patterns: 4914 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4915 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4916 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4917 /// we return the type of the truncation operation, and indicate whether the 4918 /// truncated type should be treated as signed/unsigned by setting 4919 /// \p Signed to true/false, respectively. 4920 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4921 bool &Signed, ScalarEvolution &SE) { 4922 // The case where Op == SymbolicPHI (that is, with no type conversions on 4923 // the way) is handled by the regular add recurrence creating logic and 4924 // would have already been triggered in createAddRecForPHI. Reaching it here 4925 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4926 // because one of the other operands of the SCEVAddExpr updating this PHI is 4927 // not invariant). 4928 // 4929 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4930 // this case predicates that allow us to prove that Op == SymbolicPHI will 4931 // be added. 4932 if (Op == SymbolicPHI) 4933 return nullptr; 4934 4935 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4936 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4937 if (SourceBits != NewBits) 4938 return nullptr; 4939 4940 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4941 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4942 if (!SExt && !ZExt) 4943 return nullptr; 4944 const SCEVTruncateExpr *Trunc = 4945 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4946 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4947 if (!Trunc) 4948 return nullptr; 4949 const SCEV *X = Trunc->getOperand(); 4950 if (X != SymbolicPHI) 4951 return nullptr; 4952 Signed = SExt != nullptr; 4953 return Trunc->getType(); 4954 } 4955 4956 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4957 if (!PN->getType()->isIntegerTy()) 4958 return nullptr; 4959 const Loop *L = LI.getLoopFor(PN->getParent()); 4960 if (!L || L->getHeader() != PN->getParent()) 4961 return nullptr; 4962 return L; 4963 } 4964 4965 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4966 // computation that updates the phi follows the following pattern: 4967 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4968 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4969 // If so, try to see if it can be rewritten as an AddRecExpr under some 4970 // Predicates. If successful, return them as a pair. Also cache the results 4971 // of the analysis. 4972 // 4973 // Example usage scenario: 4974 // Say the Rewriter is called for the following SCEV: 4975 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4976 // where: 4977 // %X = phi i64 (%Start, %BEValue) 4978 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4979 // and call this function with %SymbolicPHI = %X. 4980 // 4981 // The analysis will find that the value coming around the backedge has 4982 // the following SCEV: 4983 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4984 // Upon concluding that this matches the desired pattern, the function 4985 // will return the pair {NewAddRec, SmallPredsVec} where: 4986 // NewAddRec = {%Start,+,%Step} 4987 // SmallPredsVec = {P1, P2, P3} as follows: 4988 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4989 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4990 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4991 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4992 // under the predicates {P1,P2,P3}. 4993 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4994 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4995 // 4996 // TODO's: 4997 // 4998 // 1) Extend the Induction descriptor to also support inductions that involve 4999 // casts: When needed (namely, when we are called in the context of the 5000 // vectorizer induction analysis), a Set of cast instructions will be 5001 // populated by this method, and provided back to isInductionPHI. This is 5002 // needed to allow the vectorizer to properly record them to be ignored by 5003 // the cost model and to avoid vectorizing them (otherwise these casts, 5004 // which are redundant under the runtime overflow checks, will be 5005 // vectorized, which can be costly). 5006 // 5007 // 2) Support additional induction/PHISCEV patterns: We also want to support 5008 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5009 // after the induction update operation (the induction increment): 5010 // 5011 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5012 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5013 // 5014 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5015 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5016 // 5017 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5018 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5019 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5020 SmallVector<const SCEVPredicate *, 3> Predicates; 5021 5022 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5023 // return an AddRec expression under some predicate. 5024 5025 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5026 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5027 assert(L && "Expecting an integer loop header phi"); 5028 5029 // The loop may have multiple entrances or multiple exits; we can analyze 5030 // this phi as an addrec if it has a unique entry value and a unique 5031 // backedge value. 5032 Value *BEValueV = nullptr, *StartValueV = nullptr; 5033 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5034 Value *V = PN->getIncomingValue(i); 5035 if (L->contains(PN->getIncomingBlock(i))) { 5036 if (!BEValueV) { 5037 BEValueV = V; 5038 } else if (BEValueV != V) { 5039 BEValueV = nullptr; 5040 break; 5041 } 5042 } else if (!StartValueV) { 5043 StartValueV = V; 5044 } else if (StartValueV != V) { 5045 StartValueV = nullptr; 5046 break; 5047 } 5048 } 5049 if (!BEValueV || !StartValueV) 5050 return None; 5051 5052 const SCEV *BEValue = getSCEV(BEValueV); 5053 5054 // If the value coming around the backedge is an add with the symbolic 5055 // value we just inserted, possibly with casts that we can ignore under 5056 // an appropriate runtime guard, then we found a simple induction variable! 5057 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5058 if (!Add) 5059 return None; 5060 5061 // If there is a single occurrence of the symbolic value, possibly 5062 // casted, replace it with a recurrence. 5063 unsigned FoundIndex = Add->getNumOperands(); 5064 Type *TruncTy = nullptr; 5065 bool Signed; 5066 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5067 if ((TruncTy = 5068 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5069 if (FoundIndex == e) { 5070 FoundIndex = i; 5071 break; 5072 } 5073 5074 if (FoundIndex == Add->getNumOperands()) 5075 return None; 5076 5077 // Create an add with everything but the specified operand. 5078 SmallVector<const SCEV *, 8> Ops; 5079 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5080 if (i != FoundIndex) 5081 Ops.push_back(Add->getOperand(i)); 5082 const SCEV *Accum = getAddExpr(Ops); 5083 5084 // The runtime checks will not be valid if the step amount is 5085 // varying inside the loop. 5086 if (!isLoopInvariant(Accum, L)) 5087 return None; 5088 5089 // *** Part2: Create the predicates 5090 5091 // Analysis was successful: we have a phi-with-cast pattern for which we 5092 // can return an AddRec expression under the following predicates: 5093 // 5094 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5095 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5096 // P2: An Equal predicate that guarantees that 5097 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5098 // P3: An Equal predicate that guarantees that 5099 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5100 // 5101 // As we next prove, the above predicates guarantee that: 5102 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5103 // 5104 // 5105 // More formally, we want to prove that: 5106 // Expr(i+1) = Start + (i+1) * Accum 5107 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5108 // 5109 // Given that: 5110 // 1) Expr(0) = Start 5111 // 2) Expr(1) = Start + Accum 5112 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5113 // 3) Induction hypothesis (step i): 5114 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5115 // 5116 // Proof: 5117 // Expr(i+1) = 5118 // = Start + (i+1)*Accum 5119 // = (Start + i*Accum) + Accum 5120 // = Expr(i) + Accum 5121 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5122 // :: from step i 5123 // 5124 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5125 // 5126 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5127 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5128 // + Accum :: from P3 5129 // 5130 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5131 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5132 // 5133 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5134 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5135 // 5136 // By induction, the same applies to all iterations 1<=i<n: 5137 // 5138 5139 // Create a truncated addrec for which we will add a no overflow check (P1). 5140 const SCEV *StartVal = getSCEV(StartValueV); 5141 const SCEV *PHISCEV = 5142 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5143 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5144 5145 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5146 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5147 // will be constant. 5148 // 5149 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5150 // add P1. 5151 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5152 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5153 Signed ? SCEVWrapPredicate::IncrementNSSW 5154 : SCEVWrapPredicate::IncrementNUSW; 5155 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5156 Predicates.push_back(AddRecPred); 5157 } 5158 5159 // Create the Equal Predicates P2,P3: 5160 5161 // It is possible that the predicates P2 and/or P3 are computable at 5162 // compile time due to StartVal and/or Accum being constants. 5163 // If either one is, then we can check that now and escape if either P2 5164 // or P3 is false. 5165 5166 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5167 // for each of StartVal and Accum 5168 auto getExtendedExpr = [&](const SCEV *Expr, 5169 bool CreateSignExtend) -> const SCEV * { 5170 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5171 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5172 const SCEV *ExtendedExpr = 5173 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5174 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5175 return ExtendedExpr; 5176 }; 5177 5178 // Given: 5179 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5180 // = getExtendedExpr(Expr) 5181 // Determine whether the predicate P: Expr == ExtendedExpr 5182 // is known to be false at compile time 5183 auto PredIsKnownFalse = [&](const SCEV *Expr, 5184 const SCEV *ExtendedExpr) -> bool { 5185 return Expr != ExtendedExpr && 5186 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5187 }; 5188 5189 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5190 if (PredIsKnownFalse(StartVal, StartExtended)) { 5191 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5192 return None; 5193 } 5194 5195 // The Step is always Signed (because the overflow checks are either 5196 // NSSW or NUSW) 5197 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5198 if (PredIsKnownFalse(Accum, AccumExtended)) { 5199 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5200 return None; 5201 } 5202 5203 auto AppendPredicate = [&](const SCEV *Expr, 5204 const SCEV *ExtendedExpr) -> void { 5205 if (Expr != ExtendedExpr && 5206 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5207 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5208 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5209 Predicates.push_back(Pred); 5210 } 5211 }; 5212 5213 AppendPredicate(StartVal, StartExtended); 5214 AppendPredicate(Accum, AccumExtended); 5215 5216 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5217 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5218 // into NewAR if it will also add the runtime overflow checks specified in 5219 // Predicates. 5220 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5221 5222 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5223 std::make_pair(NewAR, Predicates); 5224 // Remember the result of the analysis for this SCEV at this locayyytion. 5225 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5226 return PredRewrite; 5227 } 5228 5229 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5230 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5231 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5232 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5233 if (!L) 5234 return None; 5235 5236 // Check to see if we already analyzed this PHI. 5237 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5238 if (I != PredicatedSCEVRewrites.end()) { 5239 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5240 I->second; 5241 // Analysis was done before and failed to create an AddRec: 5242 if (Rewrite.first == SymbolicPHI) 5243 return None; 5244 // Analysis was done before and succeeded to create an AddRec under 5245 // a predicate: 5246 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5247 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5248 return Rewrite; 5249 } 5250 5251 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5252 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5253 5254 // Record in the cache that the analysis failed 5255 if (!Rewrite) { 5256 SmallVector<const SCEVPredicate *, 3> Predicates; 5257 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5258 return None; 5259 } 5260 5261 return Rewrite; 5262 } 5263 5264 // FIXME: This utility is currently required because the Rewriter currently 5265 // does not rewrite this expression: 5266 // {0, +, (sext ix (trunc iy to ix) to iy)} 5267 // into {0, +, %step}, 5268 // even when the following Equal predicate exists: 5269 // "%step == (sext ix (trunc iy to ix) to iy)". 5270 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5271 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5272 if (AR1 == AR2) 5273 return true; 5274 5275 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5276 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5277 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5278 return false; 5279 return true; 5280 }; 5281 5282 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5283 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5284 return false; 5285 return true; 5286 } 5287 5288 /// A helper function for createAddRecFromPHI to handle simple cases. 5289 /// 5290 /// This function tries to find an AddRec expression for the simplest (yet most 5291 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5292 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5293 /// technique for finding the AddRec expression. 5294 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5295 Value *BEValueV, 5296 Value *StartValueV) { 5297 const Loop *L = LI.getLoopFor(PN->getParent()); 5298 assert(L && L->getHeader() == PN->getParent()); 5299 assert(BEValueV && StartValueV); 5300 5301 auto BO = MatchBinaryOp(BEValueV, DT); 5302 if (!BO) 5303 return nullptr; 5304 5305 if (BO->Opcode != Instruction::Add) 5306 return nullptr; 5307 5308 const SCEV *Accum = nullptr; 5309 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5310 Accum = getSCEV(BO->RHS); 5311 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5312 Accum = getSCEV(BO->LHS); 5313 5314 if (!Accum) 5315 return nullptr; 5316 5317 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5318 if (BO->IsNUW) 5319 Flags = setFlags(Flags, SCEV::FlagNUW); 5320 if (BO->IsNSW) 5321 Flags = setFlags(Flags, SCEV::FlagNSW); 5322 5323 const SCEV *StartVal = getSCEV(StartValueV); 5324 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5325 5326 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5327 5328 // We can add Flags to the post-inc expression only if we 5329 // know that it is *undefined behavior* for BEValueV to 5330 // overflow. 5331 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5332 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5333 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5334 5335 return PHISCEV; 5336 } 5337 5338 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5339 const Loop *L = LI.getLoopFor(PN->getParent()); 5340 if (!L || L->getHeader() != PN->getParent()) 5341 return nullptr; 5342 5343 // The loop may have multiple entrances or multiple exits; we can analyze 5344 // this phi as an addrec if it has a unique entry value and a unique 5345 // backedge value. 5346 Value *BEValueV = nullptr, *StartValueV = nullptr; 5347 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5348 Value *V = PN->getIncomingValue(i); 5349 if (L->contains(PN->getIncomingBlock(i))) { 5350 if (!BEValueV) { 5351 BEValueV = V; 5352 } else if (BEValueV != V) { 5353 BEValueV = nullptr; 5354 break; 5355 } 5356 } else if (!StartValueV) { 5357 StartValueV = V; 5358 } else if (StartValueV != V) { 5359 StartValueV = nullptr; 5360 break; 5361 } 5362 } 5363 if (!BEValueV || !StartValueV) 5364 return nullptr; 5365 5366 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5367 "PHI node already processed?"); 5368 5369 // First, try to find AddRec expression without creating a fictituos symbolic 5370 // value for PN. 5371 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5372 return S; 5373 5374 // Handle PHI node value symbolically. 5375 const SCEV *SymbolicName = getUnknown(PN); 5376 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5377 5378 // Using this symbolic name for the PHI, analyze the value coming around 5379 // the back-edge. 5380 const SCEV *BEValue = getSCEV(BEValueV); 5381 5382 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5383 // has a special value for the first iteration of the loop. 5384 5385 // If the value coming around the backedge is an add with the symbolic 5386 // value we just inserted, then we found a simple induction variable! 5387 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5388 // If there is a single occurrence of the symbolic value, replace it 5389 // with a recurrence. 5390 unsigned FoundIndex = Add->getNumOperands(); 5391 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5392 if (Add->getOperand(i) == SymbolicName) 5393 if (FoundIndex == e) { 5394 FoundIndex = i; 5395 break; 5396 } 5397 5398 if (FoundIndex != Add->getNumOperands()) { 5399 // Create an add with everything but the specified operand. 5400 SmallVector<const SCEV *, 8> Ops; 5401 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5402 if (i != FoundIndex) 5403 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5404 L, *this)); 5405 const SCEV *Accum = getAddExpr(Ops); 5406 5407 // This is not a valid addrec if the step amount is varying each 5408 // loop iteration, but is not itself an addrec in this loop. 5409 if (isLoopInvariant(Accum, L) || 5410 (isa<SCEVAddRecExpr>(Accum) && 5411 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5412 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5413 5414 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5415 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5416 if (BO->IsNUW) 5417 Flags = setFlags(Flags, SCEV::FlagNUW); 5418 if (BO->IsNSW) 5419 Flags = setFlags(Flags, SCEV::FlagNSW); 5420 } 5421 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5422 // If the increment is an inbounds GEP, then we know the address 5423 // space cannot be wrapped around. We cannot make any guarantee 5424 // about signed or unsigned overflow because pointers are 5425 // unsigned but we may have a negative index from the base 5426 // pointer. We can guarantee that no unsigned wrap occurs if the 5427 // indices form a positive value. 5428 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5429 Flags = setFlags(Flags, SCEV::FlagNW); 5430 5431 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5432 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5433 Flags = setFlags(Flags, SCEV::FlagNUW); 5434 } 5435 5436 // We cannot transfer nuw and nsw flags from subtraction 5437 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5438 // for instance. 5439 } 5440 5441 const SCEV *StartVal = getSCEV(StartValueV); 5442 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5443 5444 // Okay, for the entire analysis of this edge we assumed the PHI 5445 // to be symbolic. We now need to go back and purge all of the 5446 // entries for the scalars that use the symbolic expression. 5447 forgetSymbolicName(PN, SymbolicName); 5448 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5449 5450 // We can add Flags to the post-inc expression only if we 5451 // know that it is *undefined behavior* for BEValueV to 5452 // overflow. 5453 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5454 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5455 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5456 5457 return PHISCEV; 5458 } 5459 } 5460 } else { 5461 // Otherwise, this could be a loop like this: 5462 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5463 // In this case, j = {1,+,1} and BEValue is j. 5464 // Because the other in-value of i (0) fits the evolution of BEValue 5465 // i really is an addrec evolution. 5466 // 5467 // We can generalize this saying that i is the shifted value of BEValue 5468 // by one iteration: 5469 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5470 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5471 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5472 if (Shifted != getCouldNotCompute() && 5473 Start != getCouldNotCompute()) { 5474 const SCEV *StartVal = getSCEV(StartValueV); 5475 if (Start == StartVal) { 5476 // Okay, for the entire analysis of this edge we assumed the PHI 5477 // to be symbolic. We now need to go back and purge all of the 5478 // entries for the scalars that use the symbolic expression. 5479 forgetSymbolicName(PN, SymbolicName); 5480 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5481 return Shifted; 5482 } 5483 } 5484 } 5485 5486 // Remove the temporary PHI node SCEV that has been inserted while intending 5487 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5488 // as it will prevent later (possibly simpler) SCEV expressions to be added 5489 // to the ValueExprMap. 5490 eraseValueFromMap(PN); 5491 5492 return nullptr; 5493 } 5494 5495 // Checks if the SCEV S is available at BB. S is considered available at BB 5496 // if S can be materialized at BB without introducing a fault. 5497 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5498 BasicBlock *BB) { 5499 struct CheckAvailable { 5500 bool TraversalDone = false; 5501 bool Available = true; 5502 5503 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5504 BasicBlock *BB = nullptr; 5505 DominatorTree &DT; 5506 5507 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5508 : L(L), BB(BB), DT(DT) {} 5509 5510 bool setUnavailable() { 5511 TraversalDone = true; 5512 Available = false; 5513 return false; 5514 } 5515 5516 bool follow(const SCEV *S) { 5517 switch (S->getSCEVType()) { 5518 case scConstant: 5519 case scPtrToInt: 5520 case scTruncate: 5521 case scZeroExtend: 5522 case scSignExtend: 5523 case scAddExpr: 5524 case scMulExpr: 5525 case scUMaxExpr: 5526 case scSMaxExpr: 5527 case scUMinExpr: 5528 case scSMinExpr: 5529 // These expressions are available if their operand(s) is/are. 5530 return true; 5531 5532 case scAddRecExpr: { 5533 // We allow add recurrences that are on the loop BB is in, or some 5534 // outer loop. This guarantees availability because the value of the 5535 // add recurrence at BB is simply the "current" value of the induction 5536 // variable. We can relax this in the future; for instance an add 5537 // recurrence on a sibling dominating loop is also available at BB. 5538 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5539 if (L && (ARLoop == L || ARLoop->contains(L))) 5540 return true; 5541 5542 return setUnavailable(); 5543 } 5544 5545 case scUnknown: { 5546 // For SCEVUnknown, we check for simple dominance. 5547 const auto *SU = cast<SCEVUnknown>(S); 5548 Value *V = SU->getValue(); 5549 5550 if (isa<Argument>(V)) 5551 return false; 5552 5553 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5554 return false; 5555 5556 return setUnavailable(); 5557 } 5558 5559 case scUDivExpr: 5560 case scCouldNotCompute: 5561 // We do not try to smart about these at all. 5562 return setUnavailable(); 5563 } 5564 llvm_unreachable("Unknown SCEV kind!"); 5565 } 5566 5567 bool isDone() { return TraversalDone; } 5568 }; 5569 5570 CheckAvailable CA(L, BB, DT); 5571 SCEVTraversal<CheckAvailable> ST(CA); 5572 5573 ST.visitAll(S); 5574 return CA.Available; 5575 } 5576 5577 // Try to match a control flow sequence that branches out at BI and merges back 5578 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5579 // match. 5580 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5581 Value *&C, Value *&LHS, Value *&RHS) { 5582 C = BI->getCondition(); 5583 5584 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5585 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5586 5587 if (!LeftEdge.isSingleEdge()) 5588 return false; 5589 5590 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5591 5592 Use &LeftUse = Merge->getOperandUse(0); 5593 Use &RightUse = Merge->getOperandUse(1); 5594 5595 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5596 LHS = LeftUse; 5597 RHS = RightUse; 5598 return true; 5599 } 5600 5601 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5602 LHS = RightUse; 5603 RHS = LeftUse; 5604 return true; 5605 } 5606 5607 return false; 5608 } 5609 5610 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5611 auto IsReachable = 5612 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5613 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5614 const Loop *L = LI.getLoopFor(PN->getParent()); 5615 5616 // We don't want to break LCSSA, even in a SCEV expression tree. 5617 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5618 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5619 return nullptr; 5620 5621 // Try to match 5622 // 5623 // br %cond, label %left, label %right 5624 // left: 5625 // br label %merge 5626 // right: 5627 // br label %merge 5628 // merge: 5629 // V = phi [ %x, %left ], [ %y, %right ] 5630 // 5631 // as "select %cond, %x, %y" 5632 5633 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5634 assert(IDom && "At least the entry block should dominate PN"); 5635 5636 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5637 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5638 5639 if (BI && BI->isConditional() && 5640 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5641 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5642 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5643 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5644 } 5645 5646 return nullptr; 5647 } 5648 5649 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5650 if (const SCEV *S = createAddRecFromPHI(PN)) 5651 return S; 5652 5653 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5654 return S; 5655 5656 // If the PHI has a single incoming value, follow that value, unless the 5657 // PHI's incoming blocks are in a different loop, in which case doing so 5658 // risks breaking LCSSA form. Instcombine would normally zap these, but 5659 // it doesn't have DominatorTree information, so it may miss cases. 5660 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5661 if (LI.replacementPreservesLCSSAForm(PN, V)) 5662 return getSCEV(V); 5663 5664 // If it's not a loop phi, we can't handle it yet. 5665 return getUnknown(PN); 5666 } 5667 5668 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5669 Value *Cond, 5670 Value *TrueVal, 5671 Value *FalseVal) { 5672 // Handle "constant" branch or select. This can occur for instance when a 5673 // loop pass transforms an inner loop and moves on to process the outer loop. 5674 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5675 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5676 5677 // Try to match some simple smax or umax patterns. 5678 auto *ICI = dyn_cast<ICmpInst>(Cond); 5679 if (!ICI) 5680 return getUnknown(I); 5681 5682 Value *LHS = ICI->getOperand(0); 5683 Value *RHS = ICI->getOperand(1); 5684 5685 switch (ICI->getPredicate()) { 5686 case ICmpInst::ICMP_SLT: 5687 case ICmpInst::ICMP_SLE: 5688 case ICmpInst::ICMP_ULT: 5689 case ICmpInst::ICMP_ULE: 5690 std::swap(LHS, RHS); 5691 LLVM_FALLTHROUGH; 5692 case ICmpInst::ICMP_SGT: 5693 case ICmpInst::ICMP_SGE: 5694 case ICmpInst::ICMP_UGT: 5695 case ICmpInst::ICMP_UGE: 5696 // a > b ? a+x : b+x -> max(a, b)+x 5697 // a > b ? b+x : a+x -> min(a, b)+x 5698 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5699 bool Signed = ICI->isSigned(); 5700 const SCEV *LA = getSCEV(TrueVal); 5701 const SCEV *RA = getSCEV(FalseVal); 5702 const SCEV *LS = getSCEV(LHS); 5703 const SCEV *RS = getSCEV(RHS); 5704 if (LA->getType()->isPointerTy()) { 5705 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5706 // Need to make sure we can't produce weird expressions involving 5707 // negated pointers. 5708 if (LA == LS && RA == RS) 5709 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5710 if (LA == RS && RA == LS) 5711 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5712 } 5713 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5714 if (Op->getType()->isPointerTy()) { 5715 Op = getLosslessPtrToIntExpr(Op); 5716 if (isa<SCEVCouldNotCompute>(Op)) 5717 return Op; 5718 } 5719 if (Signed) 5720 Op = getNoopOrSignExtend(Op, I->getType()); 5721 else 5722 Op = getNoopOrZeroExtend(Op, I->getType()); 5723 return Op; 5724 }; 5725 LS = CoerceOperand(LS); 5726 RS = CoerceOperand(RS); 5727 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5728 break; 5729 const SCEV *LDiff = getMinusSCEV(LA, LS); 5730 const SCEV *RDiff = getMinusSCEV(RA, RS); 5731 if (LDiff == RDiff) 5732 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5733 LDiff); 5734 LDiff = getMinusSCEV(LA, RS); 5735 RDiff = getMinusSCEV(RA, LS); 5736 if (LDiff == RDiff) 5737 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5738 LDiff); 5739 } 5740 break; 5741 case ICmpInst::ICMP_NE: 5742 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5743 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5744 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5745 const SCEV *One = getOne(I->getType()); 5746 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5747 const SCEV *LA = getSCEV(TrueVal); 5748 const SCEV *RA = getSCEV(FalseVal); 5749 const SCEV *LDiff = getMinusSCEV(LA, LS); 5750 const SCEV *RDiff = getMinusSCEV(RA, One); 5751 if (LDiff == RDiff) 5752 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5753 } 5754 break; 5755 case ICmpInst::ICMP_EQ: 5756 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5757 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5758 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5759 const SCEV *One = getOne(I->getType()); 5760 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5761 const SCEV *LA = getSCEV(TrueVal); 5762 const SCEV *RA = getSCEV(FalseVal); 5763 const SCEV *LDiff = getMinusSCEV(LA, One); 5764 const SCEV *RDiff = getMinusSCEV(RA, LS); 5765 if (LDiff == RDiff) 5766 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5767 } 5768 break; 5769 default: 5770 break; 5771 } 5772 5773 return getUnknown(I); 5774 } 5775 5776 /// Expand GEP instructions into add and multiply operations. This allows them 5777 /// to be analyzed by regular SCEV code. 5778 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5779 // Don't attempt to analyze GEPs over unsized objects. 5780 if (!GEP->getSourceElementType()->isSized()) 5781 return getUnknown(GEP); 5782 5783 SmallVector<const SCEV *, 4> IndexExprs; 5784 for (Value *Index : GEP->indices()) 5785 IndexExprs.push_back(getSCEV(Index)); 5786 return getGEPExpr(GEP, IndexExprs); 5787 } 5788 5789 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5790 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5791 return C->getAPInt().countTrailingZeros(); 5792 5793 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5794 return GetMinTrailingZeros(I->getOperand()); 5795 5796 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5797 return std::min(GetMinTrailingZeros(T->getOperand()), 5798 (uint32_t)getTypeSizeInBits(T->getType())); 5799 5800 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5801 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5802 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5803 ? getTypeSizeInBits(E->getType()) 5804 : OpRes; 5805 } 5806 5807 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5808 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5809 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5810 ? getTypeSizeInBits(E->getType()) 5811 : OpRes; 5812 } 5813 5814 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5815 // The result is the min of all operands results. 5816 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5817 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5818 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5819 return MinOpRes; 5820 } 5821 5822 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5823 // The result is the sum of all operands results. 5824 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5825 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5826 for (unsigned i = 1, e = M->getNumOperands(); 5827 SumOpRes != BitWidth && i != e; ++i) 5828 SumOpRes = 5829 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5830 return SumOpRes; 5831 } 5832 5833 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5834 // The result is the min of all operands results. 5835 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5836 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5837 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5838 return MinOpRes; 5839 } 5840 5841 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5842 // The result is the min of all operands results. 5843 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5844 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5845 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5846 return MinOpRes; 5847 } 5848 5849 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5850 // The result is the min of all operands results. 5851 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5852 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5853 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5854 return MinOpRes; 5855 } 5856 5857 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5858 // For a SCEVUnknown, ask ValueTracking. 5859 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5860 return Known.countMinTrailingZeros(); 5861 } 5862 5863 // SCEVUDivExpr 5864 return 0; 5865 } 5866 5867 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5868 auto I = MinTrailingZerosCache.find(S); 5869 if (I != MinTrailingZerosCache.end()) 5870 return I->second; 5871 5872 uint32_t Result = GetMinTrailingZerosImpl(S); 5873 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5874 assert(InsertPair.second && "Should insert a new key"); 5875 return InsertPair.first->second; 5876 } 5877 5878 /// Helper method to assign a range to V from metadata present in the IR. 5879 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5880 if (Instruction *I = dyn_cast<Instruction>(V)) 5881 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5882 return getConstantRangeFromMetadata(*MD); 5883 5884 return None; 5885 } 5886 5887 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5888 SCEV::NoWrapFlags Flags) { 5889 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5890 AddRec->setNoWrapFlags(Flags); 5891 UnsignedRanges.erase(AddRec); 5892 SignedRanges.erase(AddRec); 5893 } 5894 } 5895 5896 ConstantRange ScalarEvolution:: 5897 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5898 const DataLayout &DL = getDataLayout(); 5899 5900 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5901 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5902 5903 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5904 // use information about the trip count to improve our available range. Note 5905 // that the trip count independent cases are already handled by known bits. 5906 // WARNING: The definition of recurrence used here is subtly different than 5907 // the one used by AddRec (and thus most of this file). Step is allowed to 5908 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5909 // and other addrecs in the same loop (for non-affine addrecs). The code 5910 // below intentionally handles the case where step is not loop invariant. 5911 auto *P = dyn_cast<PHINode>(U->getValue()); 5912 if (!P) 5913 return FullSet; 5914 5915 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5916 // even the values that are not available in these blocks may come from them, 5917 // and this leads to false-positive recurrence test. 5918 for (auto *Pred : predecessors(P->getParent())) 5919 if (!DT.isReachableFromEntry(Pred)) 5920 return FullSet; 5921 5922 BinaryOperator *BO; 5923 Value *Start, *Step; 5924 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5925 return FullSet; 5926 5927 // If we found a recurrence in reachable code, we must be in a loop. Note 5928 // that BO might be in some subloop of L, and that's completely okay. 5929 auto *L = LI.getLoopFor(P->getParent()); 5930 assert(L && L->getHeader() == P->getParent()); 5931 if (!L->contains(BO->getParent())) 5932 // NOTE: This bailout should be an assert instead. However, asserting 5933 // the condition here exposes a case where LoopFusion is querying SCEV 5934 // with malformed loop information during the midst of the transform. 5935 // There doesn't appear to be an obvious fix, so for the moment bailout 5936 // until the caller issue can be fixed. PR49566 tracks the bug. 5937 return FullSet; 5938 5939 // TODO: Extend to other opcodes such as mul, and div 5940 switch (BO->getOpcode()) { 5941 default: 5942 return FullSet; 5943 case Instruction::AShr: 5944 case Instruction::LShr: 5945 case Instruction::Shl: 5946 break; 5947 }; 5948 5949 if (BO->getOperand(0) != P) 5950 // TODO: Handle the power function forms some day. 5951 return FullSet; 5952 5953 unsigned TC = getSmallConstantMaxTripCount(L); 5954 if (!TC || TC >= BitWidth) 5955 return FullSet; 5956 5957 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5958 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5959 assert(KnownStart.getBitWidth() == BitWidth && 5960 KnownStep.getBitWidth() == BitWidth); 5961 5962 // Compute total shift amount, being careful of overflow and bitwidths. 5963 auto MaxShiftAmt = KnownStep.getMaxValue(); 5964 APInt TCAP(BitWidth, TC-1); 5965 bool Overflow = false; 5966 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5967 if (Overflow) 5968 return FullSet; 5969 5970 switch (BO->getOpcode()) { 5971 default: 5972 llvm_unreachable("filtered out above"); 5973 case Instruction::AShr: { 5974 // For each ashr, three cases: 5975 // shift = 0 => unchanged value 5976 // saturation => 0 or -1 5977 // other => a value closer to zero (of the same sign) 5978 // Thus, the end value is closer to zero than the start. 5979 auto KnownEnd = KnownBits::ashr(KnownStart, 5980 KnownBits::makeConstant(TotalShift)); 5981 if (KnownStart.isNonNegative()) 5982 // Analogous to lshr (simply not yet canonicalized) 5983 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5984 KnownStart.getMaxValue() + 1); 5985 if (KnownStart.isNegative()) 5986 // End >=u Start && End <=s Start 5987 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5988 KnownEnd.getMaxValue() + 1); 5989 break; 5990 } 5991 case Instruction::LShr: { 5992 // For each lshr, three cases: 5993 // shift = 0 => unchanged value 5994 // saturation => 0 5995 // other => a smaller positive number 5996 // Thus, the low end of the unsigned range is the last value produced. 5997 auto KnownEnd = KnownBits::lshr(KnownStart, 5998 KnownBits::makeConstant(TotalShift)); 5999 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6000 KnownStart.getMaxValue() + 1); 6001 } 6002 case Instruction::Shl: { 6003 // Iff no bits are shifted out, value increases on every shift. 6004 auto KnownEnd = KnownBits::shl(KnownStart, 6005 KnownBits::makeConstant(TotalShift)); 6006 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6007 return ConstantRange(KnownStart.getMinValue(), 6008 KnownEnd.getMaxValue() + 1); 6009 break; 6010 } 6011 }; 6012 return FullSet; 6013 } 6014 6015 /// Determine the range for a particular SCEV. If SignHint is 6016 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6017 /// with a "cleaner" unsigned (resp. signed) representation. 6018 const ConstantRange & 6019 ScalarEvolution::getRangeRef(const SCEV *S, 6020 ScalarEvolution::RangeSignHint SignHint) { 6021 DenseMap<const SCEV *, ConstantRange> &Cache = 6022 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6023 : SignedRanges; 6024 ConstantRange::PreferredRangeType RangeType = 6025 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6026 ? ConstantRange::Unsigned : ConstantRange::Signed; 6027 6028 // See if we've computed this range already. 6029 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6030 if (I != Cache.end()) 6031 return I->second; 6032 6033 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6034 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6035 6036 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6037 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6038 using OBO = OverflowingBinaryOperator; 6039 6040 // If the value has known zeros, the maximum value will have those known zeros 6041 // as well. 6042 uint32_t TZ = GetMinTrailingZeros(S); 6043 if (TZ != 0) { 6044 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6045 ConservativeResult = 6046 ConstantRange(APInt::getMinValue(BitWidth), 6047 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6048 else 6049 ConservativeResult = ConstantRange( 6050 APInt::getSignedMinValue(BitWidth), 6051 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6052 } 6053 6054 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6055 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6056 unsigned WrapType = OBO::AnyWrap; 6057 if (Add->hasNoSignedWrap()) 6058 WrapType |= OBO::NoSignedWrap; 6059 if (Add->hasNoUnsignedWrap()) 6060 WrapType |= OBO::NoUnsignedWrap; 6061 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6062 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6063 WrapType, RangeType); 6064 return setRange(Add, SignHint, 6065 ConservativeResult.intersectWith(X, RangeType)); 6066 } 6067 6068 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6069 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6070 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6071 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6072 return setRange(Mul, SignHint, 6073 ConservativeResult.intersectWith(X, RangeType)); 6074 } 6075 6076 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6077 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6078 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6079 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6080 return setRange(SMax, SignHint, 6081 ConservativeResult.intersectWith(X, RangeType)); 6082 } 6083 6084 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6085 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6086 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6087 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6088 return setRange(UMax, SignHint, 6089 ConservativeResult.intersectWith(X, RangeType)); 6090 } 6091 6092 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6093 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6094 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6095 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6096 return setRange(SMin, SignHint, 6097 ConservativeResult.intersectWith(X, RangeType)); 6098 } 6099 6100 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6101 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6102 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6103 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6104 return setRange(UMin, SignHint, 6105 ConservativeResult.intersectWith(X, RangeType)); 6106 } 6107 6108 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6109 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6110 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6111 return setRange(UDiv, SignHint, 6112 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6113 } 6114 6115 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6116 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6117 return setRange(ZExt, SignHint, 6118 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6119 RangeType)); 6120 } 6121 6122 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6123 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6124 return setRange(SExt, SignHint, 6125 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6126 RangeType)); 6127 } 6128 6129 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6130 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6131 return setRange(PtrToInt, SignHint, X); 6132 } 6133 6134 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6135 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6136 return setRange(Trunc, SignHint, 6137 ConservativeResult.intersectWith(X.truncate(BitWidth), 6138 RangeType)); 6139 } 6140 6141 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6142 // If there's no unsigned wrap, the value will never be less than its 6143 // initial value. 6144 if (AddRec->hasNoUnsignedWrap()) { 6145 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6146 if (!UnsignedMinValue.isZero()) 6147 ConservativeResult = ConservativeResult.intersectWith( 6148 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6149 } 6150 6151 // If there's no signed wrap, and all the operands except initial value have 6152 // the same sign or zero, the value won't ever be: 6153 // 1: smaller than initial value if operands are non negative, 6154 // 2: bigger than initial value if operands are non positive. 6155 // For both cases, value can not cross signed min/max boundary. 6156 if (AddRec->hasNoSignedWrap()) { 6157 bool AllNonNeg = true; 6158 bool AllNonPos = true; 6159 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6160 if (!isKnownNonNegative(AddRec->getOperand(i))) 6161 AllNonNeg = false; 6162 if (!isKnownNonPositive(AddRec->getOperand(i))) 6163 AllNonPos = false; 6164 } 6165 if (AllNonNeg) 6166 ConservativeResult = ConservativeResult.intersectWith( 6167 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6168 APInt::getSignedMinValue(BitWidth)), 6169 RangeType); 6170 else if (AllNonPos) 6171 ConservativeResult = ConservativeResult.intersectWith( 6172 ConstantRange::getNonEmpty( 6173 APInt::getSignedMinValue(BitWidth), 6174 getSignedRangeMax(AddRec->getStart()) + 1), 6175 RangeType); 6176 } 6177 6178 // TODO: non-affine addrec 6179 if (AddRec->isAffine()) { 6180 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6181 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6182 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6183 auto RangeFromAffine = getRangeForAffineAR( 6184 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6185 BitWidth); 6186 ConservativeResult = 6187 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6188 6189 auto RangeFromFactoring = getRangeViaFactoring( 6190 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6191 BitWidth); 6192 ConservativeResult = 6193 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6194 } 6195 6196 // Now try symbolic BE count and more powerful methods. 6197 if (UseExpensiveRangeSharpening) { 6198 const SCEV *SymbolicMaxBECount = 6199 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6200 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6201 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6202 AddRec->hasNoSelfWrap()) { 6203 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6204 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6205 ConservativeResult = 6206 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6207 } 6208 } 6209 } 6210 6211 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6212 } 6213 6214 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6215 6216 // Check if the IR explicitly contains !range metadata. 6217 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6218 if (MDRange.hasValue()) 6219 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6220 RangeType); 6221 6222 // Use facts about recurrences in the underlying IR. Note that add 6223 // recurrences are AddRecExprs and thus don't hit this path. This 6224 // primarily handles shift recurrences. 6225 auto CR = getRangeForUnknownRecurrence(U); 6226 ConservativeResult = ConservativeResult.intersectWith(CR); 6227 6228 // See if ValueTracking can give us a useful range. 6229 const DataLayout &DL = getDataLayout(); 6230 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6231 if (Known.getBitWidth() != BitWidth) 6232 Known = Known.zextOrTrunc(BitWidth); 6233 6234 // ValueTracking may be able to compute a tighter result for the number of 6235 // sign bits than for the value of those sign bits. 6236 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6237 if (U->getType()->isPointerTy()) { 6238 // If the pointer size is larger than the index size type, this can cause 6239 // NS to be larger than BitWidth. So compensate for this. 6240 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6241 int ptrIdxDiff = ptrSize - BitWidth; 6242 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6243 NS -= ptrIdxDiff; 6244 } 6245 6246 if (NS > 1) { 6247 // If we know any of the sign bits, we know all of the sign bits. 6248 if (!Known.Zero.getHiBits(NS).isZero()) 6249 Known.Zero.setHighBits(NS); 6250 if (!Known.One.getHiBits(NS).isZero()) 6251 Known.One.setHighBits(NS); 6252 } 6253 6254 if (Known.getMinValue() != Known.getMaxValue() + 1) 6255 ConservativeResult = ConservativeResult.intersectWith( 6256 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6257 RangeType); 6258 if (NS > 1) 6259 ConservativeResult = ConservativeResult.intersectWith( 6260 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6261 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6262 RangeType); 6263 6264 // A range of Phi is a subset of union of all ranges of its input. 6265 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6266 // Make sure that we do not run over cycled Phis. 6267 if (PendingPhiRanges.insert(Phi).second) { 6268 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6269 for (auto &Op : Phi->operands()) { 6270 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6271 RangeFromOps = RangeFromOps.unionWith(OpRange); 6272 // No point to continue if we already have a full set. 6273 if (RangeFromOps.isFullSet()) 6274 break; 6275 } 6276 ConservativeResult = 6277 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6278 bool Erased = PendingPhiRanges.erase(Phi); 6279 assert(Erased && "Failed to erase Phi properly?"); 6280 (void) Erased; 6281 } 6282 } 6283 6284 return setRange(U, SignHint, std::move(ConservativeResult)); 6285 } 6286 6287 return setRange(S, SignHint, std::move(ConservativeResult)); 6288 } 6289 6290 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6291 // values that the expression can take. Initially, the expression has a value 6292 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6293 // argument defines if we treat Step as signed or unsigned. 6294 static ConstantRange getRangeForAffineARHelper(APInt Step, 6295 const ConstantRange &StartRange, 6296 const APInt &MaxBECount, 6297 unsigned BitWidth, bool Signed) { 6298 // If either Step or MaxBECount is 0, then the expression won't change, and we 6299 // just need to return the initial range. 6300 if (Step == 0 || MaxBECount == 0) 6301 return StartRange; 6302 6303 // If we don't know anything about the initial value (i.e. StartRange is 6304 // FullRange), then we don't know anything about the final range either. 6305 // Return FullRange. 6306 if (StartRange.isFullSet()) 6307 return ConstantRange::getFull(BitWidth); 6308 6309 // If Step is signed and negative, then we use its absolute value, but we also 6310 // note that we're moving in the opposite direction. 6311 bool Descending = Signed && Step.isNegative(); 6312 6313 if (Signed) 6314 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6315 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6316 // This equations hold true due to the well-defined wrap-around behavior of 6317 // APInt. 6318 Step = Step.abs(); 6319 6320 // Check if Offset is more than full span of BitWidth. If it is, the 6321 // expression is guaranteed to overflow. 6322 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6323 return ConstantRange::getFull(BitWidth); 6324 6325 // Offset is by how much the expression can change. Checks above guarantee no 6326 // overflow here. 6327 APInt Offset = Step * MaxBECount; 6328 6329 // Minimum value of the final range will match the minimal value of StartRange 6330 // if the expression is increasing and will be decreased by Offset otherwise. 6331 // Maximum value of the final range will match the maximal value of StartRange 6332 // if the expression is decreasing and will be increased by Offset otherwise. 6333 APInt StartLower = StartRange.getLower(); 6334 APInt StartUpper = StartRange.getUpper() - 1; 6335 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6336 : (StartUpper + std::move(Offset)); 6337 6338 // It's possible that the new minimum/maximum value will fall into the initial 6339 // range (due to wrap around). This means that the expression can take any 6340 // value in this bitwidth, and we have to return full range. 6341 if (StartRange.contains(MovedBoundary)) 6342 return ConstantRange::getFull(BitWidth); 6343 6344 APInt NewLower = 6345 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6346 APInt NewUpper = 6347 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6348 NewUpper += 1; 6349 6350 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6351 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6352 } 6353 6354 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6355 const SCEV *Step, 6356 const SCEV *MaxBECount, 6357 unsigned BitWidth) { 6358 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6359 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6360 "Precondition!"); 6361 6362 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6363 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6364 6365 // First, consider step signed. 6366 ConstantRange StartSRange = getSignedRange(Start); 6367 ConstantRange StepSRange = getSignedRange(Step); 6368 6369 // If Step can be both positive and negative, we need to find ranges for the 6370 // maximum absolute step values in both directions and union them. 6371 ConstantRange SR = 6372 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6373 MaxBECountValue, BitWidth, /* Signed = */ true); 6374 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6375 StartSRange, MaxBECountValue, 6376 BitWidth, /* Signed = */ true)); 6377 6378 // Next, consider step unsigned. 6379 ConstantRange UR = getRangeForAffineARHelper( 6380 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6381 MaxBECountValue, BitWidth, /* Signed = */ false); 6382 6383 // Finally, intersect signed and unsigned ranges. 6384 return SR.intersectWith(UR, ConstantRange::Smallest); 6385 } 6386 6387 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6388 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6389 ScalarEvolution::RangeSignHint SignHint) { 6390 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6391 assert(AddRec->hasNoSelfWrap() && 6392 "This only works for non-self-wrapping AddRecs!"); 6393 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6394 const SCEV *Step = AddRec->getStepRecurrence(*this); 6395 // Only deal with constant step to save compile time. 6396 if (!isa<SCEVConstant>(Step)) 6397 return ConstantRange::getFull(BitWidth); 6398 // Let's make sure that we can prove that we do not self-wrap during 6399 // MaxBECount iterations. We need this because MaxBECount is a maximum 6400 // iteration count estimate, and we might infer nw from some exit for which we 6401 // do not know max exit count (or any other side reasoning). 6402 // TODO: Turn into assert at some point. 6403 if (getTypeSizeInBits(MaxBECount->getType()) > 6404 getTypeSizeInBits(AddRec->getType())) 6405 return ConstantRange::getFull(BitWidth); 6406 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6407 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6408 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6409 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6410 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6411 MaxItersWithoutWrap)) 6412 return ConstantRange::getFull(BitWidth); 6413 6414 ICmpInst::Predicate LEPred = 6415 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6416 ICmpInst::Predicate GEPred = 6417 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6418 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6419 6420 // We know that there is no self-wrap. Let's take Start and End values and 6421 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6422 // the iteration. They either lie inside the range [Min(Start, End), 6423 // Max(Start, End)] or outside it: 6424 // 6425 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6426 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6427 // 6428 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6429 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6430 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6431 // Start <= End and step is positive, or Start >= End and step is negative. 6432 const SCEV *Start = AddRec->getStart(); 6433 ConstantRange StartRange = getRangeRef(Start, SignHint); 6434 ConstantRange EndRange = getRangeRef(End, SignHint); 6435 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6436 // If they already cover full iteration space, we will know nothing useful 6437 // even if we prove what we want to prove. 6438 if (RangeBetween.isFullSet()) 6439 return RangeBetween; 6440 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6441 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6442 : RangeBetween.isWrappedSet(); 6443 if (IsWrappedSet) 6444 return ConstantRange::getFull(BitWidth); 6445 6446 if (isKnownPositive(Step) && 6447 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6448 return RangeBetween; 6449 else if (isKnownNegative(Step) && 6450 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6451 return RangeBetween; 6452 return ConstantRange::getFull(BitWidth); 6453 } 6454 6455 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6456 const SCEV *Step, 6457 const SCEV *MaxBECount, 6458 unsigned BitWidth) { 6459 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6460 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6461 6462 struct SelectPattern { 6463 Value *Condition = nullptr; 6464 APInt TrueValue; 6465 APInt FalseValue; 6466 6467 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6468 const SCEV *S) { 6469 Optional<unsigned> CastOp; 6470 APInt Offset(BitWidth, 0); 6471 6472 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6473 "Should be!"); 6474 6475 // Peel off a constant offset: 6476 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6477 // In the future we could consider being smarter here and handle 6478 // {Start+Step,+,Step} too. 6479 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6480 return; 6481 6482 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6483 S = SA->getOperand(1); 6484 } 6485 6486 // Peel off a cast operation 6487 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6488 CastOp = SCast->getSCEVType(); 6489 S = SCast->getOperand(); 6490 } 6491 6492 using namespace llvm::PatternMatch; 6493 6494 auto *SU = dyn_cast<SCEVUnknown>(S); 6495 const APInt *TrueVal, *FalseVal; 6496 if (!SU || 6497 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6498 m_APInt(FalseVal)))) { 6499 Condition = nullptr; 6500 return; 6501 } 6502 6503 TrueValue = *TrueVal; 6504 FalseValue = *FalseVal; 6505 6506 // Re-apply the cast we peeled off earlier 6507 if (CastOp.hasValue()) 6508 switch (*CastOp) { 6509 default: 6510 llvm_unreachable("Unknown SCEV cast type!"); 6511 6512 case scTruncate: 6513 TrueValue = TrueValue.trunc(BitWidth); 6514 FalseValue = FalseValue.trunc(BitWidth); 6515 break; 6516 case scZeroExtend: 6517 TrueValue = TrueValue.zext(BitWidth); 6518 FalseValue = FalseValue.zext(BitWidth); 6519 break; 6520 case scSignExtend: 6521 TrueValue = TrueValue.sext(BitWidth); 6522 FalseValue = FalseValue.sext(BitWidth); 6523 break; 6524 } 6525 6526 // Re-apply the constant offset we peeled off earlier 6527 TrueValue += Offset; 6528 FalseValue += Offset; 6529 } 6530 6531 bool isRecognized() { return Condition != nullptr; } 6532 }; 6533 6534 SelectPattern StartPattern(*this, BitWidth, Start); 6535 if (!StartPattern.isRecognized()) 6536 return ConstantRange::getFull(BitWidth); 6537 6538 SelectPattern StepPattern(*this, BitWidth, Step); 6539 if (!StepPattern.isRecognized()) 6540 return ConstantRange::getFull(BitWidth); 6541 6542 if (StartPattern.Condition != StepPattern.Condition) { 6543 // We don't handle this case today; but we could, by considering four 6544 // possibilities below instead of two. I'm not sure if there are cases where 6545 // that will help over what getRange already does, though. 6546 return ConstantRange::getFull(BitWidth); 6547 } 6548 6549 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6550 // construct arbitrary general SCEV expressions here. This function is called 6551 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6552 // say) can end up caching a suboptimal value. 6553 6554 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6555 // C2352 and C2512 (otherwise it isn't needed). 6556 6557 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6558 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6559 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6560 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6561 6562 ConstantRange TrueRange = 6563 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6564 ConstantRange FalseRange = 6565 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6566 6567 return TrueRange.unionWith(FalseRange); 6568 } 6569 6570 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6571 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6572 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6573 6574 // Return early if there are no flags to propagate to the SCEV. 6575 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6576 if (BinOp->hasNoUnsignedWrap()) 6577 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6578 if (BinOp->hasNoSignedWrap()) 6579 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6580 if (Flags == SCEV::FlagAnyWrap) 6581 return SCEV::FlagAnyWrap; 6582 6583 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6584 } 6585 6586 const Instruction * 6587 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6588 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6589 return &*AddRec->getLoop()->getHeader()->begin(); 6590 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6591 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6592 return I; 6593 return nullptr; 6594 } 6595 6596 const Instruction * 6597 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6598 // Do a bounded search of the def relation of the requested SCEVs. 6599 SmallSet<const SCEV *, 16> Visited; 6600 SmallVector<const SCEV *> Worklist; 6601 auto pushOp = [&](const SCEV *S) { 6602 if (!Visited.insert(S).second) 6603 return; 6604 // Threshold of 30 here is arbitrary. 6605 if (Visited.size() > 30) 6606 return; 6607 Worklist.push_back(S); 6608 }; 6609 6610 for (auto *S : Ops) 6611 pushOp(S); 6612 6613 const Instruction *Bound = nullptr; 6614 while (!Worklist.empty()) { 6615 auto *S = Worklist.pop_back_val(); 6616 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6617 if (!Bound || DT.dominates(Bound, DefI)) 6618 Bound = DefI; 6619 } else if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6620 for (auto *Op : S2->operands()) 6621 pushOp(Op); 6622 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6623 for (auto *Op : S2->operands()) 6624 pushOp(Op); 6625 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6626 for (auto *Op : S2->operands()) 6627 pushOp(Op); 6628 } 6629 return Bound ? Bound : &*F.getEntryBlock().begin(); 6630 } 6631 6632 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6633 const Instruction *B) { 6634 if (A->getParent() == B->getParent() && 6635 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6636 B->getIterator())) 6637 return true; 6638 6639 auto *BLoop = LI.getLoopFor(B->getParent()); 6640 if (BLoop && BLoop->getHeader() == B->getParent() && 6641 BLoop->getLoopPreheader() == A->getParent() && 6642 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6643 A->getParent()->end()) && 6644 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6645 B->getIterator())) 6646 return true; 6647 return false; 6648 } 6649 6650 6651 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6652 // Only proceed if we can prove that I does not yield poison. 6653 if (!programUndefinedIfPoison(I)) 6654 return false; 6655 6656 // At this point we know that if I is executed, then it does not wrap 6657 // according to at least one of NSW or NUW. If I is not executed, then we do 6658 // not know if the calculation that I represents would wrap. Multiple 6659 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6660 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6661 // derived from other instructions that map to the same SCEV. We cannot make 6662 // that guarantee for cases where I is not executed. So we need to find a 6663 // upper bound on the defining scope for the SCEV, and prove that I is 6664 // executed every time we enter that scope. When the bounding scope is a 6665 // loop (the common case), this is equivalent to proving I executes on every 6666 // iteration of that loop. 6667 SmallVector<const SCEV *> SCEVOps; 6668 for (const Use &Op : I->operands()) { 6669 // I could be an extractvalue from a call to an overflow intrinsic. 6670 // TODO: We can do better here in some cases. 6671 if (isSCEVable(Op->getType())) 6672 SCEVOps.push_back(getSCEV(Op)); 6673 } 6674 auto *DefI = getDefiningScopeBound(SCEVOps); 6675 return isGuaranteedToTransferExecutionTo(DefI, I); 6676 } 6677 6678 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6679 // If we know that \c I can never be poison period, then that's enough. 6680 if (isSCEVExprNeverPoison(I)) 6681 return true; 6682 6683 // For an add recurrence specifically, we assume that infinite loops without 6684 // side effects are undefined behavior, and then reason as follows: 6685 // 6686 // If the add recurrence is poison in any iteration, it is poison on all 6687 // future iterations (since incrementing poison yields poison). If the result 6688 // of the add recurrence is fed into the loop latch condition and the loop 6689 // does not contain any throws or exiting blocks other than the latch, we now 6690 // have the ability to "choose" whether the backedge is taken or not (by 6691 // choosing a sufficiently evil value for the poison feeding into the branch) 6692 // for every iteration including and after the one in which \p I first became 6693 // poison. There are two possibilities (let's call the iteration in which \p 6694 // I first became poison as K): 6695 // 6696 // 1. In the set of iterations including and after K, the loop body executes 6697 // no side effects. In this case executing the backege an infinte number 6698 // of times will yield undefined behavior. 6699 // 6700 // 2. In the set of iterations including and after K, the loop body executes 6701 // at least one side effect. In this case, that specific instance of side 6702 // effect is control dependent on poison, which also yields undefined 6703 // behavior. 6704 6705 auto *ExitingBB = L->getExitingBlock(); 6706 auto *LatchBB = L->getLoopLatch(); 6707 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6708 return false; 6709 6710 SmallPtrSet<const Instruction *, 16> Pushed; 6711 SmallVector<const Instruction *, 8> PoisonStack; 6712 6713 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6714 // things that are known to be poison under that assumption go on the 6715 // PoisonStack. 6716 Pushed.insert(I); 6717 PoisonStack.push_back(I); 6718 6719 bool LatchControlDependentOnPoison = false; 6720 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6721 const Instruction *Poison = PoisonStack.pop_back_val(); 6722 6723 for (auto *PoisonUser : Poison->users()) { 6724 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6725 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6726 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6727 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6728 assert(BI->isConditional() && "Only possibility!"); 6729 if (BI->getParent() == LatchBB) { 6730 LatchControlDependentOnPoison = true; 6731 break; 6732 } 6733 } 6734 } 6735 } 6736 6737 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6738 } 6739 6740 ScalarEvolution::LoopProperties 6741 ScalarEvolution::getLoopProperties(const Loop *L) { 6742 using LoopProperties = ScalarEvolution::LoopProperties; 6743 6744 auto Itr = LoopPropertiesCache.find(L); 6745 if (Itr == LoopPropertiesCache.end()) { 6746 auto HasSideEffects = [](Instruction *I) { 6747 if (auto *SI = dyn_cast<StoreInst>(I)) 6748 return !SI->isSimple(); 6749 6750 return I->mayThrow() || I->mayWriteToMemory(); 6751 }; 6752 6753 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6754 /*HasNoSideEffects*/ true}; 6755 6756 for (auto *BB : L->getBlocks()) 6757 for (auto &I : *BB) { 6758 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6759 LP.HasNoAbnormalExits = false; 6760 if (HasSideEffects(&I)) 6761 LP.HasNoSideEffects = false; 6762 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6763 break; // We're already as pessimistic as we can get. 6764 } 6765 6766 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6767 assert(InsertPair.second && "We just checked!"); 6768 Itr = InsertPair.first; 6769 } 6770 6771 return Itr->second; 6772 } 6773 6774 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6775 // A mustprogress loop without side effects must be finite. 6776 // TODO: The check used here is very conservative. It's only *specific* 6777 // side effects which are well defined in infinite loops. 6778 return isMustProgress(L) && loopHasNoSideEffects(L); 6779 } 6780 6781 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6782 if (!isSCEVable(V->getType())) 6783 return getUnknown(V); 6784 6785 if (Instruction *I = dyn_cast<Instruction>(V)) { 6786 // Don't attempt to analyze instructions in blocks that aren't 6787 // reachable. Such instructions don't matter, and they aren't required 6788 // to obey basic rules for definitions dominating uses which this 6789 // analysis depends on. 6790 if (!DT.isReachableFromEntry(I->getParent())) 6791 return getUnknown(UndefValue::get(V->getType())); 6792 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6793 return getConstant(CI); 6794 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6795 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6796 else if (!isa<ConstantExpr>(V)) 6797 return getUnknown(V); 6798 6799 Operator *U = cast<Operator>(V); 6800 if (auto BO = MatchBinaryOp(U, DT)) { 6801 switch (BO->Opcode) { 6802 case Instruction::Add: { 6803 // The simple thing to do would be to just call getSCEV on both operands 6804 // and call getAddExpr with the result. However if we're looking at a 6805 // bunch of things all added together, this can be quite inefficient, 6806 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6807 // Instead, gather up all the operands and make a single getAddExpr call. 6808 // LLVM IR canonical form means we need only traverse the left operands. 6809 SmallVector<const SCEV *, 4> AddOps; 6810 do { 6811 if (BO->Op) { 6812 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6813 AddOps.push_back(OpSCEV); 6814 break; 6815 } 6816 6817 // If a NUW or NSW flag can be applied to the SCEV for this 6818 // addition, then compute the SCEV for this addition by itself 6819 // with a separate call to getAddExpr. We need to do that 6820 // instead of pushing the operands of the addition onto AddOps, 6821 // since the flags are only known to apply to this particular 6822 // addition - they may not apply to other additions that can be 6823 // formed with operands from AddOps. 6824 const SCEV *RHS = getSCEV(BO->RHS); 6825 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6826 if (Flags != SCEV::FlagAnyWrap) { 6827 const SCEV *LHS = getSCEV(BO->LHS); 6828 if (BO->Opcode == Instruction::Sub) 6829 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6830 else 6831 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6832 break; 6833 } 6834 } 6835 6836 if (BO->Opcode == Instruction::Sub) 6837 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6838 else 6839 AddOps.push_back(getSCEV(BO->RHS)); 6840 6841 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6842 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6843 NewBO->Opcode != Instruction::Sub)) { 6844 AddOps.push_back(getSCEV(BO->LHS)); 6845 break; 6846 } 6847 BO = NewBO; 6848 } while (true); 6849 6850 return getAddExpr(AddOps); 6851 } 6852 6853 case Instruction::Mul: { 6854 SmallVector<const SCEV *, 4> MulOps; 6855 do { 6856 if (BO->Op) { 6857 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6858 MulOps.push_back(OpSCEV); 6859 break; 6860 } 6861 6862 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6863 if (Flags != SCEV::FlagAnyWrap) { 6864 MulOps.push_back( 6865 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6866 break; 6867 } 6868 } 6869 6870 MulOps.push_back(getSCEV(BO->RHS)); 6871 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6872 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6873 MulOps.push_back(getSCEV(BO->LHS)); 6874 break; 6875 } 6876 BO = NewBO; 6877 } while (true); 6878 6879 return getMulExpr(MulOps); 6880 } 6881 case Instruction::UDiv: 6882 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6883 case Instruction::URem: 6884 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6885 case Instruction::Sub: { 6886 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6887 if (BO->Op) 6888 Flags = getNoWrapFlagsFromUB(BO->Op); 6889 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6890 } 6891 case Instruction::And: 6892 // For an expression like x&255 that merely masks off the high bits, 6893 // use zext(trunc(x)) as the SCEV expression. 6894 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6895 if (CI->isZero()) 6896 return getSCEV(BO->RHS); 6897 if (CI->isMinusOne()) 6898 return getSCEV(BO->LHS); 6899 const APInt &A = CI->getValue(); 6900 6901 // Instcombine's ShrinkDemandedConstant may strip bits out of 6902 // constants, obscuring what would otherwise be a low-bits mask. 6903 // Use computeKnownBits to compute what ShrinkDemandedConstant 6904 // knew about to reconstruct a low-bits mask value. 6905 unsigned LZ = A.countLeadingZeros(); 6906 unsigned TZ = A.countTrailingZeros(); 6907 unsigned BitWidth = A.getBitWidth(); 6908 KnownBits Known(BitWidth); 6909 computeKnownBits(BO->LHS, Known, getDataLayout(), 6910 0, &AC, nullptr, &DT); 6911 6912 APInt EffectiveMask = 6913 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6914 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6915 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6916 const SCEV *LHS = getSCEV(BO->LHS); 6917 const SCEV *ShiftedLHS = nullptr; 6918 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6919 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6920 // For an expression like (x * 8) & 8, simplify the multiply. 6921 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6922 unsigned GCD = std::min(MulZeros, TZ); 6923 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6924 SmallVector<const SCEV*, 4> MulOps; 6925 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6926 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6927 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6928 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6929 } 6930 } 6931 if (!ShiftedLHS) 6932 ShiftedLHS = getUDivExpr(LHS, MulCount); 6933 return getMulExpr( 6934 getZeroExtendExpr( 6935 getTruncateExpr(ShiftedLHS, 6936 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6937 BO->LHS->getType()), 6938 MulCount); 6939 } 6940 } 6941 break; 6942 6943 case Instruction::Or: 6944 // If the RHS of the Or is a constant, we may have something like: 6945 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6946 // optimizations will transparently handle this case. 6947 // 6948 // In order for this transformation to be safe, the LHS must be of the 6949 // form X*(2^n) and the Or constant must be less than 2^n. 6950 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6951 const SCEV *LHS = getSCEV(BO->LHS); 6952 const APInt &CIVal = CI->getValue(); 6953 if (GetMinTrailingZeros(LHS) >= 6954 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6955 // Build a plain add SCEV. 6956 return getAddExpr(LHS, getSCEV(CI), 6957 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6958 } 6959 } 6960 break; 6961 6962 case Instruction::Xor: 6963 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6964 // If the RHS of xor is -1, then this is a not operation. 6965 if (CI->isMinusOne()) 6966 return getNotSCEV(getSCEV(BO->LHS)); 6967 6968 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6969 // This is a variant of the check for xor with -1, and it handles 6970 // the case where instcombine has trimmed non-demanded bits out 6971 // of an xor with -1. 6972 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6973 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6974 if (LBO->getOpcode() == Instruction::And && 6975 LCI->getValue() == CI->getValue()) 6976 if (const SCEVZeroExtendExpr *Z = 6977 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6978 Type *UTy = BO->LHS->getType(); 6979 const SCEV *Z0 = Z->getOperand(); 6980 Type *Z0Ty = Z0->getType(); 6981 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6982 6983 // If C is a low-bits mask, the zero extend is serving to 6984 // mask off the high bits. Complement the operand and 6985 // re-apply the zext. 6986 if (CI->getValue().isMask(Z0TySize)) 6987 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6988 6989 // If C is a single bit, it may be in the sign-bit position 6990 // before the zero-extend. In this case, represent the xor 6991 // using an add, which is equivalent, and re-apply the zext. 6992 APInt Trunc = CI->getValue().trunc(Z0TySize); 6993 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6994 Trunc.isSignMask()) 6995 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6996 UTy); 6997 } 6998 } 6999 break; 7000 7001 case Instruction::Shl: 7002 // Turn shift left of a constant amount into a multiply. 7003 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7004 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7005 7006 // If the shift count is not less than the bitwidth, the result of 7007 // the shift is undefined. Don't try to analyze it, because the 7008 // resolution chosen here may differ from the resolution chosen in 7009 // other parts of the compiler. 7010 if (SA->getValue().uge(BitWidth)) 7011 break; 7012 7013 // We can safely preserve the nuw flag in all cases. It's also safe to 7014 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7015 // requires special handling. It can be preserved as long as we're not 7016 // left shifting by bitwidth - 1. 7017 auto Flags = SCEV::FlagAnyWrap; 7018 if (BO->Op) { 7019 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7020 if ((MulFlags & SCEV::FlagNSW) && 7021 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7022 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7023 if (MulFlags & SCEV::FlagNUW) 7024 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7025 } 7026 7027 Constant *X = ConstantInt::get( 7028 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7029 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7030 } 7031 break; 7032 7033 case Instruction::AShr: { 7034 // AShr X, C, where C is a constant. 7035 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7036 if (!CI) 7037 break; 7038 7039 Type *OuterTy = BO->LHS->getType(); 7040 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7041 // If the shift count is not less than the bitwidth, the result of 7042 // the shift is undefined. Don't try to analyze it, because the 7043 // resolution chosen here may differ from the resolution chosen in 7044 // other parts of the compiler. 7045 if (CI->getValue().uge(BitWidth)) 7046 break; 7047 7048 if (CI->isZero()) 7049 return getSCEV(BO->LHS); // shift by zero --> noop 7050 7051 uint64_t AShrAmt = CI->getZExtValue(); 7052 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7053 7054 Operator *L = dyn_cast<Operator>(BO->LHS); 7055 if (L && L->getOpcode() == Instruction::Shl) { 7056 // X = Shl A, n 7057 // Y = AShr X, m 7058 // Both n and m are constant. 7059 7060 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7061 if (L->getOperand(1) == BO->RHS) 7062 // For a two-shift sext-inreg, i.e. n = m, 7063 // use sext(trunc(x)) as the SCEV expression. 7064 return getSignExtendExpr( 7065 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7066 7067 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7068 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7069 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7070 if (ShlAmt > AShrAmt) { 7071 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7072 // expression. We already checked that ShlAmt < BitWidth, so 7073 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7074 // ShlAmt - AShrAmt < Amt. 7075 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7076 ShlAmt - AShrAmt); 7077 return getSignExtendExpr( 7078 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7079 getConstant(Mul)), OuterTy); 7080 } 7081 } 7082 } 7083 break; 7084 } 7085 } 7086 } 7087 7088 switch (U->getOpcode()) { 7089 case Instruction::Trunc: 7090 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7091 7092 case Instruction::ZExt: 7093 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7094 7095 case Instruction::SExt: 7096 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7097 // The NSW flag of a subtract does not always survive the conversion to 7098 // A + (-1)*B. By pushing sign extension onto its operands we are much 7099 // more likely to preserve NSW and allow later AddRec optimisations. 7100 // 7101 // NOTE: This is effectively duplicating this logic from getSignExtend: 7102 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7103 // but by that point the NSW information has potentially been lost. 7104 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7105 Type *Ty = U->getType(); 7106 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7107 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7108 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7109 } 7110 } 7111 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7112 7113 case Instruction::BitCast: 7114 // BitCasts are no-op casts so we just eliminate the cast. 7115 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7116 return getSCEV(U->getOperand(0)); 7117 break; 7118 7119 case Instruction::PtrToInt: { 7120 // Pointer to integer cast is straight-forward, so do model it. 7121 const SCEV *Op = getSCEV(U->getOperand(0)); 7122 Type *DstIntTy = U->getType(); 7123 // But only if effective SCEV (integer) type is wide enough to represent 7124 // all possible pointer values. 7125 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7126 if (isa<SCEVCouldNotCompute>(IntOp)) 7127 return getUnknown(V); 7128 return IntOp; 7129 } 7130 case Instruction::IntToPtr: 7131 // Just don't deal with inttoptr casts. 7132 return getUnknown(V); 7133 7134 case Instruction::SDiv: 7135 // If both operands are non-negative, this is just an udiv. 7136 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7137 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7138 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7139 break; 7140 7141 case Instruction::SRem: 7142 // If both operands are non-negative, this is just an urem. 7143 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7144 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7145 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7146 break; 7147 7148 case Instruction::GetElementPtr: 7149 return createNodeForGEP(cast<GEPOperator>(U)); 7150 7151 case Instruction::PHI: 7152 return createNodeForPHI(cast<PHINode>(U)); 7153 7154 case Instruction::Select: 7155 // U can also be a select constant expr, which let fall through. Since 7156 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7157 // constant expressions cannot have instructions as operands, we'd have 7158 // returned getUnknown for a select constant expressions anyway. 7159 if (isa<Instruction>(U)) 7160 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7161 U->getOperand(1), U->getOperand(2)); 7162 break; 7163 7164 case Instruction::Call: 7165 case Instruction::Invoke: 7166 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7167 return getSCEV(RV); 7168 7169 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7170 switch (II->getIntrinsicID()) { 7171 case Intrinsic::abs: 7172 return getAbsExpr( 7173 getSCEV(II->getArgOperand(0)), 7174 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7175 case Intrinsic::umax: 7176 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7177 getSCEV(II->getArgOperand(1))); 7178 case Intrinsic::umin: 7179 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7180 getSCEV(II->getArgOperand(1))); 7181 case Intrinsic::smax: 7182 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7183 getSCEV(II->getArgOperand(1))); 7184 case Intrinsic::smin: 7185 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7186 getSCEV(II->getArgOperand(1))); 7187 case Intrinsic::usub_sat: { 7188 const SCEV *X = getSCEV(II->getArgOperand(0)); 7189 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7190 const SCEV *ClampedY = getUMinExpr(X, Y); 7191 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7192 } 7193 case Intrinsic::uadd_sat: { 7194 const SCEV *X = getSCEV(II->getArgOperand(0)); 7195 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7196 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7197 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7198 } 7199 case Intrinsic::start_loop_iterations: 7200 // A start_loop_iterations is just equivalent to the first operand for 7201 // SCEV purposes. 7202 return getSCEV(II->getArgOperand(0)); 7203 default: 7204 break; 7205 } 7206 } 7207 break; 7208 } 7209 7210 return getUnknown(V); 7211 } 7212 7213 //===----------------------------------------------------------------------===// 7214 // Iteration Count Computation Code 7215 // 7216 7217 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7218 bool Extend) { 7219 if (isa<SCEVCouldNotCompute>(ExitCount)) 7220 return getCouldNotCompute(); 7221 7222 auto *ExitCountType = ExitCount->getType(); 7223 assert(ExitCountType->isIntegerTy()); 7224 7225 if (!Extend) 7226 return getAddExpr(ExitCount, getOne(ExitCountType)); 7227 7228 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7229 1 + ExitCountType->getScalarSizeInBits()); 7230 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7231 getOne(WiderType)); 7232 } 7233 7234 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7235 if (!ExitCount) 7236 return 0; 7237 7238 ConstantInt *ExitConst = ExitCount->getValue(); 7239 7240 // Guard against huge trip counts. 7241 if (ExitConst->getValue().getActiveBits() > 32) 7242 return 0; 7243 7244 // In case of integer overflow, this returns 0, which is correct. 7245 return ((unsigned)ExitConst->getZExtValue()) + 1; 7246 } 7247 7248 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7249 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7250 return getConstantTripCount(ExitCount); 7251 } 7252 7253 unsigned 7254 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7255 const BasicBlock *ExitingBlock) { 7256 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7257 assert(L->isLoopExiting(ExitingBlock) && 7258 "Exiting block must actually branch out of the loop!"); 7259 const SCEVConstant *ExitCount = 7260 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7261 return getConstantTripCount(ExitCount); 7262 } 7263 7264 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7265 const auto *MaxExitCount = 7266 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7267 return getConstantTripCount(MaxExitCount); 7268 } 7269 7270 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7271 SmallVector<BasicBlock *, 8> ExitingBlocks; 7272 L->getExitingBlocks(ExitingBlocks); 7273 7274 Optional<unsigned> Res = None; 7275 for (auto *ExitingBB : ExitingBlocks) { 7276 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7277 if (!Res) 7278 Res = Multiple; 7279 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7280 } 7281 return Res.getValueOr(1); 7282 } 7283 7284 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7285 const SCEV *ExitCount) { 7286 if (ExitCount == getCouldNotCompute()) 7287 return 1; 7288 7289 // Get the trip count 7290 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7291 7292 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7293 if (!TC) 7294 // Attempt to factor more general cases. Returns the greatest power of 7295 // two divisor. If overflow happens, the trip count expression is still 7296 // divisible by the greatest power of 2 divisor returned. 7297 return 1U << std::min((uint32_t)31, 7298 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7299 7300 ConstantInt *Result = TC->getValue(); 7301 7302 // Guard against huge trip counts (this requires checking 7303 // for zero to handle the case where the trip count == -1 and the 7304 // addition wraps). 7305 if (!Result || Result->getValue().getActiveBits() > 32 || 7306 Result->getValue().getActiveBits() == 0) 7307 return 1; 7308 7309 return (unsigned)Result->getZExtValue(); 7310 } 7311 7312 /// Returns the largest constant divisor of the trip count of this loop as a 7313 /// normal unsigned value, if possible. This means that the actual trip count is 7314 /// always a multiple of the returned value (don't forget the trip count could 7315 /// very well be zero as well!). 7316 /// 7317 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7318 /// multiple of a constant (which is also the case if the trip count is simply 7319 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7320 /// if the trip count is very large (>= 2^32). 7321 /// 7322 /// As explained in the comments for getSmallConstantTripCount, this assumes 7323 /// that control exits the loop via ExitingBlock. 7324 unsigned 7325 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7326 const BasicBlock *ExitingBlock) { 7327 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7328 assert(L->isLoopExiting(ExitingBlock) && 7329 "Exiting block must actually branch out of the loop!"); 7330 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7331 return getSmallConstantTripMultiple(L, ExitCount); 7332 } 7333 7334 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7335 const BasicBlock *ExitingBlock, 7336 ExitCountKind Kind) { 7337 switch (Kind) { 7338 case Exact: 7339 case SymbolicMaximum: 7340 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7341 case ConstantMaximum: 7342 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7343 }; 7344 llvm_unreachable("Invalid ExitCountKind!"); 7345 } 7346 7347 const SCEV * 7348 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7349 SCEVUnionPredicate &Preds) { 7350 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7351 } 7352 7353 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7354 ExitCountKind Kind) { 7355 switch (Kind) { 7356 case Exact: 7357 return getBackedgeTakenInfo(L).getExact(L, this); 7358 case ConstantMaximum: 7359 return getBackedgeTakenInfo(L).getConstantMax(this); 7360 case SymbolicMaximum: 7361 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7362 }; 7363 llvm_unreachable("Invalid ExitCountKind!"); 7364 } 7365 7366 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7367 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7368 } 7369 7370 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7371 static void PushLoopPHIs(const Loop *L, 7372 SmallVectorImpl<Instruction *> &Worklist, 7373 SmallPtrSetImpl<Instruction *> &Visited) { 7374 BasicBlock *Header = L->getHeader(); 7375 7376 // Push all Loop-header PHIs onto the Worklist stack. 7377 for (PHINode &PN : Header->phis()) 7378 if (Visited.insert(&PN).second) 7379 Worklist.push_back(&PN); 7380 } 7381 7382 const ScalarEvolution::BackedgeTakenInfo & 7383 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7384 auto &BTI = getBackedgeTakenInfo(L); 7385 if (BTI.hasFullInfo()) 7386 return BTI; 7387 7388 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7389 7390 if (!Pair.second) 7391 return Pair.first->second; 7392 7393 BackedgeTakenInfo Result = 7394 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7395 7396 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7397 } 7398 7399 ScalarEvolution::BackedgeTakenInfo & 7400 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7401 // Initially insert an invalid entry for this loop. If the insertion 7402 // succeeds, proceed to actually compute a backedge-taken count and 7403 // update the value. The temporary CouldNotCompute value tells SCEV 7404 // code elsewhere that it shouldn't attempt to request a new 7405 // backedge-taken count, which could result in infinite recursion. 7406 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7407 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7408 if (!Pair.second) 7409 return Pair.first->second; 7410 7411 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7412 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7413 // must be cleared in this scope. 7414 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7415 7416 // In product build, there are no usage of statistic. 7417 (void)NumTripCountsComputed; 7418 (void)NumTripCountsNotComputed; 7419 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7420 const SCEV *BEExact = Result.getExact(L, this); 7421 if (BEExact != getCouldNotCompute()) { 7422 assert(isLoopInvariant(BEExact, L) && 7423 isLoopInvariant(Result.getConstantMax(this), L) && 7424 "Computed backedge-taken count isn't loop invariant for loop!"); 7425 ++NumTripCountsComputed; 7426 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7427 isa<PHINode>(L->getHeader()->begin())) { 7428 // Only count loops that have phi nodes as not being computable. 7429 ++NumTripCountsNotComputed; 7430 } 7431 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7432 7433 // Now that we know more about the trip count for this loop, forget any 7434 // existing SCEV values for PHI nodes in this loop since they are only 7435 // conservative estimates made without the benefit of trip count 7436 // information. This is similar to the code in forgetLoop, except that 7437 // it handles SCEVUnknown PHI nodes specially. 7438 if (Result.hasAnyInfo()) { 7439 SmallVector<Instruction *, 16> Worklist; 7440 SmallPtrSet<Instruction *, 8> Discovered; 7441 PushLoopPHIs(L, Worklist, Discovered); 7442 while (!Worklist.empty()) { 7443 Instruction *I = Worklist.pop_back_val(); 7444 7445 ValueExprMapType::iterator It = 7446 ValueExprMap.find_as(static_cast<Value *>(I)); 7447 if (It != ValueExprMap.end()) { 7448 const SCEV *Old = It->second; 7449 7450 // SCEVUnknown for a PHI either means that it has an unrecognized 7451 // structure, or it's a PHI that's in the progress of being computed 7452 // by createNodeForPHI. In the former case, additional loop trip 7453 // count information isn't going to change anything. In the later 7454 // case, createNodeForPHI will perform the necessary updates on its 7455 // own when it gets to that point. 7456 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7457 eraseValueFromMap(It->first); 7458 forgetMemoizedResults(Old); 7459 } 7460 if (PHINode *PN = dyn_cast<PHINode>(I)) 7461 ConstantEvolutionLoopExitValue.erase(PN); 7462 } 7463 7464 // Since we don't need to invalidate anything for correctness and we're 7465 // only invalidating to make SCEV's results more precise, we get to stop 7466 // early to avoid invalidating too much. This is especially important in 7467 // cases like: 7468 // 7469 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7470 // loop0: 7471 // %pn0 = phi 7472 // ... 7473 // loop1: 7474 // %pn1 = phi 7475 // ... 7476 // 7477 // where both loop0 and loop1's backedge taken count uses the SCEV 7478 // expression for %v. If we don't have the early stop below then in cases 7479 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7480 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7481 // count for loop1, effectively nullifying SCEV's trip count cache. 7482 for (auto *U : I->users()) 7483 if (auto *I = dyn_cast<Instruction>(U)) { 7484 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7485 if (LoopForUser && L->contains(LoopForUser) && 7486 Discovered.insert(I).second) 7487 Worklist.push_back(I); 7488 } 7489 } 7490 } 7491 7492 // Re-lookup the insert position, since the call to 7493 // computeBackedgeTakenCount above could result in a 7494 // recusive call to getBackedgeTakenInfo (on a different 7495 // loop), which would invalidate the iterator computed 7496 // earlier. 7497 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7498 } 7499 7500 void ScalarEvolution::forgetAllLoops() { 7501 // This method is intended to forget all info about loops. It should 7502 // invalidate caches as if the following happened: 7503 // - The trip counts of all loops have changed arbitrarily 7504 // - Every llvm::Value has been updated in place to produce a different 7505 // result. 7506 BackedgeTakenCounts.clear(); 7507 PredicatedBackedgeTakenCounts.clear(); 7508 LoopPropertiesCache.clear(); 7509 ConstantEvolutionLoopExitValue.clear(); 7510 ValueExprMap.clear(); 7511 ValuesAtScopes.clear(); 7512 LoopDispositions.clear(); 7513 BlockDispositions.clear(); 7514 UnsignedRanges.clear(); 7515 SignedRanges.clear(); 7516 ExprValueMap.clear(); 7517 HasRecMap.clear(); 7518 MinTrailingZerosCache.clear(); 7519 PredicatedSCEVRewrites.clear(); 7520 } 7521 7522 void ScalarEvolution::forgetLoop(const Loop *L) { 7523 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7524 SmallVector<Instruction *, 32> Worklist; 7525 SmallPtrSet<Instruction *, 16> Visited; 7526 7527 // Iterate over all the loops and sub-loops to drop SCEV information. 7528 while (!LoopWorklist.empty()) { 7529 auto *CurrL = LoopWorklist.pop_back_val(); 7530 7531 // Drop any stored trip count value. 7532 BackedgeTakenCounts.erase(CurrL); 7533 PredicatedBackedgeTakenCounts.erase(CurrL); 7534 7535 // Drop information about predicated SCEV rewrites for this loop. 7536 for (auto I = PredicatedSCEVRewrites.begin(); 7537 I != PredicatedSCEVRewrites.end();) { 7538 std::pair<const SCEV *, const Loop *> Entry = I->first; 7539 if (Entry.second == CurrL) 7540 PredicatedSCEVRewrites.erase(I++); 7541 else 7542 ++I; 7543 } 7544 7545 auto LoopUsersItr = LoopUsers.find(CurrL); 7546 if (LoopUsersItr != LoopUsers.end()) { 7547 for (auto *S : LoopUsersItr->second) 7548 forgetMemoizedResults(S); 7549 LoopUsers.erase(LoopUsersItr); 7550 } 7551 7552 // Drop information about expressions based on loop-header PHIs. 7553 PushLoopPHIs(CurrL, Worklist, Visited); 7554 7555 while (!Worklist.empty()) { 7556 Instruction *I = Worklist.pop_back_val(); 7557 7558 ValueExprMapType::iterator It = 7559 ValueExprMap.find_as(static_cast<Value *>(I)); 7560 if (It != ValueExprMap.end()) { 7561 eraseValueFromMap(It->first); 7562 forgetMemoizedResults(It->second); 7563 if (PHINode *PN = dyn_cast<PHINode>(I)) 7564 ConstantEvolutionLoopExitValue.erase(PN); 7565 } 7566 7567 PushDefUseChildren(I, Worklist, Visited); 7568 } 7569 7570 LoopPropertiesCache.erase(CurrL); 7571 // Forget all contained loops too, to avoid dangling entries in the 7572 // ValuesAtScopes map. 7573 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7574 } 7575 } 7576 7577 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7578 while (Loop *Parent = L->getParentLoop()) 7579 L = Parent; 7580 forgetLoop(L); 7581 } 7582 7583 void ScalarEvolution::forgetValue(Value *V) { 7584 Instruction *I = dyn_cast<Instruction>(V); 7585 if (!I) return; 7586 7587 // Drop information about expressions based on loop-header PHIs. 7588 SmallVector<Instruction *, 16> Worklist; 7589 SmallPtrSet<Instruction *, 8> Visited; 7590 Worklist.push_back(I); 7591 Visited.insert(I); 7592 7593 while (!Worklist.empty()) { 7594 I = Worklist.pop_back_val(); 7595 ValueExprMapType::iterator It = 7596 ValueExprMap.find_as(static_cast<Value *>(I)); 7597 if (It != ValueExprMap.end()) { 7598 eraseValueFromMap(It->first); 7599 forgetMemoizedResults(It->second); 7600 if (PHINode *PN = dyn_cast<PHINode>(I)) 7601 ConstantEvolutionLoopExitValue.erase(PN); 7602 } 7603 7604 PushDefUseChildren(I, Worklist, Visited); 7605 } 7606 } 7607 7608 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7609 LoopDispositions.clear(); 7610 } 7611 7612 /// Get the exact loop backedge taken count considering all loop exits. A 7613 /// computable result can only be returned for loops with all exiting blocks 7614 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7615 /// is never skipped. This is a valid assumption as long as the loop exits via 7616 /// that test. For precise results, it is the caller's responsibility to specify 7617 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7618 const SCEV * 7619 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7620 SCEVUnionPredicate *Preds) const { 7621 // If any exits were not computable, the loop is not computable. 7622 if (!isComplete() || ExitNotTaken.empty()) 7623 return SE->getCouldNotCompute(); 7624 7625 const BasicBlock *Latch = L->getLoopLatch(); 7626 // All exiting blocks we have collected must dominate the only backedge. 7627 if (!Latch) 7628 return SE->getCouldNotCompute(); 7629 7630 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7631 // count is simply a minimum out of all these calculated exit counts. 7632 SmallVector<const SCEV *, 2> Ops; 7633 for (auto &ENT : ExitNotTaken) { 7634 const SCEV *BECount = ENT.ExactNotTaken; 7635 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7636 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7637 "We should only have known counts for exiting blocks that dominate " 7638 "latch!"); 7639 7640 Ops.push_back(BECount); 7641 7642 if (Preds && !ENT.hasAlwaysTruePredicate()) 7643 Preds->add(ENT.Predicate.get()); 7644 7645 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7646 "Predicate should be always true!"); 7647 } 7648 7649 return SE->getUMinFromMismatchedTypes(Ops); 7650 } 7651 7652 /// Get the exact not taken count for this loop exit. 7653 const SCEV * 7654 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7655 ScalarEvolution *SE) const { 7656 for (auto &ENT : ExitNotTaken) 7657 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7658 return ENT.ExactNotTaken; 7659 7660 return SE->getCouldNotCompute(); 7661 } 7662 7663 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7664 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7665 for (auto &ENT : ExitNotTaken) 7666 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7667 return ENT.MaxNotTaken; 7668 7669 return SE->getCouldNotCompute(); 7670 } 7671 7672 /// getConstantMax - Get the constant max backedge taken count for the loop. 7673 const SCEV * 7674 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7675 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7676 return !ENT.hasAlwaysTruePredicate(); 7677 }; 7678 7679 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 7680 return SE->getCouldNotCompute(); 7681 7682 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7683 isa<SCEVConstant>(getConstantMax())) && 7684 "No point in having a non-constant max backedge taken count!"); 7685 return getConstantMax(); 7686 } 7687 7688 const SCEV * 7689 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7690 ScalarEvolution *SE) { 7691 if (!SymbolicMax) 7692 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7693 return SymbolicMax; 7694 } 7695 7696 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7697 ScalarEvolution *SE) const { 7698 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7699 return !ENT.hasAlwaysTruePredicate(); 7700 }; 7701 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7702 } 7703 7704 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7705 return Operands.contains(S); 7706 } 7707 7708 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7709 : ExitLimit(E, E, false, None) { 7710 } 7711 7712 ScalarEvolution::ExitLimit::ExitLimit( 7713 const SCEV *E, const SCEV *M, bool MaxOrZero, 7714 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7715 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7716 // If we prove the max count is zero, so is the symbolic bound. This happens 7717 // in practice due to differences in a) how context sensitive we've chosen 7718 // to be and b) how we reason about bounds impied by UB. 7719 if (MaxNotTaken->isZero()) 7720 ExactNotTaken = MaxNotTaken; 7721 7722 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7723 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7724 "Exact is not allowed to be less precise than Max"); 7725 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7726 isa<SCEVConstant>(MaxNotTaken)) && 7727 "No point in having a non-constant max backedge taken count!"); 7728 for (auto *PredSet : PredSetList) 7729 for (auto *P : *PredSet) 7730 addPredicate(P); 7731 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7732 "Backedge count should be int"); 7733 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7734 "Max backedge count should be int"); 7735 } 7736 7737 ScalarEvolution::ExitLimit::ExitLimit( 7738 const SCEV *E, const SCEV *M, bool MaxOrZero, 7739 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7740 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7741 } 7742 7743 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7744 bool MaxOrZero) 7745 : ExitLimit(E, M, MaxOrZero, None) { 7746 } 7747 7748 class SCEVRecordOperands { 7749 SmallPtrSetImpl<const SCEV *> &Operands; 7750 7751 public: 7752 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7753 : Operands(Operands) {} 7754 bool follow(const SCEV *S) { 7755 Operands.insert(S); 7756 return true; 7757 } 7758 bool isDone() { return false; } 7759 }; 7760 7761 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7762 /// computable exit into a persistent ExitNotTakenInfo array. 7763 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7764 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7765 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7766 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7767 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7768 7769 ExitNotTaken.reserve(ExitCounts.size()); 7770 std::transform( 7771 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7772 [&](const EdgeExitInfo &EEI) { 7773 BasicBlock *ExitBB = EEI.first; 7774 const ExitLimit &EL = EEI.second; 7775 if (EL.Predicates.empty()) 7776 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7777 nullptr); 7778 7779 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7780 for (auto *Pred : EL.Predicates) 7781 Predicate->add(Pred); 7782 7783 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7784 std::move(Predicate)); 7785 }); 7786 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7787 isa<SCEVConstant>(ConstantMax)) && 7788 "No point in having a non-constant max backedge taken count!"); 7789 7790 SCEVRecordOperands RecordOperands(Operands); 7791 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7792 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7793 ST.visitAll(ConstantMax); 7794 for (auto &ENT : ExitNotTaken) 7795 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7796 ST.visitAll(ENT.ExactNotTaken); 7797 } 7798 7799 /// Compute the number of times the backedge of the specified loop will execute. 7800 ScalarEvolution::BackedgeTakenInfo 7801 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7802 bool AllowPredicates) { 7803 SmallVector<BasicBlock *, 8> ExitingBlocks; 7804 L->getExitingBlocks(ExitingBlocks); 7805 7806 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7807 7808 SmallVector<EdgeExitInfo, 4> ExitCounts; 7809 bool CouldComputeBECount = true; 7810 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7811 const SCEV *MustExitMaxBECount = nullptr; 7812 const SCEV *MayExitMaxBECount = nullptr; 7813 bool MustExitMaxOrZero = false; 7814 7815 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7816 // and compute maxBECount. 7817 // Do a union of all the predicates here. 7818 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7819 BasicBlock *ExitBB = ExitingBlocks[i]; 7820 7821 // We canonicalize untaken exits to br (constant), ignore them so that 7822 // proving an exit untaken doesn't negatively impact our ability to reason 7823 // about the loop as whole. 7824 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7825 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7826 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7827 if (ExitIfTrue == CI->isZero()) 7828 continue; 7829 } 7830 7831 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7832 7833 assert((AllowPredicates || EL.Predicates.empty()) && 7834 "Predicated exit limit when predicates are not allowed!"); 7835 7836 // 1. For each exit that can be computed, add an entry to ExitCounts. 7837 // CouldComputeBECount is true only if all exits can be computed. 7838 if (EL.ExactNotTaken == getCouldNotCompute()) 7839 // We couldn't compute an exact value for this exit, so 7840 // we won't be able to compute an exact value for the loop. 7841 CouldComputeBECount = false; 7842 else 7843 ExitCounts.emplace_back(ExitBB, EL); 7844 7845 // 2. Derive the loop's MaxBECount from each exit's max number of 7846 // non-exiting iterations. Partition the loop exits into two kinds: 7847 // LoopMustExits and LoopMayExits. 7848 // 7849 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7850 // is a LoopMayExit. If any computable LoopMustExit is found, then 7851 // MaxBECount is the minimum EL.MaxNotTaken of computable 7852 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7853 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7854 // computable EL.MaxNotTaken. 7855 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7856 DT.dominates(ExitBB, Latch)) { 7857 if (!MustExitMaxBECount) { 7858 MustExitMaxBECount = EL.MaxNotTaken; 7859 MustExitMaxOrZero = EL.MaxOrZero; 7860 } else { 7861 MustExitMaxBECount = 7862 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7863 } 7864 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7865 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7866 MayExitMaxBECount = EL.MaxNotTaken; 7867 else { 7868 MayExitMaxBECount = 7869 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7870 } 7871 } 7872 } 7873 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7874 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7875 // The loop backedge will be taken the maximum or zero times if there's 7876 // a single exit that must be taken the maximum or zero times. 7877 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7878 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7879 MaxBECount, MaxOrZero); 7880 } 7881 7882 ScalarEvolution::ExitLimit 7883 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7884 bool AllowPredicates) { 7885 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7886 // If our exiting block does not dominate the latch, then its connection with 7887 // loop's exit limit may be far from trivial. 7888 const BasicBlock *Latch = L->getLoopLatch(); 7889 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7890 return getCouldNotCompute(); 7891 7892 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7893 Instruction *Term = ExitingBlock->getTerminator(); 7894 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7895 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7896 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7897 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7898 "It should have one successor in loop and one exit block!"); 7899 // Proceed to the next level to examine the exit condition expression. 7900 return computeExitLimitFromCond( 7901 L, BI->getCondition(), ExitIfTrue, 7902 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7903 } 7904 7905 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7906 // For switch, make sure that there is a single exit from the loop. 7907 BasicBlock *Exit = nullptr; 7908 for (auto *SBB : successors(ExitingBlock)) 7909 if (!L->contains(SBB)) { 7910 if (Exit) // Multiple exit successors. 7911 return getCouldNotCompute(); 7912 Exit = SBB; 7913 } 7914 assert(Exit && "Exiting block must have at least one exit"); 7915 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7916 /*ControlsExit=*/IsOnlyExit); 7917 } 7918 7919 return getCouldNotCompute(); 7920 } 7921 7922 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7923 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7924 bool ControlsExit, bool AllowPredicates) { 7925 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7926 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7927 ControlsExit, AllowPredicates); 7928 } 7929 7930 Optional<ScalarEvolution::ExitLimit> 7931 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7932 bool ExitIfTrue, bool ControlsExit, 7933 bool AllowPredicates) { 7934 (void)this->L; 7935 (void)this->ExitIfTrue; 7936 (void)this->AllowPredicates; 7937 7938 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7939 this->AllowPredicates == AllowPredicates && 7940 "Variance in assumed invariant key components!"); 7941 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7942 if (Itr == TripCountMap.end()) 7943 return None; 7944 return Itr->second; 7945 } 7946 7947 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7948 bool ExitIfTrue, 7949 bool ControlsExit, 7950 bool AllowPredicates, 7951 const ExitLimit &EL) { 7952 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7953 this->AllowPredicates == AllowPredicates && 7954 "Variance in assumed invariant key components!"); 7955 7956 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7957 assert(InsertResult.second && "Expected successful insertion!"); 7958 (void)InsertResult; 7959 (void)ExitIfTrue; 7960 } 7961 7962 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7963 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7964 bool ControlsExit, bool AllowPredicates) { 7965 7966 if (auto MaybeEL = 7967 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7968 return *MaybeEL; 7969 7970 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7971 ControlsExit, AllowPredicates); 7972 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7973 return EL; 7974 } 7975 7976 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7977 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7978 bool ControlsExit, bool AllowPredicates) { 7979 // Handle BinOp conditions (And, Or). 7980 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7981 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7982 return *LimitFromBinOp; 7983 7984 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7985 // Proceed to the next level to examine the icmp. 7986 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7987 ExitLimit EL = 7988 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7989 if (EL.hasFullInfo() || !AllowPredicates) 7990 return EL; 7991 7992 // Try again, but use SCEV predicates this time. 7993 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7994 /*AllowPredicates=*/true); 7995 } 7996 7997 // Check for a constant condition. These are normally stripped out by 7998 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7999 // preserve the CFG and is temporarily leaving constant conditions 8000 // in place. 8001 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8002 if (ExitIfTrue == !CI->getZExtValue()) 8003 // The backedge is always taken. 8004 return getCouldNotCompute(); 8005 else 8006 // The backedge is never taken. 8007 return getZero(CI->getType()); 8008 } 8009 8010 // If it's not an integer or pointer comparison then compute it the hard way. 8011 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8012 } 8013 8014 Optional<ScalarEvolution::ExitLimit> 8015 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8016 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8017 bool ControlsExit, bool AllowPredicates) { 8018 // Check if the controlling expression for this loop is an And or Or. 8019 Value *Op0, *Op1; 8020 bool IsAnd = false; 8021 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8022 IsAnd = true; 8023 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8024 IsAnd = false; 8025 else 8026 return None; 8027 8028 // EitherMayExit is true in these two cases: 8029 // br (and Op0 Op1), loop, exit 8030 // br (or Op0 Op1), exit, loop 8031 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8032 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8033 ControlsExit && !EitherMayExit, 8034 AllowPredicates); 8035 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8036 ControlsExit && !EitherMayExit, 8037 AllowPredicates); 8038 8039 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8040 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8041 if (isa<ConstantInt>(Op1)) 8042 return Op1 == NeutralElement ? EL0 : EL1; 8043 if (isa<ConstantInt>(Op0)) 8044 return Op0 == NeutralElement ? EL1 : EL0; 8045 8046 const SCEV *BECount = getCouldNotCompute(); 8047 const SCEV *MaxBECount = getCouldNotCompute(); 8048 if (EitherMayExit) { 8049 // Both conditions must be same for the loop to continue executing. 8050 // Choose the less conservative count. 8051 // If ExitCond is a short-circuit form (select), using 8052 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 8053 // To see the detailed examples, please see 8054 // test/Analysis/ScalarEvolution/exit-count-select.ll 8055 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 8056 if (!PoisonSafe) 8057 // Even if ExitCond is select, we can safely derive BECount using both 8058 // EL0 and EL1 in these cases: 8059 // (1) EL0.ExactNotTaken is non-zero 8060 // (2) EL1.ExactNotTaken is non-poison 8061 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 8062 // it cannot be umin(0, ..)) 8063 // The PoisonSafe assignment below is simplified and the assertion after 8064 // BECount calculation fully guarantees the condition (3). 8065 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 8066 isa<SCEVConstant>(EL1.ExactNotTaken); 8067 if (EL0.ExactNotTaken != getCouldNotCompute() && 8068 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 8069 BECount = 8070 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 8071 8072 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8073 // it should have been simplified to zero (see the condition (3) above) 8074 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8075 BECount->isZero()); 8076 } 8077 if (EL0.MaxNotTaken == getCouldNotCompute()) 8078 MaxBECount = EL1.MaxNotTaken; 8079 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8080 MaxBECount = EL0.MaxNotTaken; 8081 else 8082 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8083 } else { 8084 // Both conditions must be same at the same time for the loop to exit. 8085 // For now, be conservative. 8086 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8087 BECount = EL0.ExactNotTaken; 8088 } 8089 8090 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8091 // to be more aggressive when computing BECount than when computing 8092 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8093 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8094 // to not. 8095 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8096 !isa<SCEVCouldNotCompute>(BECount)) 8097 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8098 8099 return ExitLimit(BECount, MaxBECount, false, 8100 { &EL0.Predicates, &EL1.Predicates }); 8101 } 8102 8103 ScalarEvolution::ExitLimit 8104 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8105 ICmpInst *ExitCond, 8106 bool ExitIfTrue, 8107 bool ControlsExit, 8108 bool AllowPredicates) { 8109 // If the condition was exit on true, convert the condition to exit on false 8110 ICmpInst::Predicate Pred; 8111 if (!ExitIfTrue) 8112 Pred = ExitCond->getPredicate(); 8113 else 8114 Pred = ExitCond->getInversePredicate(); 8115 const ICmpInst::Predicate OriginalPred = Pred; 8116 8117 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8118 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8119 8120 // Try to evaluate any dependencies out of the loop. 8121 LHS = getSCEVAtScope(LHS, L); 8122 RHS = getSCEVAtScope(RHS, L); 8123 8124 // At this point, we would like to compute how many iterations of the 8125 // loop the predicate will return true for these inputs. 8126 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8127 // If there is a loop-invariant, force it into the RHS. 8128 std::swap(LHS, RHS); 8129 Pred = ICmpInst::getSwappedPredicate(Pred); 8130 } 8131 8132 // Simplify the operands before analyzing them. 8133 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8134 8135 // If we have a comparison of a chrec against a constant, try to use value 8136 // ranges to answer this query. 8137 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8138 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8139 if (AddRec->getLoop() == L) { 8140 // Form the constant range. 8141 ConstantRange CompRange = 8142 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8143 8144 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8145 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8146 } 8147 8148 switch (Pred) { 8149 case ICmpInst::ICMP_NE: { // while (X != Y) 8150 // Convert to: while (X-Y != 0) 8151 if (LHS->getType()->isPointerTy()) { 8152 LHS = getLosslessPtrToIntExpr(LHS); 8153 if (isa<SCEVCouldNotCompute>(LHS)) 8154 return LHS; 8155 } 8156 if (RHS->getType()->isPointerTy()) { 8157 RHS = getLosslessPtrToIntExpr(RHS); 8158 if (isa<SCEVCouldNotCompute>(RHS)) 8159 return RHS; 8160 } 8161 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8162 AllowPredicates); 8163 if (EL.hasAnyInfo()) return EL; 8164 break; 8165 } 8166 case ICmpInst::ICMP_EQ: { // while (X == Y) 8167 // Convert to: while (X-Y == 0) 8168 if (LHS->getType()->isPointerTy()) { 8169 LHS = getLosslessPtrToIntExpr(LHS); 8170 if (isa<SCEVCouldNotCompute>(LHS)) 8171 return LHS; 8172 } 8173 if (RHS->getType()->isPointerTy()) { 8174 RHS = getLosslessPtrToIntExpr(RHS); 8175 if (isa<SCEVCouldNotCompute>(RHS)) 8176 return RHS; 8177 } 8178 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8179 if (EL.hasAnyInfo()) return EL; 8180 break; 8181 } 8182 case ICmpInst::ICMP_SLT: 8183 case ICmpInst::ICMP_ULT: { // while (X < Y) 8184 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8185 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8186 AllowPredicates); 8187 if (EL.hasAnyInfo()) return EL; 8188 break; 8189 } 8190 case ICmpInst::ICMP_SGT: 8191 case ICmpInst::ICMP_UGT: { // while (X > Y) 8192 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8193 ExitLimit EL = 8194 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8195 AllowPredicates); 8196 if (EL.hasAnyInfo()) return EL; 8197 break; 8198 } 8199 default: 8200 break; 8201 } 8202 8203 auto *ExhaustiveCount = 8204 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8205 8206 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8207 return ExhaustiveCount; 8208 8209 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8210 ExitCond->getOperand(1), L, OriginalPred); 8211 } 8212 8213 ScalarEvolution::ExitLimit 8214 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8215 SwitchInst *Switch, 8216 BasicBlock *ExitingBlock, 8217 bool ControlsExit) { 8218 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8219 8220 // Give up if the exit is the default dest of a switch. 8221 if (Switch->getDefaultDest() == ExitingBlock) 8222 return getCouldNotCompute(); 8223 8224 assert(L->contains(Switch->getDefaultDest()) && 8225 "Default case must not exit the loop!"); 8226 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8227 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8228 8229 // while (X != Y) --> while (X-Y != 0) 8230 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8231 if (EL.hasAnyInfo()) 8232 return EL; 8233 8234 return getCouldNotCompute(); 8235 } 8236 8237 static ConstantInt * 8238 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8239 ScalarEvolution &SE) { 8240 const SCEV *InVal = SE.getConstant(C); 8241 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8242 assert(isa<SCEVConstant>(Val) && 8243 "Evaluation of SCEV at constant didn't fold correctly?"); 8244 return cast<SCEVConstant>(Val)->getValue(); 8245 } 8246 8247 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8248 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8249 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8250 if (!RHS) 8251 return getCouldNotCompute(); 8252 8253 const BasicBlock *Latch = L->getLoopLatch(); 8254 if (!Latch) 8255 return getCouldNotCompute(); 8256 8257 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8258 if (!Predecessor) 8259 return getCouldNotCompute(); 8260 8261 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8262 // Return LHS in OutLHS and shift_opt in OutOpCode. 8263 auto MatchPositiveShift = 8264 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8265 8266 using namespace PatternMatch; 8267 8268 ConstantInt *ShiftAmt; 8269 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8270 OutOpCode = Instruction::LShr; 8271 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8272 OutOpCode = Instruction::AShr; 8273 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8274 OutOpCode = Instruction::Shl; 8275 else 8276 return false; 8277 8278 return ShiftAmt->getValue().isStrictlyPositive(); 8279 }; 8280 8281 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8282 // 8283 // loop: 8284 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8285 // %iv.shifted = lshr i32 %iv, <positive constant> 8286 // 8287 // Return true on a successful match. Return the corresponding PHI node (%iv 8288 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8289 auto MatchShiftRecurrence = 8290 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8291 Optional<Instruction::BinaryOps> PostShiftOpCode; 8292 8293 { 8294 Instruction::BinaryOps OpC; 8295 Value *V; 8296 8297 // If we encounter a shift instruction, "peel off" the shift operation, 8298 // and remember that we did so. Later when we inspect %iv's backedge 8299 // value, we will make sure that the backedge value uses the same 8300 // operation. 8301 // 8302 // Note: the peeled shift operation does not have to be the same 8303 // instruction as the one feeding into the PHI's backedge value. We only 8304 // really care about it being the same *kind* of shift instruction -- 8305 // that's all that is required for our later inferences to hold. 8306 if (MatchPositiveShift(LHS, V, OpC)) { 8307 PostShiftOpCode = OpC; 8308 LHS = V; 8309 } 8310 } 8311 8312 PNOut = dyn_cast<PHINode>(LHS); 8313 if (!PNOut || PNOut->getParent() != L->getHeader()) 8314 return false; 8315 8316 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8317 Value *OpLHS; 8318 8319 return 8320 // The backedge value for the PHI node must be a shift by a positive 8321 // amount 8322 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8323 8324 // of the PHI node itself 8325 OpLHS == PNOut && 8326 8327 // and the kind of shift should be match the kind of shift we peeled 8328 // off, if any. 8329 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8330 }; 8331 8332 PHINode *PN; 8333 Instruction::BinaryOps OpCode; 8334 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8335 return getCouldNotCompute(); 8336 8337 const DataLayout &DL = getDataLayout(); 8338 8339 // The key rationale for this optimization is that for some kinds of shift 8340 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8341 // within a finite number of iterations. If the condition guarding the 8342 // backedge (in the sense that the backedge is taken if the condition is true) 8343 // is false for the value the shift recurrence stabilizes to, then we know 8344 // that the backedge is taken only a finite number of times. 8345 8346 ConstantInt *StableValue = nullptr; 8347 switch (OpCode) { 8348 default: 8349 llvm_unreachable("Impossible case!"); 8350 8351 case Instruction::AShr: { 8352 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8353 // bitwidth(K) iterations. 8354 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8355 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8356 Predecessor->getTerminator(), &DT); 8357 auto *Ty = cast<IntegerType>(RHS->getType()); 8358 if (Known.isNonNegative()) 8359 StableValue = ConstantInt::get(Ty, 0); 8360 else if (Known.isNegative()) 8361 StableValue = ConstantInt::get(Ty, -1, true); 8362 else 8363 return getCouldNotCompute(); 8364 8365 break; 8366 } 8367 case Instruction::LShr: 8368 case Instruction::Shl: 8369 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8370 // stabilize to 0 in at most bitwidth(K) iterations. 8371 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8372 break; 8373 } 8374 8375 auto *Result = 8376 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8377 assert(Result->getType()->isIntegerTy(1) && 8378 "Otherwise cannot be an operand to a branch instruction"); 8379 8380 if (Result->isZeroValue()) { 8381 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8382 const SCEV *UpperBound = 8383 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8384 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8385 } 8386 8387 return getCouldNotCompute(); 8388 } 8389 8390 /// Return true if we can constant fold an instruction of the specified type, 8391 /// assuming that all operands were constants. 8392 static bool CanConstantFold(const Instruction *I) { 8393 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8394 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8395 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8396 return true; 8397 8398 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8399 if (const Function *F = CI->getCalledFunction()) 8400 return canConstantFoldCallTo(CI, F); 8401 return false; 8402 } 8403 8404 /// Determine whether this instruction can constant evolve within this loop 8405 /// assuming its operands can all constant evolve. 8406 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8407 // An instruction outside of the loop can't be derived from a loop PHI. 8408 if (!L->contains(I)) return false; 8409 8410 if (isa<PHINode>(I)) { 8411 // We don't currently keep track of the control flow needed to evaluate 8412 // PHIs, so we cannot handle PHIs inside of loops. 8413 return L->getHeader() == I->getParent(); 8414 } 8415 8416 // If we won't be able to constant fold this expression even if the operands 8417 // are constants, bail early. 8418 return CanConstantFold(I); 8419 } 8420 8421 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8422 /// recursing through each instruction operand until reaching a loop header phi. 8423 static PHINode * 8424 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8425 DenseMap<Instruction *, PHINode *> &PHIMap, 8426 unsigned Depth) { 8427 if (Depth > MaxConstantEvolvingDepth) 8428 return nullptr; 8429 8430 // Otherwise, we can evaluate this instruction if all of its operands are 8431 // constant or derived from a PHI node themselves. 8432 PHINode *PHI = nullptr; 8433 for (Value *Op : UseInst->operands()) { 8434 if (isa<Constant>(Op)) continue; 8435 8436 Instruction *OpInst = dyn_cast<Instruction>(Op); 8437 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8438 8439 PHINode *P = dyn_cast<PHINode>(OpInst); 8440 if (!P) 8441 // If this operand is already visited, reuse the prior result. 8442 // We may have P != PHI if this is the deepest point at which the 8443 // inconsistent paths meet. 8444 P = PHIMap.lookup(OpInst); 8445 if (!P) { 8446 // Recurse and memoize the results, whether a phi is found or not. 8447 // This recursive call invalidates pointers into PHIMap. 8448 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8449 PHIMap[OpInst] = P; 8450 } 8451 if (!P) 8452 return nullptr; // Not evolving from PHI 8453 if (PHI && PHI != P) 8454 return nullptr; // Evolving from multiple different PHIs. 8455 PHI = P; 8456 } 8457 // This is a expression evolving from a constant PHI! 8458 return PHI; 8459 } 8460 8461 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8462 /// in the loop that V is derived from. We allow arbitrary operations along the 8463 /// way, but the operands of an operation must either be constants or a value 8464 /// derived from a constant PHI. If this expression does not fit with these 8465 /// constraints, return null. 8466 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8467 Instruction *I = dyn_cast<Instruction>(V); 8468 if (!I || !canConstantEvolve(I, L)) return nullptr; 8469 8470 if (PHINode *PN = dyn_cast<PHINode>(I)) 8471 return PN; 8472 8473 // Record non-constant instructions contained by the loop. 8474 DenseMap<Instruction *, PHINode *> PHIMap; 8475 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8476 } 8477 8478 /// EvaluateExpression - Given an expression that passes the 8479 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8480 /// in the loop has the value PHIVal. If we can't fold this expression for some 8481 /// reason, return null. 8482 static Constant *EvaluateExpression(Value *V, const Loop *L, 8483 DenseMap<Instruction *, Constant *> &Vals, 8484 const DataLayout &DL, 8485 const TargetLibraryInfo *TLI) { 8486 // Convenient constant check, but redundant for recursive calls. 8487 if (Constant *C = dyn_cast<Constant>(V)) return C; 8488 Instruction *I = dyn_cast<Instruction>(V); 8489 if (!I) return nullptr; 8490 8491 if (Constant *C = Vals.lookup(I)) return C; 8492 8493 // An instruction inside the loop depends on a value outside the loop that we 8494 // weren't given a mapping for, or a value such as a call inside the loop. 8495 if (!canConstantEvolve(I, L)) return nullptr; 8496 8497 // An unmapped PHI can be due to a branch or another loop inside this loop, 8498 // or due to this not being the initial iteration through a loop where we 8499 // couldn't compute the evolution of this particular PHI last time. 8500 if (isa<PHINode>(I)) return nullptr; 8501 8502 std::vector<Constant*> Operands(I->getNumOperands()); 8503 8504 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8505 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8506 if (!Operand) { 8507 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8508 if (!Operands[i]) return nullptr; 8509 continue; 8510 } 8511 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8512 Vals[Operand] = C; 8513 if (!C) return nullptr; 8514 Operands[i] = C; 8515 } 8516 8517 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8518 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8519 Operands[1], DL, TLI); 8520 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8521 if (!LI->isVolatile()) 8522 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8523 } 8524 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8525 } 8526 8527 8528 // If every incoming value to PN except the one for BB is a specific Constant, 8529 // return that, else return nullptr. 8530 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8531 Constant *IncomingVal = nullptr; 8532 8533 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8534 if (PN->getIncomingBlock(i) == BB) 8535 continue; 8536 8537 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8538 if (!CurrentVal) 8539 return nullptr; 8540 8541 if (IncomingVal != CurrentVal) { 8542 if (IncomingVal) 8543 return nullptr; 8544 IncomingVal = CurrentVal; 8545 } 8546 } 8547 8548 return IncomingVal; 8549 } 8550 8551 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8552 /// in the header of its containing loop, we know the loop executes a 8553 /// constant number of times, and the PHI node is just a recurrence 8554 /// involving constants, fold it. 8555 Constant * 8556 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8557 const APInt &BEs, 8558 const Loop *L) { 8559 auto I = ConstantEvolutionLoopExitValue.find(PN); 8560 if (I != ConstantEvolutionLoopExitValue.end()) 8561 return I->second; 8562 8563 if (BEs.ugt(MaxBruteForceIterations)) 8564 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8565 8566 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8567 8568 DenseMap<Instruction *, Constant *> CurrentIterVals; 8569 BasicBlock *Header = L->getHeader(); 8570 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8571 8572 BasicBlock *Latch = L->getLoopLatch(); 8573 if (!Latch) 8574 return nullptr; 8575 8576 for (PHINode &PHI : Header->phis()) { 8577 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8578 CurrentIterVals[&PHI] = StartCST; 8579 } 8580 if (!CurrentIterVals.count(PN)) 8581 return RetVal = nullptr; 8582 8583 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8584 8585 // Execute the loop symbolically to determine the exit value. 8586 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8587 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8588 8589 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8590 unsigned IterationNum = 0; 8591 const DataLayout &DL = getDataLayout(); 8592 for (; ; ++IterationNum) { 8593 if (IterationNum == NumIterations) 8594 return RetVal = CurrentIterVals[PN]; // Got exit value! 8595 8596 // Compute the value of the PHIs for the next iteration. 8597 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8598 DenseMap<Instruction *, Constant *> NextIterVals; 8599 Constant *NextPHI = 8600 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8601 if (!NextPHI) 8602 return nullptr; // Couldn't evaluate! 8603 NextIterVals[PN] = NextPHI; 8604 8605 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8606 8607 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8608 // cease to be able to evaluate one of them or if they stop evolving, 8609 // because that doesn't necessarily prevent us from computing PN. 8610 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8611 for (const auto &I : CurrentIterVals) { 8612 PHINode *PHI = dyn_cast<PHINode>(I.first); 8613 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8614 PHIsToCompute.emplace_back(PHI, I.second); 8615 } 8616 // We use two distinct loops because EvaluateExpression may invalidate any 8617 // iterators into CurrentIterVals. 8618 for (const auto &I : PHIsToCompute) { 8619 PHINode *PHI = I.first; 8620 Constant *&NextPHI = NextIterVals[PHI]; 8621 if (!NextPHI) { // Not already computed. 8622 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8623 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8624 } 8625 if (NextPHI != I.second) 8626 StoppedEvolving = false; 8627 } 8628 8629 // If all entries in CurrentIterVals == NextIterVals then we can stop 8630 // iterating, the loop can't continue to change. 8631 if (StoppedEvolving) 8632 return RetVal = CurrentIterVals[PN]; 8633 8634 CurrentIterVals.swap(NextIterVals); 8635 } 8636 } 8637 8638 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8639 Value *Cond, 8640 bool ExitWhen) { 8641 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8642 if (!PN) return getCouldNotCompute(); 8643 8644 // If the loop is canonicalized, the PHI will have exactly two entries. 8645 // That's the only form we support here. 8646 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8647 8648 DenseMap<Instruction *, Constant *> CurrentIterVals; 8649 BasicBlock *Header = L->getHeader(); 8650 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8651 8652 BasicBlock *Latch = L->getLoopLatch(); 8653 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8654 8655 for (PHINode &PHI : Header->phis()) { 8656 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8657 CurrentIterVals[&PHI] = StartCST; 8658 } 8659 if (!CurrentIterVals.count(PN)) 8660 return getCouldNotCompute(); 8661 8662 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8663 // the loop symbolically to determine when the condition gets a value of 8664 // "ExitWhen". 8665 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8666 const DataLayout &DL = getDataLayout(); 8667 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8668 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8669 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8670 8671 // Couldn't symbolically evaluate. 8672 if (!CondVal) return getCouldNotCompute(); 8673 8674 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8675 ++NumBruteForceTripCountsComputed; 8676 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8677 } 8678 8679 // Update all the PHI nodes for the next iteration. 8680 DenseMap<Instruction *, Constant *> NextIterVals; 8681 8682 // Create a list of which PHIs we need to compute. We want to do this before 8683 // calling EvaluateExpression on them because that may invalidate iterators 8684 // into CurrentIterVals. 8685 SmallVector<PHINode *, 8> PHIsToCompute; 8686 for (const auto &I : CurrentIterVals) { 8687 PHINode *PHI = dyn_cast<PHINode>(I.first); 8688 if (!PHI || PHI->getParent() != Header) continue; 8689 PHIsToCompute.push_back(PHI); 8690 } 8691 for (PHINode *PHI : PHIsToCompute) { 8692 Constant *&NextPHI = NextIterVals[PHI]; 8693 if (NextPHI) continue; // Already computed! 8694 8695 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8696 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8697 } 8698 CurrentIterVals.swap(NextIterVals); 8699 } 8700 8701 // Too many iterations were needed to evaluate. 8702 return getCouldNotCompute(); 8703 } 8704 8705 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8706 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8707 ValuesAtScopes[V]; 8708 // Check to see if we've folded this expression at this loop before. 8709 for (auto &LS : Values) 8710 if (LS.first == L) 8711 return LS.second ? LS.second : V; 8712 8713 Values.emplace_back(L, nullptr); 8714 8715 // Otherwise compute it. 8716 const SCEV *C = computeSCEVAtScope(V, L); 8717 for (auto &LS : reverse(ValuesAtScopes[V])) 8718 if (LS.first == L) { 8719 LS.second = C; 8720 break; 8721 } 8722 return C; 8723 } 8724 8725 /// This builds up a Constant using the ConstantExpr interface. That way, we 8726 /// will return Constants for objects which aren't represented by a 8727 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8728 /// Returns NULL if the SCEV isn't representable as a Constant. 8729 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8730 switch (V->getSCEVType()) { 8731 case scCouldNotCompute: 8732 case scAddRecExpr: 8733 return nullptr; 8734 case scConstant: 8735 return cast<SCEVConstant>(V)->getValue(); 8736 case scUnknown: 8737 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8738 case scSignExtend: { 8739 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8740 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8741 return ConstantExpr::getSExt(CastOp, SS->getType()); 8742 return nullptr; 8743 } 8744 case scZeroExtend: { 8745 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8746 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8747 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8748 return nullptr; 8749 } 8750 case scPtrToInt: { 8751 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8752 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8753 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8754 8755 return nullptr; 8756 } 8757 case scTruncate: { 8758 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8759 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8760 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8761 return nullptr; 8762 } 8763 case scAddExpr: { 8764 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8765 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8766 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8767 unsigned AS = PTy->getAddressSpace(); 8768 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8769 C = ConstantExpr::getBitCast(C, DestPtrTy); 8770 } 8771 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8772 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8773 if (!C2) 8774 return nullptr; 8775 8776 // First pointer! 8777 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8778 unsigned AS = C2->getType()->getPointerAddressSpace(); 8779 std::swap(C, C2); 8780 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8781 // The offsets have been converted to bytes. We can add bytes to an 8782 // i8* by GEP with the byte count in the first index. 8783 C = ConstantExpr::getBitCast(C, DestPtrTy); 8784 } 8785 8786 // Don't bother trying to sum two pointers. We probably can't 8787 // statically compute a load that results from it anyway. 8788 if (C2->getType()->isPointerTy()) 8789 return nullptr; 8790 8791 if (C->getType()->isPointerTy()) { 8792 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8793 C, C2); 8794 } else { 8795 C = ConstantExpr::getAdd(C, C2); 8796 } 8797 } 8798 return C; 8799 } 8800 return nullptr; 8801 } 8802 case scMulExpr: { 8803 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8804 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8805 // Don't bother with pointers at all. 8806 if (C->getType()->isPointerTy()) 8807 return nullptr; 8808 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8809 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8810 if (!C2 || C2->getType()->isPointerTy()) 8811 return nullptr; 8812 C = ConstantExpr::getMul(C, C2); 8813 } 8814 return C; 8815 } 8816 return nullptr; 8817 } 8818 case scUDivExpr: { 8819 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8820 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8821 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8822 if (LHS->getType() == RHS->getType()) 8823 return ConstantExpr::getUDiv(LHS, RHS); 8824 return nullptr; 8825 } 8826 case scSMaxExpr: 8827 case scUMaxExpr: 8828 case scSMinExpr: 8829 case scUMinExpr: 8830 return nullptr; // TODO: smax, umax, smin, umax. 8831 } 8832 llvm_unreachable("Unknown SCEV kind!"); 8833 } 8834 8835 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8836 if (isa<SCEVConstant>(V)) return V; 8837 8838 // If this instruction is evolved from a constant-evolving PHI, compute the 8839 // exit value from the loop without using SCEVs. 8840 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8841 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8842 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8843 const Loop *CurrLoop = this->LI[I->getParent()]; 8844 // Looking for loop exit value. 8845 if (CurrLoop && CurrLoop->getParentLoop() == L && 8846 PN->getParent() == CurrLoop->getHeader()) { 8847 // Okay, there is no closed form solution for the PHI node. Check 8848 // to see if the loop that contains it has a known backedge-taken 8849 // count. If so, we may be able to force computation of the exit 8850 // value. 8851 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8852 // This trivial case can show up in some degenerate cases where 8853 // the incoming IR has not yet been fully simplified. 8854 if (BackedgeTakenCount->isZero()) { 8855 Value *InitValue = nullptr; 8856 bool MultipleInitValues = false; 8857 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8858 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8859 if (!InitValue) 8860 InitValue = PN->getIncomingValue(i); 8861 else if (InitValue != PN->getIncomingValue(i)) { 8862 MultipleInitValues = true; 8863 break; 8864 } 8865 } 8866 } 8867 if (!MultipleInitValues && InitValue) 8868 return getSCEV(InitValue); 8869 } 8870 // Do we have a loop invariant value flowing around the backedge 8871 // for a loop which must execute the backedge? 8872 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8873 isKnownPositive(BackedgeTakenCount) && 8874 PN->getNumIncomingValues() == 2) { 8875 8876 unsigned InLoopPred = 8877 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8878 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8879 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8880 return getSCEV(BackedgeVal); 8881 } 8882 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8883 // Okay, we know how many times the containing loop executes. If 8884 // this is a constant evolving PHI node, get the final value at 8885 // the specified iteration number. 8886 Constant *RV = getConstantEvolutionLoopExitValue( 8887 PN, BTCC->getAPInt(), CurrLoop); 8888 if (RV) return getSCEV(RV); 8889 } 8890 } 8891 8892 // If there is a single-input Phi, evaluate it at our scope. If we can 8893 // prove that this replacement does not break LCSSA form, use new value. 8894 if (PN->getNumOperands() == 1) { 8895 const SCEV *Input = getSCEV(PN->getOperand(0)); 8896 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8897 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8898 // for the simplest case just support constants. 8899 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8900 } 8901 } 8902 8903 // Okay, this is an expression that we cannot symbolically evaluate 8904 // into a SCEV. Check to see if it's possible to symbolically evaluate 8905 // the arguments into constants, and if so, try to constant propagate the 8906 // result. This is particularly useful for computing loop exit values. 8907 if (CanConstantFold(I)) { 8908 SmallVector<Constant *, 4> Operands; 8909 bool MadeImprovement = false; 8910 for (Value *Op : I->operands()) { 8911 if (Constant *C = dyn_cast<Constant>(Op)) { 8912 Operands.push_back(C); 8913 continue; 8914 } 8915 8916 // If any of the operands is non-constant and if they are 8917 // non-integer and non-pointer, don't even try to analyze them 8918 // with scev techniques. 8919 if (!isSCEVable(Op->getType())) 8920 return V; 8921 8922 const SCEV *OrigV = getSCEV(Op); 8923 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8924 MadeImprovement |= OrigV != OpV; 8925 8926 Constant *C = BuildConstantFromSCEV(OpV); 8927 if (!C) return V; 8928 if (C->getType() != Op->getType()) 8929 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8930 Op->getType(), 8931 false), 8932 C, Op->getType()); 8933 Operands.push_back(C); 8934 } 8935 8936 // Check to see if getSCEVAtScope actually made an improvement. 8937 if (MadeImprovement) { 8938 Constant *C = nullptr; 8939 const DataLayout &DL = getDataLayout(); 8940 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8941 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8942 Operands[1], DL, &TLI); 8943 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8944 if (!Load->isVolatile()) 8945 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8946 DL); 8947 } else 8948 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8949 if (!C) return V; 8950 return getSCEV(C); 8951 } 8952 } 8953 } 8954 8955 // This is some other type of SCEVUnknown, just return it. 8956 return V; 8957 } 8958 8959 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8960 // Avoid performing the look-up in the common case where the specified 8961 // expression has no loop-variant portions. 8962 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8963 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8964 if (OpAtScope != Comm->getOperand(i)) { 8965 // Okay, at least one of these operands is loop variant but might be 8966 // foldable. Build a new instance of the folded commutative expression. 8967 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8968 Comm->op_begin()+i); 8969 NewOps.push_back(OpAtScope); 8970 8971 for (++i; i != e; ++i) { 8972 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8973 NewOps.push_back(OpAtScope); 8974 } 8975 if (isa<SCEVAddExpr>(Comm)) 8976 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8977 if (isa<SCEVMulExpr>(Comm)) 8978 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8979 if (isa<SCEVMinMaxExpr>(Comm)) 8980 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8981 llvm_unreachable("Unknown commutative SCEV type!"); 8982 } 8983 } 8984 // If we got here, all operands are loop invariant. 8985 return Comm; 8986 } 8987 8988 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8989 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8990 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8991 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8992 return Div; // must be loop invariant 8993 return getUDivExpr(LHS, RHS); 8994 } 8995 8996 // If this is a loop recurrence for a loop that does not contain L, then we 8997 // are dealing with the final value computed by the loop. 8998 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8999 // First, attempt to evaluate each operand. 9000 // Avoid performing the look-up in the common case where the specified 9001 // expression has no loop-variant portions. 9002 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9003 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9004 if (OpAtScope == AddRec->getOperand(i)) 9005 continue; 9006 9007 // Okay, at least one of these operands is loop variant but might be 9008 // foldable. Build a new instance of the folded commutative expression. 9009 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9010 AddRec->op_begin()+i); 9011 NewOps.push_back(OpAtScope); 9012 for (++i; i != e; ++i) 9013 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9014 9015 const SCEV *FoldedRec = 9016 getAddRecExpr(NewOps, AddRec->getLoop(), 9017 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9018 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9019 // The addrec may be folded to a nonrecurrence, for example, if the 9020 // induction variable is multiplied by zero after constant folding. Go 9021 // ahead and return the folded value. 9022 if (!AddRec) 9023 return FoldedRec; 9024 break; 9025 } 9026 9027 // If the scope is outside the addrec's loop, evaluate it by using the 9028 // loop exit value of the addrec. 9029 if (!AddRec->getLoop()->contains(L)) { 9030 // To evaluate this recurrence, we need to know how many times the AddRec 9031 // loop iterates. Compute this now. 9032 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9033 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9034 9035 // Then, evaluate the AddRec. 9036 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9037 } 9038 9039 return AddRec; 9040 } 9041 9042 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9043 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9044 if (Op == Cast->getOperand()) 9045 return Cast; // must be loop invariant 9046 return getZeroExtendExpr(Op, Cast->getType()); 9047 } 9048 9049 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9050 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9051 if (Op == Cast->getOperand()) 9052 return Cast; // must be loop invariant 9053 return getSignExtendExpr(Op, Cast->getType()); 9054 } 9055 9056 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9057 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9058 if (Op == Cast->getOperand()) 9059 return Cast; // must be loop invariant 9060 return getTruncateExpr(Op, Cast->getType()); 9061 } 9062 9063 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9064 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9065 if (Op == Cast->getOperand()) 9066 return Cast; // must be loop invariant 9067 return getPtrToIntExpr(Op, Cast->getType()); 9068 } 9069 9070 llvm_unreachable("Unknown SCEV type!"); 9071 } 9072 9073 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9074 return getSCEVAtScope(getSCEV(V), L); 9075 } 9076 9077 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9078 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9079 return stripInjectiveFunctions(ZExt->getOperand()); 9080 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9081 return stripInjectiveFunctions(SExt->getOperand()); 9082 return S; 9083 } 9084 9085 /// Finds the minimum unsigned root of the following equation: 9086 /// 9087 /// A * X = B (mod N) 9088 /// 9089 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9090 /// A and B isn't important. 9091 /// 9092 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9093 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9094 ScalarEvolution &SE) { 9095 uint32_t BW = A.getBitWidth(); 9096 assert(BW == SE.getTypeSizeInBits(B->getType())); 9097 assert(A != 0 && "A must be non-zero."); 9098 9099 // 1. D = gcd(A, N) 9100 // 9101 // The gcd of A and N may have only one prime factor: 2. The number of 9102 // trailing zeros in A is its multiplicity 9103 uint32_t Mult2 = A.countTrailingZeros(); 9104 // D = 2^Mult2 9105 9106 // 2. Check if B is divisible by D. 9107 // 9108 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9109 // is not less than multiplicity of this prime factor for D. 9110 if (SE.GetMinTrailingZeros(B) < Mult2) 9111 return SE.getCouldNotCompute(); 9112 9113 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9114 // modulo (N / D). 9115 // 9116 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9117 // (N / D) in general. The inverse itself always fits into BW bits, though, 9118 // so we immediately truncate it. 9119 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9120 APInt Mod(BW + 1, 0); 9121 Mod.setBit(BW - Mult2); // Mod = N / D 9122 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9123 9124 // 4. Compute the minimum unsigned root of the equation: 9125 // I * (B / D) mod (N / D) 9126 // To simplify the computation, we factor out the divide by D: 9127 // (I * B mod N) / D 9128 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9129 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9130 } 9131 9132 /// For a given quadratic addrec, generate coefficients of the corresponding 9133 /// quadratic equation, multiplied by a common value to ensure that they are 9134 /// integers. 9135 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9136 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9137 /// were multiplied by, and BitWidth is the bit width of the original addrec 9138 /// coefficients. 9139 /// This function returns None if the addrec coefficients are not compile- 9140 /// time constants. 9141 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9142 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9143 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9144 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9145 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9146 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9147 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9148 << *AddRec << '\n'); 9149 9150 // We currently can only solve this if the coefficients are constants. 9151 if (!LC || !MC || !NC) { 9152 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9153 return None; 9154 } 9155 9156 APInt L = LC->getAPInt(); 9157 APInt M = MC->getAPInt(); 9158 APInt N = NC->getAPInt(); 9159 assert(!N.isZero() && "This is not a quadratic addrec"); 9160 9161 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9162 unsigned NewWidth = BitWidth + 1; 9163 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9164 << BitWidth << '\n'); 9165 // The sign-extension (as opposed to a zero-extension) here matches the 9166 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9167 N = N.sext(NewWidth); 9168 M = M.sext(NewWidth); 9169 L = L.sext(NewWidth); 9170 9171 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9172 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9173 // L+M, L+2M+N, L+3M+3N, ... 9174 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9175 // 9176 // The equation Acc = 0 is then 9177 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9178 // In a quadratic form it becomes: 9179 // N n^2 + (2M-N) n + 2L = 0. 9180 9181 APInt A = N; 9182 APInt B = 2 * M - A; 9183 APInt C = 2 * L; 9184 APInt T = APInt(NewWidth, 2); 9185 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9186 << "x + " << C << ", coeff bw: " << NewWidth 9187 << ", multiplied by " << T << '\n'); 9188 return std::make_tuple(A, B, C, T, BitWidth); 9189 } 9190 9191 /// Helper function to compare optional APInts: 9192 /// (a) if X and Y both exist, return min(X, Y), 9193 /// (b) if neither X nor Y exist, return None, 9194 /// (c) if exactly one of X and Y exists, return that value. 9195 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9196 if (X.hasValue() && Y.hasValue()) { 9197 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9198 APInt XW = X->sextOrSelf(W); 9199 APInt YW = Y->sextOrSelf(W); 9200 return XW.slt(YW) ? *X : *Y; 9201 } 9202 if (!X.hasValue() && !Y.hasValue()) 9203 return None; 9204 return X.hasValue() ? *X : *Y; 9205 } 9206 9207 /// Helper function to truncate an optional APInt to a given BitWidth. 9208 /// When solving addrec-related equations, it is preferable to return a value 9209 /// that has the same bit width as the original addrec's coefficients. If the 9210 /// solution fits in the original bit width, truncate it (except for i1). 9211 /// Returning a value of a different bit width may inhibit some optimizations. 9212 /// 9213 /// In general, a solution to a quadratic equation generated from an addrec 9214 /// may require BW+1 bits, where BW is the bit width of the addrec's 9215 /// coefficients. The reason is that the coefficients of the quadratic 9216 /// equation are BW+1 bits wide (to avoid truncation when converting from 9217 /// the addrec to the equation). 9218 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9219 if (!X.hasValue()) 9220 return None; 9221 unsigned W = X->getBitWidth(); 9222 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9223 return X->trunc(BitWidth); 9224 return X; 9225 } 9226 9227 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9228 /// iterations. The values L, M, N are assumed to be signed, and they 9229 /// should all have the same bit widths. 9230 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9231 /// where BW is the bit width of the addrec's coefficients. 9232 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9233 /// returned as such, otherwise the bit width of the returned value may 9234 /// be greater than BW. 9235 /// 9236 /// This function returns None if 9237 /// (a) the addrec coefficients are not constant, or 9238 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9239 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9240 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9241 static Optional<APInt> 9242 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9243 APInt A, B, C, M; 9244 unsigned BitWidth; 9245 auto T = GetQuadraticEquation(AddRec); 9246 if (!T.hasValue()) 9247 return None; 9248 9249 std::tie(A, B, C, M, BitWidth) = *T; 9250 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9251 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9252 if (!X.hasValue()) 9253 return None; 9254 9255 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9256 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9257 if (!V->isZero()) 9258 return None; 9259 9260 return TruncIfPossible(X, BitWidth); 9261 } 9262 9263 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9264 /// iterations. The values M, N are assumed to be signed, and they 9265 /// should all have the same bit widths. 9266 /// Find the least n such that c(n) does not belong to the given range, 9267 /// while c(n-1) does. 9268 /// 9269 /// This function returns None if 9270 /// (a) the addrec coefficients are not constant, or 9271 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9272 /// bounds of the range. 9273 static Optional<APInt> 9274 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9275 const ConstantRange &Range, ScalarEvolution &SE) { 9276 assert(AddRec->getOperand(0)->isZero() && 9277 "Starting value of addrec should be 0"); 9278 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9279 << Range << ", addrec " << *AddRec << '\n'); 9280 // This case is handled in getNumIterationsInRange. Here we can assume that 9281 // we start in the range. 9282 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9283 "Addrec's initial value should be in range"); 9284 9285 APInt A, B, C, M; 9286 unsigned BitWidth; 9287 auto T = GetQuadraticEquation(AddRec); 9288 if (!T.hasValue()) 9289 return None; 9290 9291 // Be careful about the return value: there can be two reasons for not 9292 // returning an actual number. First, if no solutions to the equations 9293 // were found, and second, if the solutions don't leave the given range. 9294 // The first case means that the actual solution is "unknown", the second 9295 // means that it's known, but not valid. If the solution is unknown, we 9296 // cannot make any conclusions. 9297 // Return a pair: the optional solution and a flag indicating if the 9298 // solution was found. 9299 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9300 // Solve for signed overflow and unsigned overflow, pick the lower 9301 // solution. 9302 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9303 << Bound << " (before multiplying by " << M << ")\n"); 9304 Bound *= M; // The quadratic equation multiplier. 9305 9306 Optional<APInt> SO = None; 9307 if (BitWidth > 1) { 9308 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9309 "signed overflow\n"); 9310 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9311 } 9312 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9313 "unsigned overflow\n"); 9314 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9315 BitWidth+1); 9316 9317 auto LeavesRange = [&] (const APInt &X) { 9318 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9319 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9320 if (Range.contains(V0->getValue())) 9321 return false; 9322 // X should be at least 1, so X-1 is non-negative. 9323 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9324 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9325 if (Range.contains(V1->getValue())) 9326 return true; 9327 return false; 9328 }; 9329 9330 // If SolveQuadraticEquationWrap returns None, it means that there can 9331 // be a solution, but the function failed to find it. We cannot treat it 9332 // as "no solution". 9333 if (!SO.hasValue() || !UO.hasValue()) 9334 return { None, false }; 9335 9336 // Check the smaller value first to see if it leaves the range. 9337 // At this point, both SO and UO must have values. 9338 Optional<APInt> Min = MinOptional(SO, UO); 9339 if (LeavesRange(*Min)) 9340 return { Min, true }; 9341 Optional<APInt> Max = Min == SO ? UO : SO; 9342 if (LeavesRange(*Max)) 9343 return { Max, true }; 9344 9345 // Solutions were found, but were eliminated, hence the "true". 9346 return { None, true }; 9347 }; 9348 9349 std::tie(A, B, C, M, BitWidth) = *T; 9350 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9351 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9352 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9353 auto SL = SolveForBoundary(Lower); 9354 auto SU = SolveForBoundary(Upper); 9355 // If any of the solutions was unknown, no meaninigful conclusions can 9356 // be made. 9357 if (!SL.second || !SU.second) 9358 return None; 9359 9360 // Claim: The correct solution is not some value between Min and Max. 9361 // 9362 // Justification: Assuming that Min and Max are different values, one of 9363 // them is when the first signed overflow happens, the other is when the 9364 // first unsigned overflow happens. Crossing the range boundary is only 9365 // possible via an overflow (treating 0 as a special case of it, modeling 9366 // an overflow as crossing k*2^W for some k). 9367 // 9368 // The interesting case here is when Min was eliminated as an invalid 9369 // solution, but Max was not. The argument is that if there was another 9370 // overflow between Min and Max, it would also have been eliminated if 9371 // it was considered. 9372 // 9373 // For a given boundary, it is possible to have two overflows of the same 9374 // type (signed/unsigned) without having the other type in between: this 9375 // can happen when the vertex of the parabola is between the iterations 9376 // corresponding to the overflows. This is only possible when the two 9377 // overflows cross k*2^W for the same k. In such case, if the second one 9378 // left the range (and was the first one to do so), the first overflow 9379 // would have to enter the range, which would mean that either we had left 9380 // the range before or that we started outside of it. Both of these cases 9381 // are contradictions. 9382 // 9383 // Claim: In the case where SolveForBoundary returns None, the correct 9384 // solution is not some value between the Max for this boundary and the 9385 // Min of the other boundary. 9386 // 9387 // Justification: Assume that we had such Max_A and Min_B corresponding 9388 // to range boundaries A and B and such that Max_A < Min_B. If there was 9389 // a solution between Max_A and Min_B, it would have to be caused by an 9390 // overflow corresponding to either A or B. It cannot correspond to B, 9391 // since Min_B is the first occurrence of such an overflow. If it 9392 // corresponded to A, it would have to be either a signed or an unsigned 9393 // overflow that is larger than both eliminated overflows for A. But 9394 // between the eliminated overflows and this overflow, the values would 9395 // cover the entire value space, thus crossing the other boundary, which 9396 // is a contradiction. 9397 9398 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9399 } 9400 9401 ScalarEvolution::ExitLimit 9402 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9403 bool AllowPredicates) { 9404 9405 // This is only used for loops with a "x != y" exit test. The exit condition 9406 // is now expressed as a single expression, V = x-y. So the exit test is 9407 // effectively V != 0. We know and take advantage of the fact that this 9408 // expression only being used in a comparison by zero context. 9409 9410 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9411 // If the value is a constant 9412 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9413 // If the value is already zero, the branch will execute zero times. 9414 if (C->getValue()->isZero()) return C; 9415 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9416 } 9417 9418 const SCEVAddRecExpr *AddRec = 9419 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9420 9421 if (!AddRec && AllowPredicates) 9422 // Try to make this an AddRec using runtime tests, in the first X 9423 // iterations of this loop, where X is the SCEV expression found by the 9424 // algorithm below. 9425 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9426 9427 if (!AddRec || AddRec->getLoop() != L) 9428 return getCouldNotCompute(); 9429 9430 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9431 // the quadratic equation to solve it. 9432 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9433 // We can only use this value if the chrec ends up with an exact zero 9434 // value at this index. When solving for "X*X != 5", for example, we 9435 // should not accept a root of 2. 9436 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9437 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9438 return ExitLimit(R, R, false, Predicates); 9439 } 9440 return getCouldNotCompute(); 9441 } 9442 9443 // Otherwise we can only handle this if it is affine. 9444 if (!AddRec->isAffine()) 9445 return getCouldNotCompute(); 9446 9447 // If this is an affine expression, the execution count of this branch is 9448 // the minimum unsigned root of the following equation: 9449 // 9450 // Start + Step*N = 0 (mod 2^BW) 9451 // 9452 // equivalent to: 9453 // 9454 // Step*N = -Start (mod 2^BW) 9455 // 9456 // where BW is the common bit width of Start and Step. 9457 9458 // Get the initial value for the loop. 9459 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9460 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9461 9462 // For now we handle only constant steps. 9463 // 9464 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9465 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9466 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9467 // We have not yet seen any such cases. 9468 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9469 if (!StepC || StepC->getValue()->isZero()) 9470 return getCouldNotCompute(); 9471 9472 // For positive steps (counting up until unsigned overflow): 9473 // N = -Start/Step (as unsigned) 9474 // For negative steps (counting down to zero): 9475 // N = Start/-Step 9476 // First compute the unsigned distance from zero in the direction of Step. 9477 bool CountDown = StepC->getAPInt().isNegative(); 9478 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9479 9480 // Handle unitary steps, which cannot wraparound. 9481 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9482 // N = Distance (as unsigned) 9483 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9484 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9485 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9486 if (MaxBECountBase.ult(MaxBECount)) 9487 MaxBECount = MaxBECountBase; 9488 9489 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9490 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9491 // case, and see if we can improve the bound. 9492 // 9493 // Explicitly handling this here is necessary because getUnsignedRange 9494 // isn't context-sensitive; it doesn't know that we only care about the 9495 // range inside the loop. 9496 const SCEV *Zero = getZero(Distance->getType()); 9497 const SCEV *One = getOne(Distance->getType()); 9498 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9499 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9500 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9501 // as "unsigned_max(Distance + 1) - 1". 9502 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9503 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9504 } 9505 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9506 } 9507 9508 // If the condition controls loop exit (the loop exits only if the expression 9509 // is true) and the addition is no-wrap we can use unsigned divide to 9510 // compute the backedge count. In this case, the step may not divide the 9511 // distance, but we don't care because if the condition is "missed" the loop 9512 // will have undefined behavior due to wrapping. 9513 if (ControlsExit && AddRec->hasNoSelfWrap() && 9514 loopHasNoAbnormalExits(AddRec->getLoop())) { 9515 const SCEV *Exact = 9516 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9517 const SCEV *Max = getCouldNotCompute(); 9518 if (Exact != getCouldNotCompute()) { 9519 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9520 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9521 if (BaseMaxInt.ult(MaxInt)) 9522 Max = getConstant(BaseMaxInt); 9523 else 9524 Max = getConstant(MaxInt); 9525 } 9526 return ExitLimit(Exact, Max, false, Predicates); 9527 } 9528 9529 // Solve the general equation. 9530 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9531 getNegativeSCEV(Start), *this); 9532 const SCEV *M = E == getCouldNotCompute() 9533 ? E 9534 : getConstant(getUnsignedRangeMax(E)); 9535 return ExitLimit(E, M, false, Predicates); 9536 } 9537 9538 ScalarEvolution::ExitLimit 9539 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9540 // Loops that look like: while (X == 0) are very strange indeed. We don't 9541 // handle them yet except for the trivial case. This could be expanded in the 9542 // future as needed. 9543 9544 // If the value is a constant, check to see if it is known to be non-zero 9545 // already. If so, the backedge will execute zero times. 9546 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9547 if (!C->getValue()->isZero()) 9548 return getZero(C->getType()); 9549 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9550 } 9551 9552 // We could implement others, but I really doubt anyone writes loops like 9553 // this, and if they did, they would already be constant folded. 9554 return getCouldNotCompute(); 9555 } 9556 9557 std::pair<const BasicBlock *, const BasicBlock *> 9558 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9559 const { 9560 // If the block has a unique predecessor, then there is no path from the 9561 // predecessor to the block that does not go through the direct edge 9562 // from the predecessor to the block. 9563 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9564 return {Pred, BB}; 9565 9566 // A loop's header is defined to be a block that dominates the loop. 9567 // If the header has a unique predecessor outside the loop, it must be 9568 // a block that has exactly one successor that can reach the loop. 9569 if (const Loop *L = LI.getLoopFor(BB)) 9570 return {L->getLoopPredecessor(), L->getHeader()}; 9571 9572 return {nullptr, nullptr}; 9573 } 9574 9575 /// SCEV structural equivalence is usually sufficient for testing whether two 9576 /// expressions are equal, however for the purposes of looking for a condition 9577 /// guarding a loop, it can be useful to be a little more general, since a 9578 /// front-end may have replicated the controlling expression. 9579 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9580 // Quick check to see if they are the same SCEV. 9581 if (A == B) return true; 9582 9583 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9584 // Not all instructions that are "identical" compute the same value. For 9585 // instance, two distinct alloca instructions allocating the same type are 9586 // identical and do not read memory; but compute distinct values. 9587 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9588 }; 9589 9590 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9591 // two different instructions with the same value. Check for this case. 9592 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9593 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9594 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9595 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9596 if (ComputesEqualValues(AI, BI)) 9597 return true; 9598 9599 // Otherwise assume they may have a different value. 9600 return false; 9601 } 9602 9603 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9604 const SCEV *&LHS, const SCEV *&RHS, 9605 unsigned Depth) { 9606 bool Changed = false; 9607 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9608 // '0 != 0'. 9609 auto TrivialCase = [&](bool TriviallyTrue) { 9610 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9611 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9612 return true; 9613 }; 9614 // If we hit the max recursion limit bail out. 9615 if (Depth >= 3) 9616 return false; 9617 9618 // Canonicalize a constant to the right side. 9619 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9620 // Check for both operands constant. 9621 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9622 if (ConstantExpr::getICmp(Pred, 9623 LHSC->getValue(), 9624 RHSC->getValue())->isNullValue()) 9625 return TrivialCase(false); 9626 else 9627 return TrivialCase(true); 9628 } 9629 // Otherwise swap the operands to put the constant on the right. 9630 std::swap(LHS, RHS); 9631 Pred = ICmpInst::getSwappedPredicate(Pred); 9632 Changed = true; 9633 } 9634 9635 // If we're comparing an addrec with a value which is loop-invariant in the 9636 // addrec's loop, put the addrec on the left. Also make a dominance check, 9637 // as both operands could be addrecs loop-invariant in each other's loop. 9638 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9639 const Loop *L = AR->getLoop(); 9640 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9641 std::swap(LHS, RHS); 9642 Pred = ICmpInst::getSwappedPredicate(Pred); 9643 Changed = true; 9644 } 9645 } 9646 9647 // If there's a constant operand, canonicalize comparisons with boundary 9648 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9649 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9650 const APInt &RA = RC->getAPInt(); 9651 9652 bool SimplifiedByConstantRange = false; 9653 9654 if (!ICmpInst::isEquality(Pred)) { 9655 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9656 if (ExactCR.isFullSet()) 9657 return TrivialCase(true); 9658 else if (ExactCR.isEmptySet()) 9659 return TrivialCase(false); 9660 9661 APInt NewRHS; 9662 CmpInst::Predicate NewPred; 9663 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9664 ICmpInst::isEquality(NewPred)) { 9665 // We were able to convert an inequality to an equality. 9666 Pred = NewPred; 9667 RHS = getConstant(NewRHS); 9668 Changed = SimplifiedByConstantRange = true; 9669 } 9670 } 9671 9672 if (!SimplifiedByConstantRange) { 9673 switch (Pred) { 9674 default: 9675 break; 9676 case ICmpInst::ICMP_EQ: 9677 case ICmpInst::ICMP_NE: 9678 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9679 if (!RA) 9680 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9681 if (const SCEVMulExpr *ME = 9682 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9683 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9684 ME->getOperand(0)->isAllOnesValue()) { 9685 RHS = AE->getOperand(1); 9686 LHS = ME->getOperand(1); 9687 Changed = true; 9688 } 9689 break; 9690 9691 9692 // The "Should have been caught earlier!" messages refer to the fact 9693 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9694 // should have fired on the corresponding cases, and canonicalized the 9695 // check to trivial case. 9696 9697 case ICmpInst::ICMP_UGE: 9698 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9699 Pred = ICmpInst::ICMP_UGT; 9700 RHS = getConstant(RA - 1); 9701 Changed = true; 9702 break; 9703 case ICmpInst::ICMP_ULE: 9704 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9705 Pred = ICmpInst::ICMP_ULT; 9706 RHS = getConstant(RA + 1); 9707 Changed = true; 9708 break; 9709 case ICmpInst::ICMP_SGE: 9710 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9711 Pred = ICmpInst::ICMP_SGT; 9712 RHS = getConstant(RA - 1); 9713 Changed = true; 9714 break; 9715 case ICmpInst::ICMP_SLE: 9716 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9717 Pred = ICmpInst::ICMP_SLT; 9718 RHS = getConstant(RA + 1); 9719 Changed = true; 9720 break; 9721 } 9722 } 9723 } 9724 9725 // Check for obvious equality. 9726 if (HasSameValue(LHS, RHS)) { 9727 if (ICmpInst::isTrueWhenEqual(Pred)) 9728 return TrivialCase(true); 9729 if (ICmpInst::isFalseWhenEqual(Pred)) 9730 return TrivialCase(false); 9731 } 9732 9733 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9734 // adding or subtracting 1 from one of the operands. 9735 switch (Pred) { 9736 case ICmpInst::ICMP_SLE: 9737 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9738 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9739 SCEV::FlagNSW); 9740 Pred = ICmpInst::ICMP_SLT; 9741 Changed = true; 9742 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9743 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9744 SCEV::FlagNSW); 9745 Pred = ICmpInst::ICMP_SLT; 9746 Changed = true; 9747 } 9748 break; 9749 case ICmpInst::ICMP_SGE: 9750 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9751 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9752 SCEV::FlagNSW); 9753 Pred = ICmpInst::ICMP_SGT; 9754 Changed = true; 9755 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9756 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9757 SCEV::FlagNSW); 9758 Pred = ICmpInst::ICMP_SGT; 9759 Changed = true; 9760 } 9761 break; 9762 case ICmpInst::ICMP_ULE: 9763 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9764 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9765 SCEV::FlagNUW); 9766 Pred = ICmpInst::ICMP_ULT; 9767 Changed = true; 9768 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9769 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9770 Pred = ICmpInst::ICMP_ULT; 9771 Changed = true; 9772 } 9773 break; 9774 case ICmpInst::ICMP_UGE: 9775 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9776 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9777 Pred = ICmpInst::ICMP_UGT; 9778 Changed = true; 9779 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9780 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9781 SCEV::FlagNUW); 9782 Pred = ICmpInst::ICMP_UGT; 9783 Changed = true; 9784 } 9785 break; 9786 default: 9787 break; 9788 } 9789 9790 // TODO: More simplifications are possible here. 9791 9792 // Recursively simplify until we either hit a recursion limit or nothing 9793 // changes. 9794 if (Changed) 9795 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9796 9797 return Changed; 9798 } 9799 9800 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9801 return getSignedRangeMax(S).isNegative(); 9802 } 9803 9804 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9805 return getSignedRangeMin(S).isStrictlyPositive(); 9806 } 9807 9808 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9809 return !getSignedRangeMin(S).isNegative(); 9810 } 9811 9812 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9813 return !getSignedRangeMax(S).isStrictlyPositive(); 9814 } 9815 9816 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9817 return getUnsignedRangeMin(S) != 0; 9818 } 9819 9820 std::pair<const SCEV *, const SCEV *> 9821 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9822 // Compute SCEV on entry of loop L. 9823 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9824 if (Start == getCouldNotCompute()) 9825 return { Start, Start }; 9826 // Compute post increment SCEV for loop L. 9827 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9828 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9829 return { Start, PostInc }; 9830 } 9831 9832 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9833 const SCEV *LHS, const SCEV *RHS) { 9834 // First collect all loops. 9835 SmallPtrSet<const Loop *, 8> LoopsUsed; 9836 getUsedLoops(LHS, LoopsUsed); 9837 getUsedLoops(RHS, LoopsUsed); 9838 9839 if (LoopsUsed.empty()) 9840 return false; 9841 9842 // Domination relationship must be a linear order on collected loops. 9843 #ifndef NDEBUG 9844 for (auto *L1 : LoopsUsed) 9845 for (auto *L2 : LoopsUsed) 9846 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9847 DT.dominates(L2->getHeader(), L1->getHeader())) && 9848 "Domination relationship is not a linear order"); 9849 #endif 9850 9851 const Loop *MDL = 9852 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9853 [&](const Loop *L1, const Loop *L2) { 9854 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9855 }); 9856 9857 // Get init and post increment value for LHS. 9858 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9859 // if LHS contains unknown non-invariant SCEV then bail out. 9860 if (SplitLHS.first == getCouldNotCompute()) 9861 return false; 9862 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9863 // Get init and post increment value for RHS. 9864 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9865 // if RHS contains unknown non-invariant SCEV then bail out. 9866 if (SplitRHS.first == getCouldNotCompute()) 9867 return false; 9868 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9869 // It is possible that init SCEV contains an invariant load but it does 9870 // not dominate MDL and is not available at MDL loop entry, so we should 9871 // check it here. 9872 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9873 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9874 return false; 9875 9876 // It seems backedge guard check is faster than entry one so in some cases 9877 // it can speed up whole estimation by short circuit 9878 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9879 SplitRHS.second) && 9880 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9881 } 9882 9883 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9884 const SCEV *LHS, const SCEV *RHS) { 9885 // Canonicalize the inputs first. 9886 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9887 9888 if (isKnownViaInduction(Pred, LHS, RHS)) 9889 return true; 9890 9891 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9892 return true; 9893 9894 // Otherwise see what can be done with some simple reasoning. 9895 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9896 } 9897 9898 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9899 const SCEV *LHS, 9900 const SCEV *RHS) { 9901 if (isKnownPredicate(Pred, LHS, RHS)) 9902 return true; 9903 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9904 return false; 9905 return None; 9906 } 9907 9908 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9909 const SCEV *LHS, const SCEV *RHS, 9910 const Instruction *CtxI) { 9911 // TODO: Analyze guards and assumes from Context's block. 9912 return isKnownPredicate(Pred, LHS, RHS) || 9913 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 9914 } 9915 9916 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 9917 const SCEV *LHS, 9918 const SCEV *RHS, 9919 const Instruction *CtxI) { 9920 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9921 if (KnownWithoutContext) 9922 return KnownWithoutContext; 9923 9924 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 9925 return true; 9926 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 9927 ICmpInst::getInversePredicate(Pred), 9928 LHS, RHS)) 9929 return false; 9930 return None; 9931 } 9932 9933 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9934 const SCEVAddRecExpr *LHS, 9935 const SCEV *RHS) { 9936 const Loop *L = LHS->getLoop(); 9937 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9938 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9939 } 9940 9941 Optional<ScalarEvolution::MonotonicPredicateType> 9942 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9943 ICmpInst::Predicate Pred) { 9944 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9945 9946 #ifndef NDEBUG 9947 // Verify an invariant: inverting the predicate should turn a monotonically 9948 // increasing change to a monotonically decreasing one, and vice versa. 9949 if (Result) { 9950 auto ResultSwapped = 9951 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9952 9953 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9954 assert(ResultSwapped.getValue() != Result.getValue() && 9955 "monotonicity should flip as we flip the predicate"); 9956 } 9957 #endif 9958 9959 return Result; 9960 } 9961 9962 Optional<ScalarEvolution::MonotonicPredicateType> 9963 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9964 ICmpInst::Predicate Pred) { 9965 // A zero step value for LHS means the induction variable is essentially a 9966 // loop invariant value. We don't really depend on the predicate actually 9967 // flipping from false to true (for increasing predicates, and the other way 9968 // around for decreasing predicates), all we care about is that *if* the 9969 // predicate changes then it only changes from false to true. 9970 // 9971 // A zero step value in itself is not very useful, but there may be places 9972 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9973 // as general as possible. 9974 9975 // Only handle LE/LT/GE/GT predicates. 9976 if (!ICmpInst::isRelational(Pred)) 9977 return None; 9978 9979 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9980 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9981 "Should be greater or less!"); 9982 9983 // Check that AR does not wrap. 9984 if (ICmpInst::isUnsigned(Pred)) { 9985 if (!LHS->hasNoUnsignedWrap()) 9986 return None; 9987 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9988 } else { 9989 assert(ICmpInst::isSigned(Pred) && 9990 "Relational predicate is either signed or unsigned!"); 9991 if (!LHS->hasNoSignedWrap()) 9992 return None; 9993 9994 const SCEV *Step = LHS->getStepRecurrence(*this); 9995 9996 if (isKnownNonNegative(Step)) 9997 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9998 9999 if (isKnownNonPositive(Step)) 10000 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10001 10002 return None; 10003 } 10004 } 10005 10006 Optional<ScalarEvolution::LoopInvariantPredicate> 10007 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10008 const SCEV *LHS, const SCEV *RHS, 10009 const Loop *L) { 10010 10011 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10012 if (!isLoopInvariant(RHS, L)) { 10013 if (!isLoopInvariant(LHS, L)) 10014 return None; 10015 10016 std::swap(LHS, RHS); 10017 Pred = ICmpInst::getSwappedPredicate(Pred); 10018 } 10019 10020 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10021 if (!ArLHS || ArLHS->getLoop() != L) 10022 return None; 10023 10024 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10025 if (!MonotonicType) 10026 return None; 10027 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10028 // true as the loop iterates, and the backedge is control dependent on 10029 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10030 // 10031 // * if the predicate was false in the first iteration then the predicate 10032 // is never evaluated again, since the loop exits without taking the 10033 // backedge. 10034 // * if the predicate was true in the first iteration then it will 10035 // continue to be true for all future iterations since it is 10036 // monotonically increasing. 10037 // 10038 // For both the above possibilities, we can replace the loop varying 10039 // predicate with its value on the first iteration of the loop (which is 10040 // loop invariant). 10041 // 10042 // A similar reasoning applies for a monotonically decreasing predicate, by 10043 // replacing true with false and false with true in the above two bullets. 10044 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10045 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10046 10047 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10048 return None; 10049 10050 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10051 } 10052 10053 Optional<ScalarEvolution::LoopInvariantPredicate> 10054 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10055 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10056 const Instruction *CtxI, const SCEV *MaxIter) { 10057 // Try to prove the following set of facts: 10058 // - The predicate is monotonic in the iteration space. 10059 // - If the check does not fail on the 1st iteration: 10060 // - No overflow will happen during first MaxIter iterations; 10061 // - It will not fail on the MaxIter'th iteration. 10062 // If the check does fail on the 1st iteration, we leave the loop and no 10063 // other checks matter. 10064 10065 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10066 if (!isLoopInvariant(RHS, L)) { 10067 if (!isLoopInvariant(LHS, L)) 10068 return None; 10069 10070 std::swap(LHS, RHS); 10071 Pred = ICmpInst::getSwappedPredicate(Pred); 10072 } 10073 10074 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10075 if (!AR || AR->getLoop() != L) 10076 return None; 10077 10078 // The predicate must be relational (i.e. <, <=, >=, >). 10079 if (!ICmpInst::isRelational(Pred)) 10080 return None; 10081 10082 // TODO: Support steps other than +/- 1. 10083 const SCEV *Step = AR->getStepRecurrence(*this); 10084 auto *One = getOne(Step->getType()); 10085 auto *MinusOne = getNegativeSCEV(One); 10086 if (Step != One && Step != MinusOne) 10087 return None; 10088 10089 // Type mismatch here means that MaxIter is potentially larger than max 10090 // unsigned value in start type, which mean we cannot prove no wrap for the 10091 // indvar. 10092 if (AR->getType() != MaxIter->getType()) 10093 return None; 10094 10095 // Value of IV on suggested last iteration. 10096 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10097 // Does it still meet the requirement? 10098 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10099 return None; 10100 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10101 // not exceed max unsigned value of this type), this effectively proves 10102 // that there is no wrap during the iteration. To prove that there is no 10103 // signed/unsigned wrap, we need to check that 10104 // Start <= Last for step = 1 or Start >= Last for step = -1. 10105 ICmpInst::Predicate NoOverflowPred = 10106 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10107 if (Step == MinusOne) 10108 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10109 const SCEV *Start = AR->getStart(); 10110 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10111 return None; 10112 10113 // Everything is fine. 10114 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10115 } 10116 10117 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10118 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10119 if (HasSameValue(LHS, RHS)) 10120 return ICmpInst::isTrueWhenEqual(Pred); 10121 10122 // This code is split out from isKnownPredicate because it is called from 10123 // within isLoopEntryGuardedByCond. 10124 10125 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10126 const ConstantRange &RangeRHS) { 10127 return RangeLHS.icmp(Pred, RangeRHS); 10128 }; 10129 10130 // The check at the top of the function catches the case where the values are 10131 // known to be equal. 10132 if (Pred == CmpInst::ICMP_EQ) 10133 return false; 10134 10135 if (Pred == CmpInst::ICMP_NE) { 10136 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10137 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10138 return true; 10139 auto *Diff = getMinusSCEV(LHS, RHS); 10140 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10141 } 10142 10143 if (CmpInst::isSigned(Pred)) 10144 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10145 10146 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10147 } 10148 10149 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10150 const SCEV *LHS, 10151 const SCEV *RHS) { 10152 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10153 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10154 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10155 // OutC1 and OutC2. 10156 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10157 APInt &OutC1, APInt &OutC2, 10158 SCEV::NoWrapFlags ExpectedFlags) { 10159 const SCEV *XNonConstOp, *XConstOp; 10160 const SCEV *YNonConstOp, *YConstOp; 10161 SCEV::NoWrapFlags XFlagsPresent; 10162 SCEV::NoWrapFlags YFlagsPresent; 10163 10164 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10165 XConstOp = getZero(X->getType()); 10166 XNonConstOp = X; 10167 XFlagsPresent = ExpectedFlags; 10168 } 10169 if (!isa<SCEVConstant>(XConstOp) || 10170 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10171 return false; 10172 10173 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10174 YConstOp = getZero(Y->getType()); 10175 YNonConstOp = Y; 10176 YFlagsPresent = ExpectedFlags; 10177 } 10178 10179 if (!isa<SCEVConstant>(YConstOp) || 10180 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10181 return false; 10182 10183 if (YNonConstOp != XNonConstOp) 10184 return false; 10185 10186 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10187 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10188 10189 return true; 10190 }; 10191 10192 APInt C1; 10193 APInt C2; 10194 10195 switch (Pred) { 10196 default: 10197 break; 10198 10199 case ICmpInst::ICMP_SGE: 10200 std::swap(LHS, RHS); 10201 LLVM_FALLTHROUGH; 10202 case ICmpInst::ICMP_SLE: 10203 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10204 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10205 return true; 10206 10207 break; 10208 10209 case ICmpInst::ICMP_SGT: 10210 std::swap(LHS, RHS); 10211 LLVM_FALLTHROUGH; 10212 case ICmpInst::ICMP_SLT: 10213 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10214 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10215 return true; 10216 10217 break; 10218 10219 case ICmpInst::ICMP_UGE: 10220 std::swap(LHS, RHS); 10221 LLVM_FALLTHROUGH; 10222 case ICmpInst::ICMP_ULE: 10223 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10224 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10225 return true; 10226 10227 break; 10228 10229 case ICmpInst::ICMP_UGT: 10230 std::swap(LHS, RHS); 10231 LLVM_FALLTHROUGH; 10232 case ICmpInst::ICMP_ULT: 10233 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10234 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10235 return true; 10236 break; 10237 } 10238 10239 return false; 10240 } 10241 10242 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10243 const SCEV *LHS, 10244 const SCEV *RHS) { 10245 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10246 return false; 10247 10248 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10249 // the stack can result in exponential time complexity. 10250 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10251 10252 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10253 // 10254 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10255 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10256 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10257 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10258 // use isKnownPredicate later if needed. 10259 return isKnownNonNegative(RHS) && 10260 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10261 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10262 } 10263 10264 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10265 ICmpInst::Predicate Pred, 10266 const SCEV *LHS, const SCEV *RHS) { 10267 // No need to even try if we know the module has no guards. 10268 if (!HasGuards) 10269 return false; 10270 10271 return any_of(*BB, [&](const Instruction &I) { 10272 using namespace llvm::PatternMatch; 10273 10274 Value *Condition; 10275 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10276 m_Value(Condition))) && 10277 isImpliedCond(Pred, LHS, RHS, Condition, false); 10278 }); 10279 } 10280 10281 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10282 /// protected by a conditional between LHS and RHS. This is used to 10283 /// to eliminate casts. 10284 bool 10285 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10286 ICmpInst::Predicate Pred, 10287 const SCEV *LHS, const SCEV *RHS) { 10288 // Interpret a null as meaning no loop, where there is obviously no guard 10289 // (interprocedural conditions notwithstanding). 10290 if (!L) return true; 10291 10292 if (VerifyIR) 10293 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10294 "This cannot be done on broken IR!"); 10295 10296 10297 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10298 return true; 10299 10300 BasicBlock *Latch = L->getLoopLatch(); 10301 if (!Latch) 10302 return false; 10303 10304 BranchInst *LoopContinuePredicate = 10305 dyn_cast<BranchInst>(Latch->getTerminator()); 10306 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10307 isImpliedCond(Pred, LHS, RHS, 10308 LoopContinuePredicate->getCondition(), 10309 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10310 return true; 10311 10312 // We don't want more than one activation of the following loops on the stack 10313 // -- that can lead to O(n!) time complexity. 10314 if (WalkingBEDominatingConds) 10315 return false; 10316 10317 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10318 10319 // See if we can exploit a trip count to prove the predicate. 10320 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10321 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10322 if (LatchBECount != getCouldNotCompute()) { 10323 // We know that Latch branches back to the loop header exactly 10324 // LatchBECount times. This means the backdege condition at Latch is 10325 // equivalent to "{0,+,1} u< LatchBECount". 10326 Type *Ty = LatchBECount->getType(); 10327 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10328 const SCEV *LoopCounter = 10329 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10330 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10331 LatchBECount)) 10332 return true; 10333 } 10334 10335 // Check conditions due to any @llvm.assume intrinsics. 10336 for (auto &AssumeVH : AC.assumptions()) { 10337 if (!AssumeVH) 10338 continue; 10339 auto *CI = cast<CallInst>(AssumeVH); 10340 if (!DT.dominates(CI, Latch->getTerminator())) 10341 continue; 10342 10343 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10344 return true; 10345 } 10346 10347 // If the loop is not reachable from the entry block, we risk running into an 10348 // infinite loop as we walk up into the dom tree. These loops do not matter 10349 // anyway, so we just return a conservative answer when we see them. 10350 if (!DT.isReachableFromEntry(L->getHeader())) 10351 return false; 10352 10353 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10354 return true; 10355 10356 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10357 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10358 assert(DTN && "should reach the loop header before reaching the root!"); 10359 10360 BasicBlock *BB = DTN->getBlock(); 10361 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10362 return true; 10363 10364 BasicBlock *PBB = BB->getSinglePredecessor(); 10365 if (!PBB) 10366 continue; 10367 10368 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10369 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10370 continue; 10371 10372 Value *Condition = ContinuePredicate->getCondition(); 10373 10374 // If we have an edge `E` within the loop body that dominates the only 10375 // latch, the condition guarding `E` also guards the backedge. This 10376 // reasoning works only for loops with a single latch. 10377 10378 BasicBlockEdge DominatingEdge(PBB, BB); 10379 if (DominatingEdge.isSingleEdge()) { 10380 // We're constructively (and conservatively) enumerating edges within the 10381 // loop body that dominate the latch. The dominator tree better agree 10382 // with us on this: 10383 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10384 10385 if (isImpliedCond(Pred, LHS, RHS, Condition, 10386 BB != ContinuePredicate->getSuccessor(0))) 10387 return true; 10388 } 10389 } 10390 10391 return false; 10392 } 10393 10394 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10395 ICmpInst::Predicate Pred, 10396 const SCEV *LHS, 10397 const SCEV *RHS) { 10398 if (VerifyIR) 10399 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10400 "This cannot be done on broken IR!"); 10401 10402 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10403 // the facts (a >= b && a != b) separately. A typical situation is when the 10404 // non-strict comparison is known from ranges and non-equality is known from 10405 // dominating predicates. If we are proving strict comparison, we always try 10406 // to prove non-equality and non-strict comparison separately. 10407 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10408 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10409 bool ProvedNonStrictComparison = false; 10410 bool ProvedNonEquality = false; 10411 10412 auto SplitAndProve = 10413 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10414 if (!ProvedNonStrictComparison) 10415 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10416 if (!ProvedNonEquality) 10417 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10418 if (ProvedNonStrictComparison && ProvedNonEquality) 10419 return true; 10420 return false; 10421 }; 10422 10423 if (ProvingStrictComparison) { 10424 auto ProofFn = [&](ICmpInst::Predicate P) { 10425 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10426 }; 10427 if (SplitAndProve(ProofFn)) 10428 return true; 10429 } 10430 10431 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10432 auto ProveViaGuard = [&](const BasicBlock *Block) { 10433 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10434 return true; 10435 if (ProvingStrictComparison) { 10436 auto ProofFn = [&](ICmpInst::Predicate P) { 10437 return isImpliedViaGuard(Block, P, LHS, RHS); 10438 }; 10439 if (SplitAndProve(ProofFn)) 10440 return true; 10441 } 10442 return false; 10443 }; 10444 10445 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10446 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10447 const Instruction *CtxI = &BB->front(); 10448 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10449 return true; 10450 if (ProvingStrictComparison) { 10451 auto ProofFn = [&](ICmpInst::Predicate P) { 10452 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10453 }; 10454 if (SplitAndProve(ProofFn)) 10455 return true; 10456 } 10457 return false; 10458 }; 10459 10460 // Starting at the block's predecessor, climb up the predecessor chain, as long 10461 // as there are predecessors that can be found that have unique successors 10462 // leading to the original block. 10463 const Loop *ContainingLoop = LI.getLoopFor(BB); 10464 const BasicBlock *PredBB; 10465 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10466 PredBB = ContainingLoop->getLoopPredecessor(); 10467 else 10468 PredBB = BB->getSinglePredecessor(); 10469 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10470 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10471 if (ProveViaGuard(Pair.first)) 10472 return true; 10473 10474 const BranchInst *LoopEntryPredicate = 10475 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10476 if (!LoopEntryPredicate || 10477 LoopEntryPredicate->isUnconditional()) 10478 continue; 10479 10480 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10481 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10482 return true; 10483 } 10484 10485 // Check conditions due to any @llvm.assume intrinsics. 10486 for (auto &AssumeVH : AC.assumptions()) { 10487 if (!AssumeVH) 10488 continue; 10489 auto *CI = cast<CallInst>(AssumeVH); 10490 if (!DT.dominates(CI, BB)) 10491 continue; 10492 10493 if (ProveViaCond(CI->getArgOperand(0), false)) 10494 return true; 10495 } 10496 10497 return false; 10498 } 10499 10500 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10501 ICmpInst::Predicate Pred, 10502 const SCEV *LHS, 10503 const SCEV *RHS) { 10504 // Interpret a null as meaning no loop, where there is obviously no guard 10505 // (interprocedural conditions notwithstanding). 10506 if (!L) 10507 return false; 10508 10509 // Both LHS and RHS must be available at loop entry. 10510 assert(isAvailableAtLoopEntry(LHS, L) && 10511 "LHS is not available at Loop Entry"); 10512 assert(isAvailableAtLoopEntry(RHS, L) && 10513 "RHS is not available at Loop Entry"); 10514 10515 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10516 return true; 10517 10518 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10519 } 10520 10521 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10522 const SCEV *RHS, 10523 const Value *FoundCondValue, bool Inverse, 10524 const Instruction *CtxI) { 10525 // False conditions implies anything. Do not bother analyzing it further. 10526 if (FoundCondValue == 10527 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10528 return true; 10529 10530 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10531 return false; 10532 10533 auto ClearOnExit = 10534 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10535 10536 // Recursively handle And and Or conditions. 10537 const Value *Op0, *Op1; 10538 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10539 if (!Inverse) 10540 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10541 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10542 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10543 if (Inverse) 10544 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10545 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10546 } 10547 10548 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10549 if (!ICI) return false; 10550 10551 // Now that we found a conditional branch that dominates the loop or controls 10552 // the loop latch. Check to see if it is the comparison we are looking for. 10553 ICmpInst::Predicate FoundPred; 10554 if (Inverse) 10555 FoundPred = ICI->getInversePredicate(); 10556 else 10557 FoundPred = ICI->getPredicate(); 10558 10559 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10560 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10561 10562 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10563 } 10564 10565 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10566 const SCEV *RHS, 10567 ICmpInst::Predicate FoundPred, 10568 const SCEV *FoundLHS, const SCEV *FoundRHS, 10569 const Instruction *CtxI) { 10570 // Balance the types. 10571 if (getTypeSizeInBits(LHS->getType()) < 10572 getTypeSizeInBits(FoundLHS->getType())) { 10573 // For unsigned and equality predicates, try to prove that both found 10574 // operands fit into narrow unsigned range. If so, try to prove facts in 10575 // narrow types. 10576 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10577 auto *NarrowType = LHS->getType(); 10578 auto *WideType = FoundLHS->getType(); 10579 auto BitWidth = getTypeSizeInBits(NarrowType); 10580 const SCEV *MaxValue = getZeroExtendExpr( 10581 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10582 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10583 MaxValue) && 10584 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10585 MaxValue)) { 10586 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10587 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10588 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10589 TruncFoundRHS, CtxI)) 10590 return true; 10591 } 10592 } 10593 10594 if (LHS->getType()->isPointerTy()) 10595 return false; 10596 if (CmpInst::isSigned(Pred)) { 10597 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10598 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10599 } else { 10600 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10601 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10602 } 10603 } else if (getTypeSizeInBits(LHS->getType()) > 10604 getTypeSizeInBits(FoundLHS->getType())) { 10605 if (FoundLHS->getType()->isPointerTy()) 10606 return false; 10607 if (CmpInst::isSigned(FoundPred)) { 10608 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10609 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10610 } else { 10611 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10612 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10613 } 10614 } 10615 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10616 FoundRHS, CtxI); 10617 } 10618 10619 bool ScalarEvolution::isImpliedCondBalancedTypes( 10620 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10621 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10622 const Instruction *CtxI) { 10623 assert(getTypeSizeInBits(LHS->getType()) == 10624 getTypeSizeInBits(FoundLHS->getType()) && 10625 "Types should be balanced!"); 10626 // Canonicalize the query to match the way instcombine will have 10627 // canonicalized the comparison. 10628 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10629 if (LHS == RHS) 10630 return CmpInst::isTrueWhenEqual(Pred); 10631 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10632 if (FoundLHS == FoundRHS) 10633 return CmpInst::isFalseWhenEqual(FoundPred); 10634 10635 // Check to see if we can make the LHS or RHS match. 10636 if (LHS == FoundRHS || RHS == FoundLHS) { 10637 if (isa<SCEVConstant>(RHS)) { 10638 std::swap(FoundLHS, FoundRHS); 10639 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10640 } else { 10641 std::swap(LHS, RHS); 10642 Pred = ICmpInst::getSwappedPredicate(Pred); 10643 } 10644 } 10645 10646 // Check whether the found predicate is the same as the desired predicate. 10647 if (FoundPred == Pred) 10648 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10649 10650 // Check whether swapping the found predicate makes it the same as the 10651 // desired predicate. 10652 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10653 // We can write the implication 10654 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10655 // using one of the following ways: 10656 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10657 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10658 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10659 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10660 // Forms 1. and 2. require swapping the operands of one condition. Don't 10661 // do this if it would break canonical constant/addrec ordering. 10662 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10663 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10664 CtxI); 10665 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10666 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 10667 10668 // There's no clear preference between forms 3. and 4., try both. Avoid 10669 // forming getNotSCEV of pointer values as the resulting subtract is 10670 // not legal. 10671 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 10672 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10673 FoundLHS, FoundRHS, CtxI)) 10674 return true; 10675 10676 if (!FoundLHS->getType()->isPointerTy() && 10677 !FoundRHS->getType()->isPointerTy() && 10678 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10679 getNotSCEV(FoundRHS), CtxI)) 10680 return true; 10681 10682 return false; 10683 } 10684 10685 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 10686 CmpInst::Predicate P2) { 10687 assert(P1 != P2 && "Handled earlier!"); 10688 return CmpInst::isRelational(P2) && 10689 P1 == CmpInst::getFlippedSignednessPredicate(P2); 10690 }; 10691 if (IsSignFlippedPredicate(Pred, FoundPred)) { 10692 // Unsigned comparison is the same as signed comparison when both the 10693 // operands are non-negative or negative. 10694 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 10695 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 10696 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10697 // Create local copies that we can freely swap and canonicalize our 10698 // conditions to "le/lt". 10699 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 10700 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 10701 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 10702 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 10703 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 10704 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 10705 std::swap(CanonicalLHS, CanonicalRHS); 10706 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 10707 } 10708 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 10709 "Must be!"); 10710 assert((ICmpInst::isLT(CanonicalFoundPred) || 10711 ICmpInst::isLE(CanonicalFoundPred)) && 10712 "Must be!"); 10713 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 10714 // Use implication: 10715 // x <u y && y >=s 0 --> x <s y. 10716 // If we can prove the left part, the right part is also proven. 10717 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10718 CanonicalRHS, CanonicalFoundLHS, 10719 CanonicalFoundRHS); 10720 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 10721 // Use implication: 10722 // x <s y && y <s 0 --> x <u y. 10723 // If we can prove the left part, the right part is also proven. 10724 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 10725 CanonicalRHS, CanonicalFoundLHS, 10726 CanonicalFoundRHS); 10727 } 10728 10729 // Check if we can make progress by sharpening ranges. 10730 if (FoundPred == ICmpInst::ICMP_NE && 10731 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10732 10733 const SCEVConstant *C = nullptr; 10734 const SCEV *V = nullptr; 10735 10736 if (isa<SCEVConstant>(FoundLHS)) { 10737 C = cast<SCEVConstant>(FoundLHS); 10738 V = FoundRHS; 10739 } else { 10740 C = cast<SCEVConstant>(FoundRHS); 10741 V = FoundLHS; 10742 } 10743 10744 // The guarding predicate tells us that C != V. If the known range 10745 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10746 // range we consider has to correspond to same signedness as the 10747 // predicate we're interested in folding. 10748 10749 APInt Min = ICmpInst::isSigned(Pred) ? 10750 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10751 10752 if (Min == C->getAPInt()) { 10753 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10754 // This is true even if (Min + 1) wraps around -- in case of 10755 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10756 10757 APInt SharperMin = Min + 1; 10758 10759 switch (Pred) { 10760 case ICmpInst::ICMP_SGE: 10761 case ICmpInst::ICMP_UGE: 10762 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10763 // RHS, we're done. 10764 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10765 CtxI)) 10766 return true; 10767 LLVM_FALLTHROUGH; 10768 10769 case ICmpInst::ICMP_SGT: 10770 case ICmpInst::ICMP_UGT: 10771 // We know from the range information that (V `Pred` Min || 10772 // V == Min). We know from the guarding condition that !(V 10773 // == Min). This gives us 10774 // 10775 // V `Pred` Min || V == Min && !(V == Min) 10776 // => V `Pred` Min 10777 // 10778 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10779 10780 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 10781 return true; 10782 break; 10783 10784 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10785 case ICmpInst::ICMP_SLE: 10786 case ICmpInst::ICMP_ULE: 10787 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10788 LHS, V, getConstant(SharperMin), CtxI)) 10789 return true; 10790 LLVM_FALLTHROUGH; 10791 10792 case ICmpInst::ICMP_SLT: 10793 case ICmpInst::ICMP_ULT: 10794 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10795 LHS, V, getConstant(Min), CtxI)) 10796 return true; 10797 break; 10798 10799 default: 10800 // No change 10801 break; 10802 } 10803 } 10804 } 10805 10806 // Check whether the actual condition is beyond sufficient. 10807 if (FoundPred == ICmpInst::ICMP_EQ) 10808 if (ICmpInst::isTrueWhenEqual(Pred)) 10809 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10810 return true; 10811 if (Pred == ICmpInst::ICMP_NE) 10812 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10813 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10814 return true; 10815 10816 // Otherwise assume the worst. 10817 return false; 10818 } 10819 10820 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10821 const SCEV *&L, const SCEV *&R, 10822 SCEV::NoWrapFlags &Flags) { 10823 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10824 if (!AE || AE->getNumOperands() != 2) 10825 return false; 10826 10827 L = AE->getOperand(0); 10828 R = AE->getOperand(1); 10829 Flags = AE->getNoWrapFlags(); 10830 return true; 10831 } 10832 10833 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10834 const SCEV *Less) { 10835 // We avoid subtracting expressions here because this function is usually 10836 // fairly deep in the call stack (i.e. is called many times). 10837 10838 // X - X = 0. 10839 if (More == Less) 10840 return APInt(getTypeSizeInBits(More->getType()), 0); 10841 10842 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10843 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10844 const auto *MAR = cast<SCEVAddRecExpr>(More); 10845 10846 if (LAR->getLoop() != MAR->getLoop()) 10847 return None; 10848 10849 // We look at affine expressions only; not for correctness but to keep 10850 // getStepRecurrence cheap. 10851 if (!LAR->isAffine() || !MAR->isAffine()) 10852 return None; 10853 10854 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10855 return None; 10856 10857 Less = LAR->getStart(); 10858 More = MAR->getStart(); 10859 10860 // fall through 10861 } 10862 10863 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10864 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10865 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10866 return M - L; 10867 } 10868 10869 SCEV::NoWrapFlags Flags; 10870 const SCEV *LLess = nullptr, *RLess = nullptr; 10871 const SCEV *LMore = nullptr, *RMore = nullptr; 10872 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10873 // Compare (X + C1) vs X. 10874 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10875 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10876 if (RLess == More) 10877 return -(C1->getAPInt()); 10878 10879 // Compare X vs (X + C2). 10880 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10881 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10882 if (RMore == Less) 10883 return C2->getAPInt(); 10884 10885 // Compare (X + C1) vs (X + C2). 10886 if (C1 && C2 && RLess == RMore) 10887 return C2->getAPInt() - C1->getAPInt(); 10888 10889 return None; 10890 } 10891 10892 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10893 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10894 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 10895 // Try to recognize the following pattern: 10896 // 10897 // FoundRHS = ... 10898 // ... 10899 // loop: 10900 // FoundLHS = {Start,+,W} 10901 // context_bb: // Basic block from the same loop 10902 // known(Pred, FoundLHS, FoundRHS) 10903 // 10904 // If some predicate is known in the context of a loop, it is also known on 10905 // each iteration of this loop, including the first iteration. Therefore, in 10906 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10907 // prove the original pred using this fact. 10908 if (!CtxI) 10909 return false; 10910 const BasicBlock *ContextBB = CtxI->getParent(); 10911 // Make sure AR varies in the context block. 10912 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10913 const Loop *L = AR->getLoop(); 10914 // Make sure that context belongs to the loop and executes on 1st iteration 10915 // (if it ever executes at all). 10916 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10917 return false; 10918 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10919 return false; 10920 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10921 } 10922 10923 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10924 const Loop *L = AR->getLoop(); 10925 // Make sure that context belongs to the loop and executes on 1st iteration 10926 // (if it ever executes at all). 10927 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10928 return false; 10929 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10930 return false; 10931 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10932 } 10933 10934 return false; 10935 } 10936 10937 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10938 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10939 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10940 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10941 return false; 10942 10943 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10944 if (!AddRecLHS) 10945 return false; 10946 10947 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10948 if (!AddRecFoundLHS) 10949 return false; 10950 10951 // We'd like to let SCEV reason about control dependencies, so we constrain 10952 // both the inequalities to be about add recurrences on the same loop. This 10953 // way we can use isLoopEntryGuardedByCond later. 10954 10955 const Loop *L = AddRecFoundLHS->getLoop(); 10956 if (L != AddRecLHS->getLoop()) 10957 return false; 10958 10959 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10960 // 10961 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10962 // ... (2) 10963 // 10964 // Informal proof for (2), assuming (1) [*]: 10965 // 10966 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10967 // 10968 // Then 10969 // 10970 // FoundLHS s< FoundRHS s< INT_MIN - C 10971 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10972 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10973 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10974 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10975 // <=> FoundLHS + C s< FoundRHS + C 10976 // 10977 // [*]: (1) can be proved by ruling out overflow. 10978 // 10979 // [**]: This can be proved by analyzing all the four possibilities: 10980 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10981 // (A s>= 0, B s>= 0). 10982 // 10983 // Note: 10984 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10985 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10986 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10987 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10988 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10989 // C)". 10990 10991 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10992 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10993 if (!LDiff || !RDiff || *LDiff != *RDiff) 10994 return false; 10995 10996 if (LDiff->isMinValue()) 10997 return true; 10998 10999 APInt FoundRHSLimit; 11000 11001 if (Pred == CmpInst::ICMP_ULT) { 11002 FoundRHSLimit = -(*RDiff); 11003 } else { 11004 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11005 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11006 } 11007 11008 // Try to prove (1) or (2), as needed. 11009 return isAvailableAtLoopEntry(FoundRHS, L) && 11010 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11011 getConstant(FoundRHSLimit)); 11012 } 11013 11014 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11015 const SCEV *LHS, const SCEV *RHS, 11016 const SCEV *FoundLHS, 11017 const SCEV *FoundRHS, unsigned Depth) { 11018 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11019 11020 auto ClearOnExit = make_scope_exit([&]() { 11021 if (LPhi) { 11022 bool Erased = PendingMerges.erase(LPhi); 11023 assert(Erased && "Failed to erase LPhi!"); 11024 (void)Erased; 11025 } 11026 if (RPhi) { 11027 bool Erased = PendingMerges.erase(RPhi); 11028 assert(Erased && "Failed to erase RPhi!"); 11029 (void)Erased; 11030 } 11031 }); 11032 11033 // Find respective Phis and check that they are not being pending. 11034 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11035 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11036 if (!PendingMerges.insert(Phi).second) 11037 return false; 11038 LPhi = Phi; 11039 } 11040 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11041 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11042 // If we detect a loop of Phi nodes being processed by this method, for 11043 // example: 11044 // 11045 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11046 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11047 // 11048 // we don't want to deal with a case that complex, so return conservative 11049 // answer false. 11050 if (!PendingMerges.insert(Phi).second) 11051 return false; 11052 RPhi = Phi; 11053 } 11054 11055 // If none of LHS, RHS is a Phi, nothing to do here. 11056 if (!LPhi && !RPhi) 11057 return false; 11058 11059 // If there is a SCEVUnknown Phi we are interested in, make it left. 11060 if (!LPhi) { 11061 std::swap(LHS, RHS); 11062 std::swap(FoundLHS, FoundRHS); 11063 std::swap(LPhi, RPhi); 11064 Pred = ICmpInst::getSwappedPredicate(Pred); 11065 } 11066 11067 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11068 const BasicBlock *LBB = LPhi->getParent(); 11069 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11070 11071 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11072 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11073 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11074 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11075 }; 11076 11077 if (RPhi && RPhi->getParent() == LBB) { 11078 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11079 // If we compare two Phis from the same block, and for each entry block 11080 // the predicate is true for incoming values from this block, then the 11081 // predicate is also true for the Phis. 11082 for (const BasicBlock *IncBB : predecessors(LBB)) { 11083 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11084 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11085 if (!ProvedEasily(L, R)) 11086 return false; 11087 } 11088 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11089 // Case two: RHS is also a Phi from the same basic block, and it is an 11090 // AddRec. It means that there is a loop which has both AddRec and Unknown 11091 // PHIs, for it we can compare incoming values of AddRec from above the loop 11092 // and latch with their respective incoming values of LPhi. 11093 // TODO: Generalize to handle loops with many inputs in a header. 11094 if (LPhi->getNumIncomingValues() != 2) return false; 11095 11096 auto *RLoop = RAR->getLoop(); 11097 auto *Predecessor = RLoop->getLoopPredecessor(); 11098 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11099 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11100 if (!ProvedEasily(L1, RAR->getStart())) 11101 return false; 11102 auto *Latch = RLoop->getLoopLatch(); 11103 assert(Latch && "Loop with AddRec with no latch?"); 11104 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11105 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11106 return false; 11107 } else { 11108 // In all other cases go over inputs of LHS and compare each of them to RHS, 11109 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11110 // At this point RHS is either a non-Phi, or it is a Phi from some block 11111 // different from LBB. 11112 for (const BasicBlock *IncBB : predecessors(LBB)) { 11113 // Check that RHS is available in this block. 11114 if (!dominates(RHS, IncBB)) 11115 return false; 11116 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11117 // Make sure L does not refer to a value from a potentially previous 11118 // iteration of a loop. 11119 if (!properlyDominates(L, IncBB)) 11120 return false; 11121 if (!ProvedEasily(L, RHS)) 11122 return false; 11123 } 11124 } 11125 return true; 11126 } 11127 11128 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11129 const SCEV *LHS, const SCEV *RHS, 11130 const SCEV *FoundLHS, 11131 const SCEV *FoundRHS, 11132 const Instruction *CtxI) { 11133 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11134 return true; 11135 11136 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11137 return true; 11138 11139 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11140 CtxI)) 11141 return true; 11142 11143 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11144 FoundLHS, FoundRHS); 11145 } 11146 11147 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11148 template <typename MinMaxExprType> 11149 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11150 const SCEV *Candidate) { 11151 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11152 if (!MinMaxExpr) 11153 return false; 11154 11155 return is_contained(MinMaxExpr->operands(), Candidate); 11156 } 11157 11158 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11159 ICmpInst::Predicate Pred, 11160 const SCEV *LHS, const SCEV *RHS) { 11161 // If both sides are affine addrecs for the same loop, with equal 11162 // steps, and we know the recurrences don't wrap, then we only 11163 // need to check the predicate on the starting values. 11164 11165 if (!ICmpInst::isRelational(Pred)) 11166 return false; 11167 11168 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11169 if (!LAR) 11170 return false; 11171 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11172 if (!RAR) 11173 return false; 11174 if (LAR->getLoop() != RAR->getLoop()) 11175 return false; 11176 if (!LAR->isAffine() || !RAR->isAffine()) 11177 return false; 11178 11179 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11180 return false; 11181 11182 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11183 SCEV::FlagNSW : SCEV::FlagNUW; 11184 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11185 return false; 11186 11187 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11188 } 11189 11190 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11191 /// expression? 11192 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11193 ICmpInst::Predicate Pred, 11194 const SCEV *LHS, const SCEV *RHS) { 11195 switch (Pred) { 11196 default: 11197 return false; 11198 11199 case ICmpInst::ICMP_SGE: 11200 std::swap(LHS, RHS); 11201 LLVM_FALLTHROUGH; 11202 case ICmpInst::ICMP_SLE: 11203 return 11204 // min(A, ...) <= A 11205 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11206 // A <= max(A, ...) 11207 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11208 11209 case ICmpInst::ICMP_UGE: 11210 std::swap(LHS, RHS); 11211 LLVM_FALLTHROUGH; 11212 case ICmpInst::ICMP_ULE: 11213 return 11214 // min(A, ...) <= A 11215 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11216 // A <= max(A, ...) 11217 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11218 } 11219 11220 llvm_unreachable("covered switch fell through?!"); 11221 } 11222 11223 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11224 const SCEV *LHS, const SCEV *RHS, 11225 const SCEV *FoundLHS, 11226 const SCEV *FoundRHS, 11227 unsigned Depth) { 11228 assert(getTypeSizeInBits(LHS->getType()) == 11229 getTypeSizeInBits(RHS->getType()) && 11230 "LHS and RHS have different sizes?"); 11231 assert(getTypeSizeInBits(FoundLHS->getType()) == 11232 getTypeSizeInBits(FoundRHS->getType()) && 11233 "FoundLHS and FoundRHS have different sizes?"); 11234 // We want to avoid hurting the compile time with analysis of too big trees. 11235 if (Depth > MaxSCEVOperationsImplicationDepth) 11236 return false; 11237 11238 // We only want to work with GT comparison so far. 11239 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11240 Pred = CmpInst::getSwappedPredicate(Pred); 11241 std::swap(LHS, RHS); 11242 std::swap(FoundLHS, FoundRHS); 11243 } 11244 11245 // For unsigned, try to reduce it to corresponding signed comparison. 11246 if (Pred == ICmpInst::ICMP_UGT) 11247 // We can replace unsigned predicate with its signed counterpart if all 11248 // involved values are non-negative. 11249 // TODO: We could have better support for unsigned. 11250 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11251 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11252 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11253 // use this fact to prove that LHS and RHS are non-negative. 11254 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11255 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11256 FoundRHS) && 11257 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11258 FoundRHS)) 11259 Pred = ICmpInst::ICMP_SGT; 11260 } 11261 11262 if (Pred != ICmpInst::ICMP_SGT) 11263 return false; 11264 11265 auto GetOpFromSExt = [&](const SCEV *S) { 11266 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11267 return Ext->getOperand(); 11268 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11269 // the constant in some cases. 11270 return S; 11271 }; 11272 11273 // Acquire values from extensions. 11274 auto *OrigLHS = LHS; 11275 auto *OrigFoundLHS = FoundLHS; 11276 LHS = GetOpFromSExt(LHS); 11277 FoundLHS = GetOpFromSExt(FoundLHS); 11278 11279 // Is the SGT predicate can be proved trivially or using the found context. 11280 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11281 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11282 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11283 FoundRHS, Depth + 1); 11284 }; 11285 11286 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11287 // We want to avoid creation of any new non-constant SCEV. Since we are 11288 // going to compare the operands to RHS, we should be certain that we don't 11289 // need any size extensions for this. So let's decline all cases when the 11290 // sizes of types of LHS and RHS do not match. 11291 // TODO: Maybe try to get RHS from sext to catch more cases? 11292 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11293 return false; 11294 11295 // Should not overflow. 11296 if (!LHSAddExpr->hasNoSignedWrap()) 11297 return false; 11298 11299 auto *LL = LHSAddExpr->getOperand(0); 11300 auto *LR = LHSAddExpr->getOperand(1); 11301 auto *MinusOne = getMinusOne(RHS->getType()); 11302 11303 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11304 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11305 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11306 }; 11307 // Try to prove the following rule: 11308 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11309 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11310 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11311 return true; 11312 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11313 Value *LL, *LR; 11314 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11315 11316 using namespace llvm::PatternMatch; 11317 11318 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11319 // Rules for division. 11320 // We are going to perform some comparisons with Denominator and its 11321 // derivative expressions. In general case, creating a SCEV for it may 11322 // lead to a complex analysis of the entire graph, and in particular it 11323 // can request trip count recalculation for the same loop. This would 11324 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11325 // this, we only want to create SCEVs that are constants in this section. 11326 // So we bail if Denominator is not a constant. 11327 if (!isa<ConstantInt>(LR)) 11328 return false; 11329 11330 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11331 11332 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11333 // then a SCEV for the numerator already exists and matches with FoundLHS. 11334 auto *Numerator = getExistingSCEV(LL); 11335 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11336 return false; 11337 11338 // Make sure that the numerator matches with FoundLHS and the denominator 11339 // is positive. 11340 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11341 return false; 11342 11343 auto *DTy = Denominator->getType(); 11344 auto *FRHSTy = FoundRHS->getType(); 11345 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11346 // One of types is a pointer and another one is not. We cannot extend 11347 // them properly to a wider type, so let us just reject this case. 11348 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11349 // to avoid this check. 11350 return false; 11351 11352 // Given that: 11353 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11354 auto *WTy = getWiderType(DTy, FRHSTy); 11355 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11356 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11357 11358 // Try to prove the following rule: 11359 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11360 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11361 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11362 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11363 if (isKnownNonPositive(RHS) && 11364 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11365 return true; 11366 11367 // Try to prove the following rule: 11368 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11369 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11370 // If we divide it by Denominator > 2, then: 11371 // 1. If FoundLHS is negative, then the result is 0. 11372 // 2. If FoundLHS is non-negative, then the result is non-negative. 11373 // Anyways, the result is non-negative. 11374 auto *MinusOne = getMinusOne(WTy); 11375 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11376 if (isKnownNegative(RHS) && 11377 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11378 return true; 11379 } 11380 } 11381 11382 // If our expression contained SCEVUnknown Phis, and we split it down and now 11383 // need to prove something for them, try to prove the predicate for every 11384 // possible incoming values of those Phis. 11385 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11386 return true; 11387 11388 return false; 11389 } 11390 11391 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11392 const SCEV *LHS, const SCEV *RHS) { 11393 // zext x u<= sext x, sext x s<= zext x 11394 switch (Pred) { 11395 case ICmpInst::ICMP_SGE: 11396 std::swap(LHS, RHS); 11397 LLVM_FALLTHROUGH; 11398 case ICmpInst::ICMP_SLE: { 11399 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11400 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11401 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11402 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11403 return true; 11404 break; 11405 } 11406 case ICmpInst::ICMP_UGE: 11407 std::swap(LHS, RHS); 11408 LLVM_FALLTHROUGH; 11409 case ICmpInst::ICMP_ULE: { 11410 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11411 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11412 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11413 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11414 return true; 11415 break; 11416 } 11417 default: 11418 break; 11419 }; 11420 return false; 11421 } 11422 11423 bool 11424 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11425 const SCEV *LHS, const SCEV *RHS) { 11426 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11427 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11428 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11429 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11430 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11431 } 11432 11433 bool 11434 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11435 const SCEV *LHS, const SCEV *RHS, 11436 const SCEV *FoundLHS, 11437 const SCEV *FoundRHS) { 11438 switch (Pred) { 11439 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11440 case ICmpInst::ICMP_EQ: 11441 case ICmpInst::ICMP_NE: 11442 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11443 return true; 11444 break; 11445 case ICmpInst::ICMP_SLT: 11446 case ICmpInst::ICMP_SLE: 11447 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11448 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11449 return true; 11450 break; 11451 case ICmpInst::ICMP_SGT: 11452 case ICmpInst::ICMP_SGE: 11453 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11454 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11455 return true; 11456 break; 11457 case ICmpInst::ICMP_ULT: 11458 case ICmpInst::ICMP_ULE: 11459 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11460 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11461 return true; 11462 break; 11463 case ICmpInst::ICMP_UGT: 11464 case ICmpInst::ICMP_UGE: 11465 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11466 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11467 return true; 11468 break; 11469 } 11470 11471 // Maybe it can be proved via operations? 11472 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11473 return true; 11474 11475 return false; 11476 } 11477 11478 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11479 const SCEV *LHS, 11480 const SCEV *RHS, 11481 const SCEV *FoundLHS, 11482 const SCEV *FoundRHS) { 11483 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11484 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11485 // reduce the compile time impact of this optimization. 11486 return false; 11487 11488 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11489 if (!Addend) 11490 return false; 11491 11492 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11493 11494 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11495 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11496 ConstantRange FoundLHSRange = 11497 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11498 11499 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11500 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11501 11502 // We can also compute the range of values for `LHS` that satisfy the 11503 // consequent, "`LHS` `Pred` `RHS`": 11504 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11505 // The antecedent implies the consequent if every value of `LHS` that 11506 // satisfies the antecedent also satisfies the consequent. 11507 return LHSRange.icmp(Pred, ConstRHS); 11508 } 11509 11510 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11511 bool IsSigned) { 11512 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11513 11514 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11515 const SCEV *One = getOne(Stride->getType()); 11516 11517 if (IsSigned) { 11518 APInt MaxRHS = getSignedRangeMax(RHS); 11519 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11520 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11521 11522 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11523 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11524 } 11525 11526 APInt MaxRHS = getUnsignedRangeMax(RHS); 11527 APInt MaxValue = APInt::getMaxValue(BitWidth); 11528 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11529 11530 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11531 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11532 } 11533 11534 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11535 bool IsSigned) { 11536 11537 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11538 const SCEV *One = getOne(Stride->getType()); 11539 11540 if (IsSigned) { 11541 APInt MinRHS = getSignedRangeMin(RHS); 11542 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11543 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11544 11545 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11546 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11547 } 11548 11549 APInt MinRHS = getUnsignedRangeMin(RHS); 11550 APInt MinValue = APInt::getMinValue(BitWidth); 11551 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11552 11553 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11554 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11555 } 11556 11557 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11558 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11559 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11560 // expression fixes the case of N=0. 11561 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11562 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11563 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11564 } 11565 11566 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11567 const SCEV *Stride, 11568 const SCEV *End, 11569 unsigned BitWidth, 11570 bool IsSigned) { 11571 // The logic in this function assumes we can represent a positive stride. 11572 // If we can't, the backedge-taken count must be zero. 11573 if (IsSigned && BitWidth == 1) 11574 return getZero(Stride->getType()); 11575 11576 // This code has only been closely audited for negative strides in the 11577 // unsigned comparison case, it may be correct for signed comparison, but 11578 // that needs to be established. 11579 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11580 "Stride is expected strictly positive for signed case!"); 11581 11582 // Calculate the maximum backedge count based on the range of values 11583 // permitted by Start, End, and Stride. 11584 APInt MinStart = 11585 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11586 11587 APInt MinStride = 11588 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11589 11590 // We assume either the stride is positive, or the backedge-taken count 11591 // is zero. So force StrideForMaxBECount to be at least one. 11592 APInt One(BitWidth, 1); 11593 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11594 : APIntOps::umax(One, MinStride); 11595 11596 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11597 : APInt::getMaxValue(BitWidth); 11598 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11599 11600 // Although End can be a MAX expression we estimate MaxEnd considering only 11601 // the case End = RHS of the loop termination condition. This is safe because 11602 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11603 // taken count. 11604 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11605 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11606 11607 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11608 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11609 : APIntOps::umax(MaxEnd, MinStart); 11610 11611 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11612 getConstant(StrideForMaxBECount) /* Step */); 11613 } 11614 11615 ScalarEvolution::ExitLimit 11616 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11617 const Loop *L, bool IsSigned, 11618 bool ControlsExit, bool AllowPredicates) { 11619 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11620 11621 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11622 bool PredicatedIV = false; 11623 11624 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11625 // Can we prove this loop *must* be UB if overflow of IV occurs? 11626 // Reasoning goes as follows: 11627 // * Suppose the IV did self wrap. 11628 // * If Stride evenly divides the iteration space, then once wrap 11629 // occurs, the loop must revisit the same values. 11630 // * We know that RHS is invariant, and that none of those values 11631 // caused this exit to be taken previously. Thus, this exit is 11632 // dynamically dead. 11633 // * If this is the sole exit, then a dead exit implies the loop 11634 // must be infinite if there are no abnormal exits. 11635 // * If the loop were infinite, then it must either not be mustprogress 11636 // or have side effects. Otherwise, it must be UB. 11637 // * It can't (by assumption), be UB so we have contradicted our 11638 // premise and can conclude the IV did not in fact self-wrap. 11639 if (!isLoopInvariant(RHS, L)) 11640 return false; 11641 11642 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11643 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11644 return false; 11645 11646 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11647 return false; 11648 11649 return loopIsFiniteByAssumption(L); 11650 }; 11651 11652 if (!IV) { 11653 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11654 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11655 if (AR && AR->getLoop() == L && AR->isAffine()) { 11656 auto Flags = AR->getNoWrapFlags(); 11657 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11658 Flags = setFlags(Flags, SCEV::FlagNW); 11659 11660 SmallVector<const SCEV*> Operands{AR->operands()}; 11661 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11662 11663 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11664 } 11665 if (AR->hasNoUnsignedWrap()) { 11666 // Emulate what getZeroExtendExpr would have done during construction 11667 // if we'd been able to infer the fact just above at that time. 11668 const SCEV *Step = AR->getStepRecurrence(*this); 11669 Type *Ty = ZExt->getType(); 11670 auto *S = getAddRecExpr( 11671 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11672 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11673 IV = dyn_cast<SCEVAddRecExpr>(S); 11674 } 11675 } 11676 } 11677 } 11678 11679 11680 if (!IV && AllowPredicates) { 11681 // Try to make this an AddRec using runtime tests, in the first X 11682 // iterations of this loop, where X is the SCEV expression found by the 11683 // algorithm below. 11684 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11685 PredicatedIV = true; 11686 } 11687 11688 // Avoid weird loops 11689 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11690 return getCouldNotCompute(); 11691 11692 // A precondition of this method is that the condition being analyzed 11693 // reaches an exiting branch which dominates the latch. Given that, we can 11694 // assume that an increment which violates the nowrap specification and 11695 // produces poison must cause undefined behavior when the resulting poison 11696 // value is branched upon and thus we can conclude that the backedge is 11697 // taken no more often than would be required to produce that poison value. 11698 // Note that a well defined loop can exit on the iteration which violates 11699 // the nowrap specification if there is another exit (either explicit or 11700 // implicit/exceptional) which causes the loop to execute before the 11701 // exiting instruction we're analyzing would trigger UB. 11702 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11703 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11704 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11705 11706 const SCEV *Stride = IV->getStepRecurrence(*this); 11707 11708 bool PositiveStride = isKnownPositive(Stride); 11709 11710 // Avoid negative or zero stride values. 11711 if (!PositiveStride) { 11712 // We can compute the correct backedge taken count for loops with unknown 11713 // strides if we can prove that the loop is not an infinite loop with side 11714 // effects. Here's the loop structure we are trying to handle - 11715 // 11716 // i = start 11717 // do { 11718 // A[i] = i; 11719 // i += s; 11720 // } while (i < end); 11721 // 11722 // The backedge taken count for such loops is evaluated as - 11723 // (max(end, start + stride) - start - 1) /u stride 11724 // 11725 // The additional preconditions that we need to check to prove correctness 11726 // of the above formula is as follows - 11727 // 11728 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11729 // NoWrap flag). 11730 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11731 // no side effects within the loop) 11732 // c) loop has a single static exit (with no abnormal exits) 11733 // 11734 // Precondition a) implies that if the stride is negative, this is a single 11735 // trip loop. The backedge taken count formula reduces to zero in this case. 11736 // 11737 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11738 // then a zero stride means the backedge can't be taken without executing 11739 // undefined behavior. 11740 // 11741 // The positive stride case is the same as isKnownPositive(Stride) returning 11742 // true (original behavior of the function). 11743 // 11744 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 11745 !loopHasNoAbnormalExits(L)) 11746 return getCouldNotCompute(); 11747 11748 // This bailout is protecting the logic in computeMaxBECountForLT which 11749 // has not yet been sufficiently auditted or tested with negative strides. 11750 // We used to filter out all known-non-positive cases here, we're in the 11751 // process of being less restrictive bit by bit. 11752 if (IsSigned && isKnownNonPositive(Stride)) 11753 return getCouldNotCompute(); 11754 11755 if (!isKnownNonZero(Stride)) { 11756 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11757 // if it might eventually be greater than start and if so, on which 11758 // iteration. We can't even produce a useful upper bound. 11759 if (!isLoopInvariant(RHS, L)) 11760 return getCouldNotCompute(); 11761 11762 // We allow a potentially zero stride, but we need to divide by stride 11763 // below. Since the loop can't be infinite and this check must control 11764 // the sole exit, we can infer the exit must be taken on the first 11765 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11766 // we know the numerator in the divides below must be zero, so we can 11767 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11768 // and produce the right result. 11769 // FIXME: Handle the case where Stride is poison? 11770 auto wouldZeroStrideBeUB = [&]() { 11771 // Proof by contradiction. Suppose the stride were zero. If we can 11772 // prove that the backedge *is* taken on the first iteration, then since 11773 // we know this condition controls the sole exit, we must have an 11774 // infinite loop. We can't have a (well defined) infinite loop per 11775 // check just above. 11776 // Note: The (Start - Stride) term is used to get the start' term from 11777 // (start' + stride,+,stride). Remember that we only care about the 11778 // result of this expression when stride == 0 at runtime. 11779 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11780 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11781 }; 11782 if (!wouldZeroStrideBeUB()) { 11783 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11784 } 11785 } 11786 } else if (!Stride->isOne() && !NoWrap) { 11787 auto isUBOnWrap = [&]() { 11788 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11789 // follows trivially from the fact that every (un)signed-wrapped, but 11790 // not self-wrapped value must be LT than the last value before 11791 // (un)signed wrap. Since we know that last value didn't exit, nor 11792 // will any smaller one. 11793 return canAssumeNoSelfWrap(IV); 11794 }; 11795 11796 // Avoid proven overflow cases: this will ensure that the backedge taken 11797 // count will not generate any unsigned overflow. Relaxed no-overflow 11798 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11799 // undefined behaviors like the case of C language. 11800 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11801 return getCouldNotCompute(); 11802 } 11803 11804 // On all paths just preceeding, we established the following invariant: 11805 // IV can be assumed not to overflow up to and including the exiting 11806 // iteration. We proved this in one of two ways: 11807 // 1) We can show overflow doesn't occur before the exiting iteration 11808 // 1a) canIVOverflowOnLT, and b) step of one 11809 // 2) We can show that if overflow occurs, the loop must execute UB 11810 // before any possible exit. 11811 // Note that we have not yet proved RHS invariant (in general). 11812 11813 const SCEV *Start = IV->getStart(); 11814 11815 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11816 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 11817 // Use integer-typed versions for actual computation; we can't subtract 11818 // pointers in general. 11819 const SCEV *OrigStart = Start; 11820 const SCEV *OrigRHS = RHS; 11821 if (Start->getType()->isPointerTy()) { 11822 Start = getLosslessPtrToIntExpr(Start); 11823 if (isa<SCEVCouldNotCompute>(Start)) 11824 return Start; 11825 } 11826 if (RHS->getType()->isPointerTy()) { 11827 RHS = getLosslessPtrToIntExpr(RHS); 11828 if (isa<SCEVCouldNotCompute>(RHS)) 11829 return RHS; 11830 } 11831 11832 // When the RHS is not invariant, we do not know the end bound of the loop and 11833 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11834 // calculate the MaxBECount, given the start, stride and max value for the end 11835 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11836 // checked above). 11837 if (!isLoopInvariant(RHS, L)) { 11838 const SCEV *MaxBECount = computeMaxBECountForLT( 11839 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11840 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11841 false /*MaxOrZero*/, Predicates); 11842 } 11843 11844 // We use the expression (max(End,Start)-Start)/Stride to describe the 11845 // backedge count, as if the backedge is taken at least once max(End,Start) 11846 // is End and so the result is as above, and if not max(End,Start) is Start 11847 // so we get a backedge count of zero. 11848 const SCEV *BECount = nullptr; 11849 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 11850 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 11851 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 11852 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 11853 // Can we prove (max(RHS,Start) > Start - Stride? 11854 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 11855 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 11856 // In this case, we can use a refined formula for computing backedge taken 11857 // count. The general formula remains: 11858 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11859 // We want to use the alternate formula: 11860 // "((End - 1) - (Start - Stride)) /u Stride" 11861 // Let's do a quick case analysis to show these are equivalent under 11862 // our precondition that max(RHS,Start) > Start - Stride. 11863 // * For RHS <= Start, the backedge-taken count must be zero. 11864 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11865 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11866 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11867 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11868 // this to the stride of 1 case. 11869 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11870 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11871 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11872 // "((RHS - (Start - Stride) - 1) /u Stride". 11873 // Our preconditions trivially imply no overflow in that form. 11874 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11875 const SCEV *Numerator = 11876 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 11877 BECount = getUDivExpr(Numerator, Stride); 11878 } 11879 11880 const SCEV *BECountIfBackedgeTaken = nullptr; 11881 if (!BECount) { 11882 auto canProveRHSGreaterThanEqualStart = [&]() { 11883 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11884 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11885 return true; 11886 11887 // (RHS > Start - 1) implies RHS >= Start. 11888 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11889 // "Start - 1" doesn't overflow. 11890 // * For signed comparison, if Start - 1 does overflow, it's equal 11891 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11892 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11893 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11894 // 11895 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11896 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11897 auto *StartMinusOne = getAddExpr(OrigStart, 11898 getMinusOne(OrigStart->getType())); 11899 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11900 }; 11901 11902 // If we know that RHS >= Start in the context of loop, then we know that 11903 // max(RHS, Start) = RHS at this point. 11904 const SCEV *End; 11905 if (canProveRHSGreaterThanEqualStart()) { 11906 End = RHS; 11907 } else { 11908 // If RHS < Start, the backedge will be taken zero times. So in 11909 // general, we can write the backedge-taken count as: 11910 // 11911 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11912 // 11913 // We convert it to the following to make it more convenient for SCEV: 11914 // 11915 // ceil(max(RHS, Start) - Start) / Stride 11916 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11917 11918 // See what would happen if we assume the backedge is taken. This is 11919 // used to compute MaxBECount. 11920 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11921 } 11922 11923 // At this point, we know: 11924 // 11925 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11926 // 2. The index variable doesn't overflow. 11927 // 11928 // Therefore, we know N exists such that 11929 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11930 // doesn't overflow. 11931 // 11932 // Using this information, try to prove whether the addition in 11933 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11934 const SCEV *One = getOne(Stride->getType()); 11935 bool MayAddOverflow = [&] { 11936 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11937 if (StrideC->getAPInt().isPowerOf2()) { 11938 // Suppose Stride is a power of two, and Start/End are unsigned 11939 // integers. Let UMAX be the largest representable unsigned 11940 // integer. 11941 // 11942 // By the preconditions of this function, we know 11943 // "(Start + Stride * N) >= End", and this doesn't overflow. 11944 // As a formula: 11945 // 11946 // End <= (Start + Stride * N) <= UMAX 11947 // 11948 // Subtracting Start from all the terms: 11949 // 11950 // End - Start <= Stride * N <= UMAX - Start 11951 // 11952 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11953 // 11954 // End - Start <= Stride * N <= UMAX 11955 // 11956 // Stride * N is a multiple of Stride. Therefore, 11957 // 11958 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11959 // 11960 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11961 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11962 // 11963 // End - Start <= Stride * N <= UMAX - Stride - 1 11964 // 11965 // Dropping the middle term: 11966 // 11967 // End - Start <= UMAX - Stride - 1 11968 // 11969 // Adding Stride - 1 to both sides: 11970 // 11971 // (End - Start) + (Stride - 1) <= UMAX 11972 // 11973 // In other words, the addition doesn't have unsigned overflow. 11974 // 11975 // A similar proof works if we treat Start/End as signed values. 11976 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11977 // use signed max instead of unsigned max. Note that we're trying 11978 // to prove a lack of unsigned overflow in either case. 11979 return false; 11980 } 11981 } 11982 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 11983 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 11984 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 11985 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 11986 // 11987 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 11988 return false; 11989 } 11990 return true; 11991 }(); 11992 11993 const SCEV *Delta = getMinusSCEV(End, Start); 11994 if (!MayAddOverflow) { 11995 // floor((D + (S - 1)) / S) 11996 // We prefer this formulation if it's legal because it's fewer operations. 11997 BECount = 11998 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 11999 } else { 12000 BECount = getUDivCeilSCEV(Delta, Stride); 12001 } 12002 } 12003 12004 const SCEV *MaxBECount; 12005 bool MaxOrZero = false; 12006 if (isa<SCEVConstant>(BECount)) { 12007 MaxBECount = BECount; 12008 } else if (BECountIfBackedgeTaken && 12009 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12010 // If we know exactly how many times the backedge will be taken if it's 12011 // taken at least once, then the backedge count will either be that or 12012 // zero. 12013 MaxBECount = BECountIfBackedgeTaken; 12014 MaxOrZero = true; 12015 } else { 12016 MaxBECount = computeMaxBECountForLT( 12017 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12018 } 12019 12020 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12021 !isa<SCEVCouldNotCompute>(BECount)) 12022 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12023 12024 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12025 } 12026 12027 ScalarEvolution::ExitLimit 12028 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12029 const Loop *L, bool IsSigned, 12030 bool ControlsExit, bool AllowPredicates) { 12031 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12032 // We handle only IV > Invariant 12033 if (!isLoopInvariant(RHS, L)) 12034 return getCouldNotCompute(); 12035 12036 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12037 if (!IV && AllowPredicates) 12038 // Try to make this an AddRec using runtime tests, in the first X 12039 // iterations of this loop, where X is the SCEV expression found by the 12040 // algorithm below. 12041 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12042 12043 // Avoid weird loops 12044 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12045 return getCouldNotCompute(); 12046 12047 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12048 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12049 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12050 12051 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12052 12053 // Avoid negative or zero stride values 12054 if (!isKnownPositive(Stride)) 12055 return getCouldNotCompute(); 12056 12057 // Avoid proven overflow cases: this will ensure that the backedge taken count 12058 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12059 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12060 // behaviors like the case of C language. 12061 if (!Stride->isOne() && !NoWrap) 12062 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12063 return getCouldNotCompute(); 12064 12065 const SCEV *Start = IV->getStart(); 12066 const SCEV *End = RHS; 12067 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12068 // If we know that Start >= RHS in the context of loop, then we know that 12069 // min(RHS, Start) = RHS at this point. 12070 if (isLoopEntryGuardedByCond( 12071 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12072 End = RHS; 12073 else 12074 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12075 } 12076 12077 if (Start->getType()->isPointerTy()) { 12078 Start = getLosslessPtrToIntExpr(Start); 12079 if (isa<SCEVCouldNotCompute>(Start)) 12080 return Start; 12081 } 12082 if (End->getType()->isPointerTy()) { 12083 End = getLosslessPtrToIntExpr(End); 12084 if (isa<SCEVCouldNotCompute>(End)) 12085 return End; 12086 } 12087 12088 // Compute ((Start - End) + (Stride - 1)) / Stride. 12089 // FIXME: This can overflow. Holding off on fixing this for now; 12090 // howManyGreaterThans will hopefully be gone soon. 12091 const SCEV *One = getOne(Stride->getType()); 12092 const SCEV *BECount = getUDivExpr( 12093 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12094 12095 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12096 : getUnsignedRangeMax(Start); 12097 12098 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12099 : getUnsignedRangeMin(Stride); 12100 12101 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12102 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12103 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12104 12105 // Although End can be a MIN expression we estimate MinEnd considering only 12106 // the case End = RHS. This is safe because in the other case (Start - End) 12107 // is zero, leading to a zero maximum backedge taken count. 12108 APInt MinEnd = 12109 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12110 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12111 12112 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12113 ? BECount 12114 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12115 getConstant(MinStride)); 12116 12117 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12118 MaxBECount = BECount; 12119 12120 return ExitLimit(BECount, MaxBECount, false, Predicates); 12121 } 12122 12123 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12124 ScalarEvolution &SE) const { 12125 if (Range.isFullSet()) // Infinite loop. 12126 return SE.getCouldNotCompute(); 12127 12128 // If the start is a non-zero constant, shift the range to simplify things. 12129 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12130 if (!SC->getValue()->isZero()) { 12131 SmallVector<const SCEV *, 4> Operands(operands()); 12132 Operands[0] = SE.getZero(SC->getType()); 12133 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12134 getNoWrapFlags(FlagNW)); 12135 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12136 return ShiftedAddRec->getNumIterationsInRange( 12137 Range.subtract(SC->getAPInt()), SE); 12138 // This is strange and shouldn't happen. 12139 return SE.getCouldNotCompute(); 12140 } 12141 12142 // The only time we can solve this is when we have all constant indices. 12143 // Otherwise, we cannot determine the overflow conditions. 12144 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12145 return SE.getCouldNotCompute(); 12146 12147 // Okay at this point we know that all elements of the chrec are constants and 12148 // that the start element is zero. 12149 12150 // First check to see if the range contains zero. If not, the first 12151 // iteration exits. 12152 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12153 if (!Range.contains(APInt(BitWidth, 0))) 12154 return SE.getZero(getType()); 12155 12156 if (isAffine()) { 12157 // If this is an affine expression then we have this situation: 12158 // Solve {0,+,A} in Range === Ax in Range 12159 12160 // We know that zero is in the range. If A is positive then we know that 12161 // the upper value of the range must be the first possible exit value. 12162 // If A is negative then the lower of the range is the last possible loop 12163 // value. Also note that we already checked for a full range. 12164 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12165 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12166 12167 // The exit value should be (End+A)/A. 12168 APInt ExitVal = (End + A).udiv(A); 12169 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12170 12171 // Evaluate at the exit value. If we really did fall out of the valid 12172 // range, then we computed our trip count, otherwise wrap around or other 12173 // things must have happened. 12174 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12175 if (Range.contains(Val->getValue())) 12176 return SE.getCouldNotCompute(); // Something strange happened 12177 12178 // Ensure that the previous value is in the range. This is a sanity check. 12179 assert(Range.contains( 12180 EvaluateConstantChrecAtConstant(this, 12181 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12182 "Linear scev computation is off in a bad way!"); 12183 return SE.getConstant(ExitValue); 12184 } 12185 12186 if (isQuadratic()) { 12187 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12188 return SE.getConstant(S.getValue()); 12189 } 12190 12191 return SE.getCouldNotCompute(); 12192 } 12193 12194 const SCEVAddRecExpr * 12195 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12196 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12197 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12198 // but in this case we cannot guarantee that the value returned will be an 12199 // AddRec because SCEV does not have a fixed point where it stops 12200 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12201 // may happen if we reach arithmetic depth limit while simplifying. So we 12202 // construct the returned value explicitly. 12203 SmallVector<const SCEV *, 3> Ops; 12204 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12205 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12206 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12207 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12208 // We know that the last operand is not a constant zero (otherwise it would 12209 // have been popped out earlier). This guarantees us that if the result has 12210 // the same last operand, then it will also not be popped out, meaning that 12211 // the returned value will be an AddRec. 12212 const SCEV *Last = getOperand(getNumOperands() - 1); 12213 assert(!Last->isZero() && "Recurrency with zero step?"); 12214 Ops.push_back(Last); 12215 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12216 SCEV::FlagAnyWrap)); 12217 } 12218 12219 // Return true when S contains at least an undef value. 12220 static inline bool containsUndefs(const SCEV *S) { 12221 return SCEVExprContains(S, [](const SCEV *S) { 12222 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12223 return isa<UndefValue>(SU->getValue()); 12224 return false; 12225 }); 12226 } 12227 12228 /// Return the size of an element read or written by Inst. 12229 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12230 Type *Ty; 12231 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12232 Ty = Store->getValueOperand()->getType(); 12233 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12234 Ty = Load->getType(); 12235 else 12236 return nullptr; 12237 12238 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12239 return getSizeOfExpr(ETy, Ty); 12240 } 12241 12242 //===----------------------------------------------------------------------===// 12243 // SCEVCallbackVH Class Implementation 12244 //===----------------------------------------------------------------------===// 12245 12246 void ScalarEvolution::SCEVCallbackVH::deleted() { 12247 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12248 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12249 SE->ConstantEvolutionLoopExitValue.erase(PN); 12250 SE->eraseValueFromMap(getValPtr()); 12251 // this now dangles! 12252 } 12253 12254 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12255 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12256 12257 // Forget all the expressions associated with users of the old value, 12258 // so that future queries will recompute the expressions using the new 12259 // value. 12260 Value *Old = getValPtr(); 12261 SmallVector<User *, 16> Worklist(Old->users()); 12262 SmallPtrSet<User *, 8> Visited; 12263 while (!Worklist.empty()) { 12264 User *U = Worklist.pop_back_val(); 12265 // Deleting the Old value will cause this to dangle. Postpone 12266 // that until everything else is done. 12267 if (U == Old) 12268 continue; 12269 if (!Visited.insert(U).second) 12270 continue; 12271 if (PHINode *PN = dyn_cast<PHINode>(U)) 12272 SE->ConstantEvolutionLoopExitValue.erase(PN); 12273 SE->eraseValueFromMap(U); 12274 llvm::append_range(Worklist, U->users()); 12275 } 12276 // Delete the Old value. 12277 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12278 SE->ConstantEvolutionLoopExitValue.erase(PN); 12279 SE->eraseValueFromMap(Old); 12280 // this now dangles! 12281 } 12282 12283 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12284 : CallbackVH(V), SE(se) {} 12285 12286 //===----------------------------------------------------------------------===// 12287 // ScalarEvolution Class Implementation 12288 //===----------------------------------------------------------------------===// 12289 12290 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12291 AssumptionCache &AC, DominatorTree &DT, 12292 LoopInfo &LI) 12293 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12294 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12295 LoopDispositions(64), BlockDispositions(64) { 12296 // To use guards for proving predicates, we need to scan every instruction in 12297 // relevant basic blocks, and not just terminators. Doing this is a waste of 12298 // time if the IR does not actually contain any calls to 12299 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12300 // 12301 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12302 // to _add_ guards to the module when there weren't any before, and wants 12303 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12304 // efficient in lieu of being smart in that rather obscure case. 12305 12306 auto *GuardDecl = F.getParent()->getFunction( 12307 Intrinsic::getName(Intrinsic::experimental_guard)); 12308 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12309 } 12310 12311 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12312 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12313 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12314 ValueExprMap(std::move(Arg.ValueExprMap)), 12315 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12316 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12317 PendingMerges(std::move(Arg.PendingMerges)), 12318 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12319 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12320 PredicatedBackedgeTakenCounts( 12321 std::move(Arg.PredicatedBackedgeTakenCounts)), 12322 ConstantEvolutionLoopExitValue( 12323 std::move(Arg.ConstantEvolutionLoopExitValue)), 12324 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12325 LoopDispositions(std::move(Arg.LoopDispositions)), 12326 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12327 BlockDispositions(std::move(Arg.BlockDispositions)), 12328 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12329 SignedRanges(std::move(Arg.SignedRanges)), 12330 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12331 UniquePreds(std::move(Arg.UniquePreds)), 12332 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12333 LoopUsers(std::move(Arg.LoopUsers)), 12334 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12335 FirstUnknown(Arg.FirstUnknown) { 12336 Arg.FirstUnknown = nullptr; 12337 } 12338 12339 ScalarEvolution::~ScalarEvolution() { 12340 // Iterate through all the SCEVUnknown instances and call their 12341 // destructors, so that they release their references to their values. 12342 for (SCEVUnknown *U = FirstUnknown; U;) { 12343 SCEVUnknown *Tmp = U; 12344 U = U->Next; 12345 Tmp->~SCEVUnknown(); 12346 } 12347 FirstUnknown = nullptr; 12348 12349 ExprValueMap.clear(); 12350 ValueExprMap.clear(); 12351 HasRecMap.clear(); 12352 BackedgeTakenCounts.clear(); 12353 PredicatedBackedgeTakenCounts.clear(); 12354 12355 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12356 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12357 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12358 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12359 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12360 } 12361 12362 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12363 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12364 } 12365 12366 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12367 const Loop *L) { 12368 // Print all inner loops first 12369 for (Loop *I : *L) 12370 PrintLoopInfo(OS, SE, I); 12371 12372 OS << "Loop "; 12373 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12374 OS << ": "; 12375 12376 SmallVector<BasicBlock *, 8> ExitingBlocks; 12377 L->getExitingBlocks(ExitingBlocks); 12378 if (ExitingBlocks.size() != 1) 12379 OS << "<multiple exits> "; 12380 12381 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12382 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12383 else 12384 OS << "Unpredictable backedge-taken count.\n"; 12385 12386 if (ExitingBlocks.size() > 1) 12387 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12388 OS << " exit count for " << ExitingBlock->getName() << ": " 12389 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12390 } 12391 12392 OS << "Loop "; 12393 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12394 OS << ": "; 12395 12396 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12397 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12398 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12399 OS << ", actual taken count either this or zero."; 12400 } else { 12401 OS << "Unpredictable max backedge-taken count. "; 12402 } 12403 12404 OS << "\n" 12405 "Loop "; 12406 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12407 OS << ": "; 12408 12409 SCEVUnionPredicate Pred; 12410 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12411 if (!isa<SCEVCouldNotCompute>(PBT)) { 12412 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12413 OS << " Predicates:\n"; 12414 Pred.print(OS, 4); 12415 } else { 12416 OS << "Unpredictable predicated backedge-taken count. "; 12417 } 12418 OS << "\n"; 12419 12420 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12421 OS << "Loop "; 12422 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12423 OS << ": "; 12424 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12425 } 12426 } 12427 12428 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12429 switch (LD) { 12430 case ScalarEvolution::LoopVariant: 12431 return "Variant"; 12432 case ScalarEvolution::LoopInvariant: 12433 return "Invariant"; 12434 case ScalarEvolution::LoopComputable: 12435 return "Computable"; 12436 } 12437 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12438 } 12439 12440 void ScalarEvolution::print(raw_ostream &OS) const { 12441 // ScalarEvolution's implementation of the print method is to print 12442 // out SCEV values of all instructions that are interesting. Doing 12443 // this potentially causes it to create new SCEV objects though, 12444 // which technically conflicts with the const qualifier. This isn't 12445 // observable from outside the class though, so casting away the 12446 // const isn't dangerous. 12447 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12448 12449 if (ClassifyExpressions) { 12450 OS << "Classifying expressions for: "; 12451 F.printAsOperand(OS, /*PrintType=*/false); 12452 OS << "\n"; 12453 for (Instruction &I : instructions(F)) 12454 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12455 OS << I << '\n'; 12456 OS << " --> "; 12457 const SCEV *SV = SE.getSCEV(&I); 12458 SV->print(OS); 12459 if (!isa<SCEVCouldNotCompute>(SV)) { 12460 OS << " U: "; 12461 SE.getUnsignedRange(SV).print(OS); 12462 OS << " S: "; 12463 SE.getSignedRange(SV).print(OS); 12464 } 12465 12466 const Loop *L = LI.getLoopFor(I.getParent()); 12467 12468 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12469 if (AtUse != SV) { 12470 OS << " --> "; 12471 AtUse->print(OS); 12472 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12473 OS << " U: "; 12474 SE.getUnsignedRange(AtUse).print(OS); 12475 OS << " S: "; 12476 SE.getSignedRange(AtUse).print(OS); 12477 } 12478 } 12479 12480 if (L) { 12481 OS << "\t\t" "Exits: "; 12482 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12483 if (!SE.isLoopInvariant(ExitValue, L)) { 12484 OS << "<<Unknown>>"; 12485 } else { 12486 OS << *ExitValue; 12487 } 12488 12489 bool First = true; 12490 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12491 if (First) { 12492 OS << "\t\t" "LoopDispositions: { "; 12493 First = false; 12494 } else { 12495 OS << ", "; 12496 } 12497 12498 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12499 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12500 } 12501 12502 for (auto *InnerL : depth_first(L)) { 12503 if (InnerL == L) 12504 continue; 12505 if (First) { 12506 OS << "\t\t" "LoopDispositions: { "; 12507 First = false; 12508 } else { 12509 OS << ", "; 12510 } 12511 12512 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12513 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12514 } 12515 12516 OS << " }"; 12517 } 12518 12519 OS << "\n"; 12520 } 12521 } 12522 12523 OS << "Determining loop execution counts for: "; 12524 F.printAsOperand(OS, /*PrintType=*/false); 12525 OS << "\n"; 12526 for (Loop *I : LI) 12527 PrintLoopInfo(OS, &SE, I); 12528 } 12529 12530 ScalarEvolution::LoopDisposition 12531 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12532 auto &Values = LoopDispositions[S]; 12533 for (auto &V : Values) { 12534 if (V.getPointer() == L) 12535 return V.getInt(); 12536 } 12537 Values.emplace_back(L, LoopVariant); 12538 LoopDisposition D = computeLoopDisposition(S, L); 12539 auto &Values2 = LoopDispositions[S]; 12540 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12541 if (V.getPointer() == L) { 12542 V.setInt(D); 12543 break; 12544 } 12545 } 12546 return D; 12547 } 12548 12549 ScalarEvolution::LoopDisposition 12550 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12551 switch (S->getSCEVType()) { 12552 case scConstant: 12553 return LoopInvariant; 12554 case scPtrToInt: 12555 case scTruncate: 12556 case scZeroExtend: 12557 case scSignExtend: 12558 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12559 case scAddRecExpr: { 12560 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12561 12562 // If L is the addrec's loop, it's computable. 12563 if (AR->getLoop() == L) 12564 return LoopComputable; 12565 12566 // Add recurrences are never invariant in the function-body (null loop). 12567 if (!L) 12568 return LoopVariant; 12569 12570 // Everything that is not defined at loop entry is variant. 12571 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12572 return LoopVariant; 12573 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12574 " dominate the contained loop's header?"); 12575 12576 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12577 if (AR->getLoop()->contains(L)) 12578 return LoopInvariant; 12579 12580 // This recurrence is variant w.r.t. L if any of its operands 12581 // are variant. 12582 for (auto *Op : AR->operands()) 12583 if (!isLoopInvariant(Op, L)) 12584 return LoopVariant; 12585 12586 // Otherwise it's loop-invariant. 12587 return LoopInvariant; 12588 } 12589 case scAddExpr: 12590 case scMulExpr: 12591 case scUMaxExpr: 12592 case scSMaxExpr: 12593 case scUMinExpr: 12594 case scSMinExpr: { 12595 bool HasVarying = false; 12596 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12597 LoopDisposition D = getLoopDisposition(Op, L); 12598 if (D == LoopVariant) 12599 return LoopVariant; 12600 if (D == LoopComputable) 12601 HasVarying = true; 12602 } 12603 return HasVarying ? LoopComputable : LoopInvariant; 12604 } 12605 case scUDivExpr: { 12606 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12607 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12608 if (LD == LoopVariant) 12609 return LoopVariant; 12610 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12611 if (RD == LoopVariant) 12612 return LoopVariant; 12613 return (LD == LoopInvariant && RD == LoopInvariant) ? 12614 LoopInvariant : LoopComputable; 12615 } 12616 case scUnknown: 12617 // All non-instruction values are loop invariant. All instructions are loop 12618 // invariant if they are not contained in the specified loop. 12619 // Instructions are never considered invariant in the function body 12620 // (null loop) because they are defined within the "loop". 12621 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12622 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12623 return LoopInvariant; 12624 case scCouldNotCompute: 12625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12626 } 12627 llvm_unreachable("Unknown SCEV kind!"); 12628 } 12629 12630 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12631 return getLoopDisposition(S, L) == LoopInvariant; 12632 } 12633 12634 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12635 return getLoopDisposition(S, L) == LoopComputable; 12636 } 12637 12638 ScalarEvolution::BlockDisposition 12639 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12640 auto &Values = BlockDispositions[S]; 12641 for (auto &V : Values) { 12642 if (V.getPointer() == BB) 12643 return V.getInt(); 12644 } 12645 Values.emplace_back(BB, DoesNotDominateBlock); 12646 BlockDisposition D = computeBlockDisposition(S, BB); 12647 auto &Values2 = BlockDispositions[S]; 12648 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12649 if (V.getPointer() == BB) { 12650 V.setInt(D); 12651 break; 12652 } 12653 } 12654 return D; 12655 } 12656 12657 ScalarEvolution::BlockDisposition 12658 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12659 switch (S->getSCEVType()) { 12660 case scConstant: 12661 return ProperlyDominatesBlock; 12662 case scPtrToInt: 12663 case scTruncate: 12664 case scZeroExtend: 12665 case scSignExtend: 12666 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12667 case scAddRecExpr: { 12668 // This uses a "dominates" query instead of "properly dominates" query 12669 // to test for proper dominance too, because the instruction which 12670 // produces the addrec's value is a PHI, and a PHI effectively properly 12671 // dominates its entire containing block. 12672 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12673 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12674 return DoesNotDominateBlock; 12675 12676 // Fall through into SCEVNAryExpr handling. 12677 LLVM_FALLTHROUGH; 12678 } 12679 case scAddExpr: 12680 case scMulExpr: 12681 case scUMaxExpr: 12682 case scSMaxExpr: 12683 case scUMinExpr: 12684 case scSMinExpr: { 12685 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12686 bool Proper = true; 12687 for (const SCEV *NAryOp : NAry->operands()) { 12688 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12689 if (D == DoesNotDominateBlock) 12690 return DoesNotDominateBlock; 12691 if (D == DominatesBlock) 12692 Proper = false; 12693 } 12694 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12695 } 12696 case scUDivExpr: { 12697 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12698 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12699 BlockDisposition LD = getBlockDisposition(LHS, BB); 12700 if (LD == DoesNotDominateBlock) 12701 return DoesNotDominateBlock; 12702 BlockDisposition RD = getBlockDisposition(RHS, BB); 12703 if (RD == DoesNotDominateBlock) 12704 return DoesNotDominateBlock; 12705 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12706 ProperlyDominatesBlock : DominatesBlock; 12707 } 12708 case scUnknown: 12709 if (Instruction *I = 12710 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12711 if (I->getParent() == BB) 12712 return DominatesBlock; 12713 if (DT.properlyDominates(I->getParent(), BB)) 12714 return ProperlyDominatesBlock; 12715 return DoesNotDominateBlock; 12716 } 12717 return ProperlyDominatesBlock; 12718 case scCouldNotCompute: 12719 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12720 } 12721 llvm_unreachable("Unknown SCEV kind!"); 12722 } 12723 12724 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12725 return getBlockDisposition(S, BB) >= DominatesBlock; 12726 } 12727 12728 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12729 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12730 } 12731 12732 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12733 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12734 } 12735 12736 void 12737 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12738 ValuesAtScopes.erase(S); 12739 LoopDispositions.erase(S); 12740 BlockDispositions.erase(S); 12741 UnsignedRanges.erase(S); 12742 SignedRanges.erase(S); 12743 ExprValueMap.erase(S); 12744 HasRecMap.erase(S); 12745 MinTrailingZerosCache.erase(S); 12746 12747 for (auto I = PredicatedSCEVRewrites.begin(); 12748 I != PredicatedSCEVRewrites.end();) { 12749 std::pair<const SCEV *, const Loop *> Entry = I->first; 12750 if (Entry.first == S) 12751 PredicatedSCEVRewrites.erase(I++); 12752 else 12753 ++I; 12754 } 12755 12756 auto RemoveSCEVFromBackedgeMap = 12757 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12758 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12759 BackedgeTakenInfo &BEInfo = I->second; 12760 if (BEInfo.hasOperand(S)) 12761 Map.erase(I++); 12762 else 12763 ++I; 12764 } 12765 }; 12766 12767 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12768 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12769 } 12770 12771 void 12772 ScalarEvolution::getUsedLoops(const SCEV *S, 12773 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12774 struct FindUsedLoops { 12775 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12776 : LoopsUsed(LoopsUsed) {} 12777 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12778 bool follow(const SCEV *S) { 12779 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12780 LoopsUsed.insert(AR->getLoop()); 12781 return true; 12782 } 12783 12784 bool isDone() const { return false; } 12785 }; 12786 12787 FindUsedLoops F(LoopsUsed); 12788 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12789 } 12790 12791 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12792 SmallPtrSet<const Loop *, 8> LoopsUsed; 12793 getUsedLoops(S, LoopsUsed); 12794 for (auto *L : LoopsUsed) 12795 LoopUsers[L].push_back(S); 12796 } 12797 12798 void ScalarEvolution::verify() const { 12799 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12800 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12801 12802 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12803 12804 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12805 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12806 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12807 12808 const SCEV *visitConstant(const SCEVConstant *Constant) { 12809 return SE.getConstant(Constant->getAPInt()); 12810 } 12811 12812 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12813 return SE.getUnknown(Expr->getValue()); 12814 } 12815 12816 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12817 return SE.getCouldNotCompute(); 12818 } 12819 }; 12820 12821 SCEVMapper SCM(SE2); 12822 12823 while (!LoopStack.empty()) { 12824 auto *L = LoopStack.pop_back_val(); 12825 llvm::append_range(LoopStack, *L); 12826 12827 auto *CurBECount = SCM.visit( 12828 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12829 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12830 12831 if (CurBECount == SE2.getCouldNotCompute() || 12832 NewBECount == SE2.getCouldNotCompute()) { 12833 // NB! This situation is legal, but is very suspicious -- whatever pass 12834 // change the loop to make a trip count go from could not compute to 12835 // computable or vice-versa *should have* invalidated SCEV. However, we 12836 // choose not to assert here (for now) since we don't want false 12837 // positives. 12838 continue; 12839 } 12840 12841 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12842 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12843 // not propagate undef aggressively). This means we can (and do) fail 12844 // verification in cases where a transform makes the trip count of a loop 12845 // go from "undef" to "undef+1" (say). The transform is fine, since in 12846 // both cases the loop iterates "undef" times, but SCEV thinks we 12847 // increased the trip count of the loop by 1 incorrectly. 12848 continue; 12849 } 12850 12851 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12852 SE.getTypeSizeInBits(NewBECount->getType())) 12853 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12854 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12855 SE.getTypeSizeInBits(NewBECount->getType())) 12856 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12857 12858 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12859 12860 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12861 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12862 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12863 dbgs() << "Old: " << *CurBECount << "\n"; 12864 dbgs() << "New: " << *NewBECount << "\n"; 12865 dbgs() << "Delta: " << *Delta << "\n"; 12866 std::abort(); 12867 } 12868 } 12869 12870 // Collect all valid loops currently in LoopInfo. 12871 SmallPtrSet<Loop *, 32> ValidLoops; 12872 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12873 while (!Worklist.empty()) { 12874 Loop *L = Worklist.pop_back_val(); 12875 if (ValidLoops.contains(L)) 12876 continue; 12877 ValidLoops.insert(L); 12878 Worklist.append(L->begin(), L->end()); 12879 } 12880 // Check for SCEV expressions referencing invalid/deleted loops. 12881 for (auto &KV : ValueExprMap) { 12882 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12883 if (!AR) 12884 continue; 12885 assert(ValidLoops.contains(AR->getLoop()) && 12886 "AddRec references invalid loop"); 12887 } 12888 } 12889 12890 bool ScalarEvolution::invalidate( 12891 Function &F, const PreservedAnalyses &PA, 12892 FunctionAnalysisManager::Invalidator &Inv) { 12893 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12894 // of its dependencies is invalidated. 12895 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12896 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12897 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12898 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12899 Inv.invalidate<LoopAnalysis>(F, PA); 12900 } 12901 12902 AnalysisKey ScalarEvolutionAnalysis::Key; 12903 12904 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12905 FunctionAnalysisManager &AM) { 12906 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12907 AM.getResult<AssumptionAnalysis>(F), 12908 AM.getResult<DominatorTreeAnalysis>(F), 12909 AM.getResult<LoopAnalysis>(F)); 12910 } 12911 12912 PreservedAnalyses 12913 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12914 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12915 return PreservedAnalyses::all(); 12916 } 12917 12918 PreservedAnalyses 12919 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12920 // For compatibility with opt's -analyze feature under legacy pass manager 12921 // which was not ported to NPM. This keeps tests using 12922 // update_analyze_test_checks.py working. 12923 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12924 << F.getName() << "':\n"; 12925 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12926 return PreservedAnalyses::all(); 12927 } 12928 12929 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12930 "Scalar Evolution Analysis", false, true) 12931 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12932 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12933 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12934 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12935 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12936 "Scalar Evolution Analysis", false, true) 12937 12938 char ScalarEvolutionWrapperPass::ID = 0; 12939 12940 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12941 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12942 } 12943 12944 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12945 SE.reset(new ScalarEvolution( 12946 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12947 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12948 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12949 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12950 return false; 12951 } 12952 12953 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12954 12955 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12956 SE->print(OS); 12957 } 12958 12959 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12960 if (!VerifySCEV) 12961 return; 12962 12963 SE->verify(); 12964 } 12965 12966 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12967 AU.setPreservesAll(); 12968 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12969 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12970 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12971 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12972 } 12973 12974 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12975 const SCEV *RHS) { 12976 FoldingSetNodeID ID; 12977 assert(LHS->getType() == RHS->getType() && 12978 "Type mismatch between LHS and RHS"); 12979 // Unique this node based on the arguments 12980 ID.AddInteger(SCEVPredicate::P_Equal); 12981 ID.AddPointer(LHS); 12982 ID.AddPointer(RHS); 12983 void *IP = nullptr; 12984 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12985 return S; 12986 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12987 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12988 UniquePreds.InsertNode(Eq, IP); 12989 return Eq; 12990 } 12991 12992 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12993 const SCEVAddRecExpr *AR, 12994 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12995 FoldingSetNodeID ID; 12996 // Unique this node based on the arguments 12997 ID.AddInteger(SCEVPredicate::P_Wrap); 12998 ID.AddPointer(AR); 12999 ID.AddInteger(AddedFlags); 13000 void *IP = nullptr; 13001 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13002 return S; 13003 auto *OF = new (SCEVAllocator) 13004 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13005 UniquePreds.InsertNode(OF, IP); 13006 return OF; 13007 } 13008 13009 namespace { 13010 13011 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13012 public: 13013 13014 /// Rewrites \p S in the context of a loop L and the SCEV predication 13015 /// infrastructure. 13016 /// 13017 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13018 /// equivalences present in \p Pred. 13019 /// 13020 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13021 /// \p NewPreds such that the result will be an AddRecExpr. 13022 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13023 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13024 SCEVUnionPredicate *Pred) { 13025 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13026 return Rewriter.visit(S); 13027 } 13028 13029 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13030 if (Pred) { 13031 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13032 for (auto *Pred : ExprPreds) 13033 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13034 if (IPred->getLHS() == Expr) 13035 return IPred->getRHS(); 13036 } 13037 return convertToAddRecWithPreds(Expr); 13038 } 13039 13040 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13041 const SCEV *Operand = visit(Expr->getOperand()); 13042 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13043 if (AR && AR->getLoop() == L && AR->isAffine()) { 13044 // This couldn't be folded because the operand didn't have the nuw 13045 // flag. Add the nusw flag as an assumption that we could make. 13046 const SCEV *Step = AR->getStepRecurrence(SE); 13047 Type *Ty = Expr->getType(); 13048 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13049 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13050 SE.getSignExtendExpr(Step, Ty), L, 13051 AR->getNoWrapFlags()); 13052 } 13053 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13054 } 13055 13056 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13057 const SCEV *Operand = visit(Expr->getOperand()); 13058 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13059 if (AR && AR->getLoop() == L && AR->isAffine()) { 13060 // This couldn't be folded because the operand didn't have the nsw 13061 // flag. Add the nssw flag as an assumption that we could make. 13062 const SCEV *Step = AR->getStepRecurrence(SE); 13063 Type *Ty = Expr->getType(); 13064 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13065 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13066 SE.getSignExtendExpr(Step, Ty), L, 13067 AR->getNoWrapFlags()); 13068 } 13069 return SE.getSignExtendExpr(Operand, Expr->getType()); 13070 } 13071 13072 private: 13073 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13074 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13075 SCEVUnionPredicate *Pred) 13076 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13077 13078 bool addOverflowAssumption(const SCEVPredicate *P) { 13079 if (!NewPreds) { 13080 // Check if we've already made this assumption. 13081 return Pred && Pred->implies(P); 13082 } 13083 NewPreds->insert(P); 13084 return true; 13085 } 13086 13087 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13088 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13089 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13090 return addOverflowAssumption(A); 13091 } 13092 13093 // If \p Expr represents a PHINode, we try to see if it can be represented 13094 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13095 // to add this predicate as a runtime overflow check, we return the AddRec. 13096 // If \p Expr does not meet these conditions (is not a PHI node, or we 13097 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13098 // return \p Expr. 13099 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13100 if (!isa<PHINode>(Expr->getValue())) 13101 return Expr; 13102 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13103 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13104 if (!PredicatedRewrite) 13105 return Expr; 13106 for (auto *P : PredicatedRewrite->second){ 13107 // Wrap predicates from outer loops are not supported. 13108 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13109 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13110 if (L != AR->getLoop()) 13111 return Expr; 13112 } 13113 if (!addOverflowAssumption(P)) 13114 return Expr; 13115 } 13116 return PredicatedRewrite->first; 13117 } 13118 13119 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13120 SCEVUnionPredicate *Pred; 13121 const Loop *L; 13122 }; 13123 13124 } // end anonymous namespace 13125 13126 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13127 SCEVUnionPredicate &Preds) { 13128 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13129 } 13130 13131 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13132 const SCEV *S, const Loop *L, 13133 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13134 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13135 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13136 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13137 13138 if (!AddRec) 13139 return nullptr; 13140 13141 // Since the transformation was successful, we can now transfer the SCEV 13142 // predicates. 13143 for (auto *P : TransformPreds) 13144 Preds.insert(P); 13145 13146 return AddRec; 13147 } 13148 13149 /// SCEV predicates 13150 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13151 SCEVPredicateKind Kind) 13152 : FastID(ID), Kind(Kind) {} 13153 13154 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13155 const SCEV *LHS, const SCEV *RHS) 13156 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13157 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13158 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13159 } 13160 13161 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13162 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13163 13164 if (!Op) 13165 return false; 13166 13167 return Op->LHS == LHS && Op->RHS == RHS; 13168 } 13169 13170 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13171 13172 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13173 13174 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13175 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13176 } 13177 13178 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13179 const SCEVAddRecExpr *AR, 13180 IncrementWrapFlags Flags) 13181 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13182 13183 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13184 13185 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13186 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13187 13188 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13189 } 13190 13191 bool SCEVWrapPredicate::isAlwaysTrue() const { 13192 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13193 IncrementWrapFlags IFlags = Flags; 13194 13195 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13196 IFlags = clearFlags(IFlags, IncrementNSSW); 13197 13198 return IFlags == IncrementAnyWrap; 13199 } 13200 13201 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13202 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13203 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13204 OS << "<nusw>"; 13205 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13206 OS << "<nssw>"; 13207 OS << "\n"; 13208 } 13209 13210 SCEVWrapPredicate::IncrementWrapFlags 13211 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13212 ScalarEvolution &SE) { 13213 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13214 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13215 13216 // We can safely transfer the NSW flag as NSSW. 13217 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13218 ImpliedFlags = IncrementNSSW; 13219 13220 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13221 // If the increment is positive, the SCEV NUW flag will also imply the 13222 // WrapPredicate NUSW flag. 13223 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13224 if (Step->getValue()->getValue().isNonNegative()) 13225 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13226 } 13227 13228 return ImpliedFlags; 13229 } 13230 13231 /// Union predicates don't get cached so create a dummy set ID for it. 13232 SCEVUnionPredicate::SCEVUnionPredicate() 13233 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13234 13235 bool SCEVUnionPredicate::isAlwaysTrue() const { 13236 return all_of(Preds, 13237 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13238 } 13239 13240 ArrayRef<const SCEVPredicate *> 13241 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13242 auto I = SCEVToPreds.find(Expr); 13243 if (I == SCEVToPreds.end()) 13244 return ArrayRef<const SCEVPredicate *>(); 13245 return I->second; 13246 } 13247 13248 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13249 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13250 return all_of(Set->Preds, 13251 [this](const SCEVPredicate *I) { return this->implies(I); }); 13252 13253 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13254 if (ScevPredsIt == SCEVToPreds.end()) 13255 return false; 13256 auto &SCEVPreds = ScevPredsIt->second; 13257 13258 return any_of(SCEVPreds, 13259 [N](const SCEVPredicate *I) { return I->implies(N); }); 13260 } 13261 13262 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13263 13264 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13265 for (auto Pred : Preds) 13266 Pred->print(OS, Depth); 13267 } 13268 13269 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13270 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13271 for (auto Pred : Set->Preds) 13272 add(Pred); 13273 return; 13274 } 13275 13276 if (implies(N)) 13277 return; 13278 13279 const SCEV *Key = N->getExpr(); 13280 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13281 " associated expression!"); 13282 13283 SCEVToPreds[Key].push_back(N); 13284 Preds.push_back(N); 13285 } 13286 13287 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13288 Loop &L) 13289 : SE(SE), L(L) {} 13290 13291 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13292 const SCEV *Expr = SE.getSCEV(V); 13293 RewriteEntry &Entry = RewriteMap[Expr]; 13294 13295 // If we already have an entry and the version matches, return it. 13296 if (Entry.second && Generation == Entry.first) 13297 return Entry.second; 13298 13299 // We found an entry but it's stale. Rewrite the stale entry 13300 // according to the current predicate. 13301 if (Entry.second) 13302 Expr = Entry.second; 13303 13304 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13305 Entry = {Generation, NewSCEV}; 13306 13307 return NewSCEV; 13308 } 13309 13310 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13311 if (!BackedgeCount) { 13312 SCEVUnionPredicate BackedgePred; 13313 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13314 addPredicate(BackedgePred); 13315 } 13316 return BackedgeCount; 13317 } 13318 13319 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13320 if (Preds.implies(&Pred)) 13321 return; 13322 Preds.add(&Pred); 13323 updateGeneration(); 13324 } 13325 13326 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13327 return Preds; 13328 } 13329 13330 void PredicatedScalarEvolution::updateGeneration() { 13331 // If the generation number wrapped recompute everything. 13332 if (++Generation == 0) { 13333 for (auto &II : RewriteMap) { 13334 const SCEV *Rewritten = II.second.second; 13335 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13336 } 13337 } 13338 } 13339 13340 void PredicatedScalarEvolution::setNoOverflow( 13341 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13342 const SCEV *Expr = getSCEV(V); 13343 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13344 13345 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13346 13347 // Clear the statically implied flags. 13348 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13349 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13350 13351 auto II = FlagsMap.insert({V, Flags}); 13352 if (!II.second) 13353 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13354 } 13355 13356 bool PredicatedScalarEvolution::hasNoOverflow( 13357 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13358 const SCEV *Expr = getSCEV(V); 13359 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13360 13361 Flags = SCEVWrapPredicate::clearFlags( 13362 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13363 13364 auto II = FlagsMap.find(V); 13365 13366 if (II != FlagsMap.end()) 13367 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13368 13369 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13370 } 13371 13372 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13373 const SCEV *Expr = this->getSCEV(V); 13374 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13375 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13376 13377 if (!New) 13378 return nullptr; 13379 13380 for (auto *P : NewPreds) 13381 Preds.add(P); 13382 13383 updateGeneration(); 13384 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13385 return New; 13386 } 13387 13388 PredicatedScalarEvolution::PredicatedScalarEvolution( 13389 const PredicatedScalarEvolution &Init) 13390 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13391 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13392 for (auto I : Init.FlagsMap) 13393 FlagsMap.insert(I); 13394 } 13395 13396 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13397 // For each block. 13398 for (auto *BB : L.getBlocks()) 13399 for (auto &I : *BB) { 13400 if (!SE.isSCEVable(I.getType())) 13401 continue; 13402 13403 auto *Expr = SE.getSCEV(&I); 13404 auto II = RewriteMap.find(Expr); 13405 13406 if (II == RewriteMap.end()) 13407 continue; 13408 13409 // Don't print things that are not interesting. 13410 if (II->second.second == Expr) 13411 continue; 13412 13413 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13414 OS.indent(Depth + 2) << *Expr << "\n"; 13415 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13416 } 13417 } 13418 13419 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13420 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13421 // for URem with constant power-of-2 second operands. 13422 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13423 // 4, A / B becomes X / 8). 13424 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13425 const SCEV *&RHS) { 13426 // Try to match 'zext (trunc A to iB) to iY', which is used 13427 // for URem with constant power-of-2 second operands. Make sure the size of 13428 // the operand A matches the size of the whole expressions. 13429 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13430 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13431 LHS = Trunc->getOperand(); 13432 // Bail out if the type of the LHS is larger than the type of the 13433 // expression for now. 13434 if (getTypeSizeInBits(LHS->getType()) > 13435 getTypeSizeInBits(Expr->getType())) 13436 return false; 13437 if (LHS->getType() != Expr->getType()) 13438 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13439 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13440 << getTypeSizeInBits(Trunc->getType())); 13441 return true; 13442 } 13443 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13444 if (Add == nullptr || Add->getNumOperands() != 2) 13445 return false; 13446 13447 const SCEV *A = Add->getOperand(1); 13448 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13449 13450 if (Mul == nullptr) 13451 return false; 13452 13453 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13454 // (SomeExpr + (-(SomeExpr / B) * B)). 13455 if (Expr == getURemExpr(A, B)) { 13456 LHS = A; 13457 RHS = B; 13458 return true; 13459 } 13460 return false; 13461 }; 13462 13463 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13464 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13465 return MatchURemWithDivisor(Mul->getOperand(1)) || 13466 MatchURemWithDivisor(Mul->getOperand(2)); 13467 13468 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13469 if (Mul->getNumOperands() == 2) 13470 return MatchURemWithDivisor(Mul->getOperand(1)) || 13471 MatchURemWithDivisor(Mul->getOperand(0)) || 13472 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13473 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13474 return false; 13475 } 13476 13477 const SCEV * 13478 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13479 SmallVector<BasicBlock*, 16> ExitingBlocks; 13480 L->getExitingBlocks(ExitingBlocks); 13481 13482 // Form an expression for the maximum exit count possible for this loop. We 13483 // merge the max and exact information to approximate a version of 13484 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13485 SmallVector<const SCEV*, 4> ExitCounts; 13486 for (BasicBlock *ExitingBB : ExitingBlocks) { 13487 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13488 if (isa<SCEVCouldNotCompute>(ExitCount)) 13489 ExitCount = getExitCount(L, ExitingBB, 13490 ScalarEvolution::ConstantMaximum); 13491 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13492 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13493 "We should only have known counts for exiting blocks that " 13494 "dominate latch!"); 13495 ExitCounts.push_back(ExitCount); 13496 } 13497 } 13498 if (ExitCounts.empty()) 13499 return getCouldNotCompute(); 13500 return getUMinFromMismatchedTypes(ExitCounts); 13501 } 13502 13503 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13504 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13505 /// we cannot guarantee that the replacement is loop invariant in the loop of 13506 /// the AddRec. 13507 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13508 ValueToSCEVMapTy ⤅ 13509 13510 public: 13511 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13512 : SCEVRewriteVisitor(SE), Map(M) {} 13513 13514 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13515 13516 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13517 auto I = Map.find(Expr->getValue()); 13518 if (I == Map.end()) 13519 return Expr; 13520 return I->second; 13521 } 13522 }; 13523 13524 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13525 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13526 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13527 // WARNING: It is generally unsound to apply any wrap flags to the proposed 13528 // replacement SCEV which isn't directly implied by the structure of that 13529 // SCEV. In particular, using contextual facts to imply flags is *NOT* 13530 // legal. See the scoping rules for flags in the header to understand why. 13531 13532 // If we have LHS == 0, check if LHS is computing a property of some unknown 13533 // SCEV %v which we can rewrite %v to express explicitly. 13534 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13535 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13536 RHSC->getValue()->isNullValue()) { 13537 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13538 // explicitly express that. 13539 const SCEV *URemLHS = nullptr; 13540 const SCEV *URemRHS = nullptr; 13541 if (matchURem(LHS, URemLHS, URemRHS)) { 13542 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13543 Value *V = LHSUnknown->getValue(); 13544 RewriteMap[V] = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 13545 return; 13546 } 13547 } 13548 } 13549 13550 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13551 std::swap(LHS, RHS); 13552 Predicate = CmpInst::getSwappedPredicate(Predicate); 13553 } 13554 13555 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13556 // create this form when combining two checks of the form (X u< C2 + C1) and 13557 // (X >=u C1). 13558 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13559 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13560 if (!AddExpr || AddExpr->getNumOperands() != 2) 13561 return false; 13562 13563 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13564 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13565 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13566 if (!C1 || !C2 || !LHSUnknown) 13567 return false; 13568 13569 auto ExactRegion = 13570 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13571 .sub(C1->getAPInt()); 13572 13573 // Bail out, unless we have a non-wrapping, monotonic range. 13574 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13575 return false; 13576 auto I = RewriteMap.find(LHSUnknown->getValue()); 13577 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13578 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13579 getConstant(ExactRegion.getUnsignedMin()), 13580 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13581 return true; 13582 }; 13583 if (MatchRangeCheckIdiom()) 13584 return; 13585 13586 // For now, limit to conditions that provide information about unknown 13587 // expressions. RHS also cannot contain add recurrences. 13588 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13589 if (!LHSUnknown || containsAddRecurrence(RHS)) 13590 return; 13591 13592 // Check whether LHS has already been rewritten. In that case we want to 13593 // chain further rewrites onto the already rewritten value. 13594 auto I = RewriteMap.find(LHSUnknown->getValue()); 13595 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13596 const SCEV *RewrittenRHS = nullptr; 13597 switch (Predicate) { 13598 case CmpInst::ICMP_ULT: 13599 RewrittenRHS = 13600 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13601 break; 13602 case CmpInst::ICMP_SLT: 13603 RewrittenRHS = 13604 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13605 break; 13606 case CmpInst::ICMP_ULE: 13607 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13608 break; 13609 case CmpInst::ICMP_SLE: 13610 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13611 break; 13612 case CmpInst::ICMP_UGT: 13613 RewrittenRHS = 13614 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13615 break; 13616 case CmpInst::ICMP_SGT: 13617 RewrittenRHS = 13618 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13619 break; 13620 case CmpInst::ICMP_UGE: 13621 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13622 break; 13623 case CmpInst::ICMP_SGE: 13624 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13625 break; 13626 case CmpInst::ICMP_EQ: 13627 if (isa<SCEVConstant>(RHS)) 13628 RewrittenRHS = RHS; 13629 break; 13630 case CmpInst::ICMP_NE: 13631 if (isa<SCEVConstant>(RHS) && 13632 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13633 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13634 break; 13635 default: 13636 break; 13637 } 13638 13639 if (RewrittenRHS) 13640 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13641 }; 13642 // Starting at the loop predecessor, climb up the predecessor chain, as long 13643 // as there are predecessors that can be found that have unique successors 13644 // leading to the original header. 13645 // TODO: share this logic with isLoopEntryGuardedByCond. 13646 ValueToSCEVMapTy RewriteMap; 13647 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13648 L->getLoopPredecessor(), L->getHeader()); 13649 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13650 13651 const BranchInst *LoopEntryPredicate = 13652 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13653 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13654 continue; 13655 13656 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13657 SmallVector<Value *, 8> Worklist; 13658 SmallPtrSet<Value *, 8> Visited; 13659 Worklist.push_back(LoopEntryPredicate->getCondition()); 13660 while (!Worklist.empty()) { 13661 Value *Cond = Worklist.pop_back_val(); 13662 if (!Visited.insert(Cond).second) 13663 continue; 13664 13665 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13666 auto Predicate = 13667 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13668 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13669 getSCEV(Cmp->getOperand(1)), RewriteMap); 13670 continue; 13671 } 13672 13673 Value *L, *R; 13674 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13675 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13676 Worklist.push_back(L); 13677 Worklist.push_back(R); 13678 } 13679 } 13680 } 13681 13682 // Also collect information from assumptions dominating the loop. 13683 for (auto &AssumeVH : AC.assumptions()) { 13684 if (!AssumeVH) 13685 continue; 13686 auto *AssumeI = cast<CallInst>(AssumeVH); 13687 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13688 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13689 continue; 13690 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13691 getSCEV(Cmp->getOperand(1)), RewriteMap); 13692 } 13693 13694 if (RewriteMap.empty()) 13695 return Expr; 13696 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13697 return Rewriter.visit(Expr); 13698 } 13699