1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumArrayLenItCounts, 143 "Number of trip counts computed with array length"); 144 STATISTIC(NumTripCountsComputed, 145 "Number of loops with predictable loop counts"); 146 STATISTIC(NumTripCountsNotComputed, 147 "Number of loops without predictable loop counts"); 148 STATISTIC(NumBruteForceTripCountsComputed, 149 "Number of loops with trip counts computed by force"); 150 151 static cl::opt<unsigned> 152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 153 cl::ZeroOrMore, 154 cl::desc("Maximum number of iterations SCEV will " 155 "symbolically execute a constant " 156 "derived loop"), 157 cl::init(100)); 158 159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 160 static cl::opt<bool> VerifySCEV( 161 "verify-scev", cl::Hidden, 162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 163 static cl::opt<bool> VerifySCEVStrict( 164 "verify-scev-strict", cl::Hidden, 165 cl::desc("Enable stricter verification with -verify-scev is passed")); 166 static cl::opt<bool> 167 VerifySCEVMap("verify-scev-maps", cl::Hidden, 168 cl::desc("Verify no dangling value in ScalarEvolution's " 169 "ExprValueMap (slow)")); 170 171 static cl::opt<bool> VerifyIR( 172 "scev-verify-ir", cl::Hidden, 173 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 174 cl::init(false)); 175 176 static cl::opt<unsigned> MulOpsInlineThreshold( 177 "scev-mulops-inline-threshold", cl::Hidden, 178 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 179 cl::init(32)); 180 181 static cl::opt<unsigned> AddOpsInlineThreshold( 182 "scev-addops-inline-threshold", cl::Hidden, 183 cl::desc("Threshold for inlining addition operands into a SCEV"), 184 cl::init(500)); 185 186 static cl::opt<unsigned> MaxSCEVCompareDepth( 187 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 188 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 189 cl::init(32)); 190 191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 192 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 193 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 194 cl::init(2)); 195 196 static cl::opt<unsigned> MaxValueCompareDepth( 197 "scalar-evolution-max-value-compare-depth", cl::Hidden, 198 cl::desc("Maximum depth of recursive value complexity comparisons"), 199 cl::init(2)); 200 201 static cl::opt<unsigned> 202 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 203 cl::desc("Maximum depth of recursive arithmetics"), 204 cl::init(32)); 205 206 static cl::opt<unsigned> MaxConstantEvolvingDepth( 207 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 208 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 209 210 static cl::opt<unsigned> 211 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 212 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 213 cl::init(8)); 214 215 static cl::opt<unsigned> 216 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 217 cl::desc("Max coefficients in AddRec during evolving"), 218 cl::init(8)); 219 220 static cl::opt<unsigned> 221 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 222 cl::desc("Size of the expression which is considered huge"), 223 cl::init(4096)); 224 225 static cl::opt<bool> 226 ClassifyExpressions("scalar-evolution-classify-expressions", 227 cl::Hidden, cl::init(true), 228 cl::desc("When printing analysis, include information on every instruction")); 229 230 static cl::opt<bool> UseExpensiveRangeSharpening( 231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 232 cl::init(false), 233 cl::desc("Use more powerful methods of sharpening expression ranges. May " 234 "be costly in terms of compile time")); 235 236 //===----------------------------------------------------------------------===// 237 // SCEV class definitions 238 //===----------------------------------------------------------------------===// 239 240 //===----------------------------------------------------------------------===// 241 // Implementation of the SCEV class. 242 // 243 244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 245 LLVM_DUMP_METHOD void SCEV::dump() const { 246 print(dbgs()); 247 dbgs() << '\n'; 248 } 249 #endif 250 251 void SCEV::print(raw_ostream &OS) const { 252 switch (getSCEVType()) { 253 case scConstant: 254 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 255 return; 256 case scPtrToInt: { 257 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 258 const SCEV *Op = PtrToInt->getOperand(); 259 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 260 << *PtrToInt->getType() << ")"; 261 return; 262 } 263 case scTruncate: { 264 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 265 const SCEV *Op = Trunc->getOperand(); 266 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 267 << *Trunc->getType() << ")"; 268 return; 269 } 270 case scZeroExtend: { 271 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 272 const SCEV *Op = ZExt->getOperand(); 273 OS << "(zext " << *Op->getType() << " " << *Op << " to " 274 << *ZExt->getType() << ")"; 275 return; 276 } 277 case scSignExtend: { 278 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 279 const SCEV *Op = SExt->getOperand(); 280 OS << "(sext " << *Op->getType() << " " << *Op << " to " 281 << *SExt->getType() << ")"; 282 return; 283 } 284 case scAddRecExpr: { 285 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 286 OS << "{" << *AR->getOperand(0); 287 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 288 OS << ",+," << *AR->getOperand(i); 289 OS << "}<"; 290 if (AR->hasNoUnsignedWrap()) 291 OS << "nuw><"; 292 if (AR->hasNoSignedWrap()) 293 OS << "nsw><"; 294 if (AR->hasNoSelfWrap() && 295 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 296 OS << "nw><"; 297 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 298 OS << ">"; 299 return; 300 } 301 case scAddExpr: 302 case scMulExpr: 303 case scUMaxExpr: 304 case scSMaxExpr: 305 case scUMinExpr: 306 case scSMinExpr: { 307 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 308 const char *OpStr = nullptr; 309 switch (NAry->getSCEVType()) { 310 case scAddExpr: OpStr = " + "; break; 311 case scMulExpr: OpStr = " * "; break; 312 case scUMaxExpr: OpStr = " umax "; break; 313 case scSMaxExpr: OpStr = " smax "; break; 314 case scUMinExpr: 315 OpStr = " umin "; 316 break; 317 case scSMinExpr: 318 OpStr = " smin "; 319 break; 320 default: 321 llvm_unreachable("There are no other nary expression types."); 322 } 323 OS << "("; 324 ListSeparator LS(OpStr); 325 for (const SCEV *Op : NAry->operands()) 326 OS << LS << *Op; 327 OS << ")"; 328 switch (NAry->getSCEVType()) { 329 case scAddExpr: 330 case scMulExpr: 331 if (NAry->hasNoUnsignedWrap()) 332 OS << "<nuw>"; 333 if (NAry->hasNoSignedWrap()) 334 OS << "<nsw>"; 335 break; 336 default: 337 // Nothing to print for other nary expressions. 338 break; 339 } 340 return; 341 } 342 case scUDivExpr: { 343 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 344 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 345 return; 346 } 347 case scUnknown: { 348 const SCEVUnknown *U = cast<SCEVUnknown>(this); 349 Type *AllocTy; 350 if (U->isSizeOf(AllocTy)) { 351 OS << "sizeof(" << *AllocTy << ")"; 352 return; 353 } 354 if (U->isAlignOf(AllocTy)) { 355 OS << "alignof(" << *AllocTy << ")"; 356 return; 357 } 358 359 Type *CTy; 360 Constant *FieldNo; 361 if (U->isOffsetOf(CTy, FieldNo)) { 362 OS << "offsetof(" << *CTy << ", "; 363 FieldNo->printAsOperand(OS, false); 364 OS << ")"; 365 return; 366 } 367 368 // Otherwise just print it normally. 369 U->getValue()->printAsOperand(OS, false); 370 return; 371 } 372 case scCouldNotCompute: 373 OS << "***COULDNOTCOMPUTE***"; 374 return; 375 } 376 llvm_unreachable("Unknown SCEV kind!"); 377 } 378 379 Type *SCEV::getType() const { 380 switch (getSCEVType()) { 381 case scConstant: 382 return cast<SCEVConstant>(this)->getType(); 383 case scPtrToInt: 384 case scTruncate: 385 case scZeroExtend: 386 case scSignExtend: 387 return cast<SCEVCastExpr>(this)->getType(); 388 case scAddRecExpr: 389 return cast<SCEVAddRecExpr>(this)->getType(); 390 case scMulExpr: 391 return cast<SCEVMulExpr>(this)->getType(); 392 case scUMaxExpr: 393 case scSMaxExpr: 394 case scUMinExpr: 395 case scSMinExpr: 396 return cast<SCEVMinMaxExpr>(this)->getType(); 397 case scAddExpr: 398 return cast<SCEVAddExpr>(this)->getType(); 399 case scUDivExpr: 400 return cast<SCEVUDivExpr>(this)->getType(); 401 case scUnknown: 402 return cast<SCEVUnknown>(this)->getType(); 403 case scCouldNotCompute: 404 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 405 } 406 llvm_unreachable("Unknown SCEV kind!"); 407 } 408 409 bool SCEV::isZero() const { 410 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 411 return SC->getValue()->isZero(); 412 return false; 413 } 414 415 bool SCEV::isOne() const { 416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 417 return SC->getValue()->isOne(); 418 return false; 419 } 420 421 bool SCEV::isAllOnesValue() const { 422 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 423 return SC->getValue()->isMinusOne(); 424 return false; 425 } 426 427 bool SCEV::isNonConstantNegative() const { 428 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 429 if (!Mul) return false; 430 431 // If there is a constant factor, it will be first. 432 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 433 if (!SC) return false; 434 435 // Return true if the value is negative, this matches things like (-42 * V). 436 return SC->getAPInt().isNegative(); 437 } 438 439 SCEVCouldNotCompute::SCEVCouldNotCompute() : 440 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 441 442 bool SCEVCouldNotCompute::classof(const SCEV *S) { 443 return S->getSCEVType() == scCouldNotCompute; 444 } 445 446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 447 FoldingSetNodeID ID; 448 ID.AddInteger(scConstant); 449 ID.AddPointer(V); 450 void *IP = nullptr; 451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 452 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 453 UniqueSCEVs.InsertNode(S, IP); 454 return S; 455 } 456 457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 458 return getConstant(ConstantInt::get(getContext(), Val)); 459 } 460 461 const SCEV * 462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 463 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 464 return getConstant(ConstantInt::get(ITy, V, isSigned)); 465 } 466 467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 468 const SCEV *op, Type *ty) 469 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 470 Operands[0] = op; 471 } 472 473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 474 Type *ITy) 475 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 476 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 477 "Must be a non-bit-width-changing pointer-to-integer cast!"); 478 } 479 480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 481 SCEVTypes SCEVTy, const SCEV *op, 482 Type *ty) 483 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 484 485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 486 Type *ty) 487 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 488 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 489 "Cannot truncate non-integer value!"); 490 } 491 492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 493 const SCEV *op, Type *ty) 494 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 495 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 496 "Cannot zero extend non-integer value!"); 497 } 498 499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 500 const SCEV *op, Type *ty) 501 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 502 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 503 "Cannot sign extend non-integer value!"); 504 } 505 506 void SCEVUnknown::deleted() { 507 // Clear this SCEVUnknown from various maps. 508 SE->forgetMemoizedResults(this); 509 510 // Remove this SCEVUnknown from the uniquing map. 511 SE->UniqueSCEVs.RemoveNode(this); 512 513 // Release the value. 514 setValPtr(nullptr); 515 } 516 517 void SCEVUnknown::allUsesReplacedWith(Value *New) { 518 // Remove this SCEVUnknown from the uniquing map. 519 SE->UniqueSCEVs.RemoveNode(this); 520 521 // Update this SCEVUnknown to point to the new value. This is needed 522 // because there may still be outstanding SCEVs which still point to 523 // this SCEVUnknown. 524 setValPtr(New); 525 } 526 527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 528 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 529 if (VCE->getOpcode() == Instruction::PtrToInt) 530 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 531 if (CE->getOpcode() == Instruction::GetElementPtr && 532 CE->getOperand(0)->isNullValue() && 533 CE->getNumOperands() == 2) 534 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 535 if (CI->isOne()) { 536 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 537 ->getElementType(); 538 return true; 539 } 540 541 return false; 542 } 543 544 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 545 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 546 if (VCE->getOpcode() == Instruction::PtrToInt) 547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 548 if (CE->getOpcode() == Instruction::GetElementPtr && 549 CE->getOperand(0)->isNullValue()) { 550 Type *Ty = 551 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 552 if (StructType *STy = dyn_cast<StructType>(Ty)) 553 if (!STy->isPacked() && 554 CE->getNumOperands() == 3 && 555 CE->getOperand(1)->isNullValue()) { 556 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 557 if (CI->isOne() && 558 STy->getNumElements() == 2 && 559 STy->getElementType(0)->isIntegerTy(1)) { 560 AllocTy = STy->getElementType(1); 561 return true; 562 } 563 } 564 } 565 566 return false; 567 } 568 569 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 570 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 571 if (VCE->getOpcode() == Instruction::PtrToInt) 572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 573 if (CE->getOpcode() == Instruction::GetElementPtr && 574 CE->getNumOperands() == 3 && 575 CE->getOperand(0)->isNullValue() && 576 CE->getOperand(1)->isNullValue()) { 577 Type *Ty = 578 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 579 // Ignore vector types here so that ScalarEvolutionExpander doesn't 580 // emit getelementptrs that index into vectors. 581 if (Ty->isStructTy() || Ty->isArrayTy()) { 582 CTy = Ty; 583 FieldNo = CE->getOperand(2); 584 return true; 585 } 586 } 587 588 return false; 589 } 590 591 //===----------------------------------------------------------------------===// 592 // SCEV Utilities 593 //===----------------------------------------------------------------------===// 594 595 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 596 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 597 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 598 /// have been previously deemed to be "equally complex" by this routine. It is 599 /// intended to avoid exponential time complexity in cases like: 600 /// 601 /// %a = f(%x, %y) 602 /// %b = f(%a, %a) 603 /// %c = f(%b, %b) 604 /// 605 /// %d = f(%x, %y) 606 /// %e = f(%d, %d) 607 /// %f = f(%e, %e) 608 /// 609 /// CompareValueComplexity(%f, %c) 610 /// 611 /// Since we do not continue running this routine on expression trees once we 612 /// have seen unequal values, there is no need to track them in the cache. 613 static int 614 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 615 const LoopInfo *const LI, Value *LV, Value *RV, 616 unsigned Depth) { 617 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 618 return 0; 619 620 // Order pointer values after integer values. This helps SCEVExpander form 621 // GEPs. 622 bool LIsPointer = LV->getType()->isPointerTy(), 623 RIsPointer = RV->getType()->isPointerTy(); 624 if (LIsPointer != RIsPointer) 625 return (int)LIsPointer - (int)RIsPointer; 626 627 // Compare getValueID values. 628 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 629 if (LID != RID) 630 return (int)LID - (int)RID; 631 632 // Sort arguments by their position. 633 if (const auto *LA = dyn_cast<Argument>(LV)) { 634 const auto *RA = cast<Argument>(RV); 635 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 636 return (int)LArgNo - (int)RArgNo; 637 } 638 639 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 640 const auto *RGV = cast<GlobalValue>(RV); 641 642 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 643 auto LT = GV->getLinkage(); 644 return !(GlobalValue::isPrivateLinkage(LT) || 645 GlobalValue::isInternalLinkage(LT)); 646 }; 647 648 // Use the names to distinguish the two values, but only if the 649 // names are semantically important. 650 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 651 return LGV->getName().compare(RGV->getName()); 652 } 653 654 // For instructions, compare their loop depth, and their operand count. This 655 // is pretty loose. 656 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 657 const auto *RInst = cast<Instruction>(RV); 658 659 // Compare loop depths. 660 const BasicBlock *LParent = LInst->getParent(), 661 *RParent = RInst->getParent(); 662 if (LParent != RParent) { 663 unsigned LDepth = LI->getLoopDepth(LParent), 664 RDepth = LI->getLoopDepth(RParent); 665 if (LDepth != RDepth) 666 return (int)LDepth - (int)RDepth; 667 } 668 669 // Compare the number of operands. 670 unsigned LNumOps = LInst->getNumOperands(), 671 RNumOps = RInst->getNumOperands(); 672 if (LNumOps != RNumOps) 673 return (int)LNumOps - (int)RNumOps; 674 675 for (unsigned Idx : seq(0u, LNumOps)) { 676 int Result = 677 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 678 RInst->getOperand(Idx), Depth + 1); 679 if (Result != 0) 680 return Result; 681 } 682 } 683 684 EqCacheValue.unionSets(LV, RV); 685 return 0; 686 } 687 688 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 689 // than RHS, respectively. A three-way result allows recursive comparisons to be 690 // more efficient. 691 // If the max analysis depth was reached, return None, assuming we do not know 692 // if they are equivalent for sure. 693 static Optional<int> 694 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 695 EquivalenceClasses<const Value *> &EqCacheValue, 696 const LoopInfo *const LI, const SCEV *LHS, 697 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 698 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 699 if (LHS == RHS) 700 return 0; 701 702 // Primarily, sort the SCEVs by their getSCEVType(). 703 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 704 if (LType != RType) 705 return (int)LType - (int)RType; 706 707 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 708 return 0; 709 710 if (Depth > MaxSCEVCompareDepth) 711 return None; 712 713 // Aside from the getSCEVType() ordering, the particular ordering 714 // isn't very important except that it's beneficial to be consistent, 715 // so that (a + b) and (b + a) don't end up as different expressions. 716 switch (LType) { 717 case scUnknown: { 718 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 719 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 720 721 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 722 RU->getValue(), Depth + 1); 723 if (X == 0) 724 EqCacheSCEV.unionSets(LHS, RHS); 725 return X; 726 } 727 728 case scConstant: { 729 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 730 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 731 732 // Compare constant values. 733 const APInt &LA = LC->getAPInt(); 734 const APInt &RA = RC->getAPInt(); 735 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 736 if (LBitWidth != RBitWidth) 737 return (int)LBitWidth - (int)RBitWidth; 738 return LA.ult(RA) ? -1 : 1; 739 } 740 741 case scAddRecExpr: { 742 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 743 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 744 745 // There is always a dominance between two recs that are used by one SCEV, 746 // so we can safely sort recs by loop header dominance. We require such 747 // order in getAddExpr. 748 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 749 if (LLoop != RLoop) { 750 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 751 assert(LHead != RHead && "Two loops share the same header?"); 752 if (DT.dominates(LHead, RHead)) 753 return 1; 754 else 755 assert(DT.dominates(RHead, LHead) && 756 "No dominance between recurrences used by one SCEV?"); 757 return -1; 758 } 759 760 // Addrec complexity grows with operand count. 761 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 762 if (LNumOps != RNumOps) 763 return (int)LNumOps - (int)RNumOps; 764 765 // Lexicographically compare. 766 for (unsigned i = 0; i != LNumOps; ++i) { 767 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 768 LA->getOperand(i), RA->getOperand(i), DT, 769 Depth + 1); 770 if (X != 0) 771 return X; 772 } 773 EqCacheSCEV.unionSets(LHS, RHS); 774 return 0; 775 } 776 777 case scAddExpr: 778 case scMulExpr: 779 case scSMaxExpr: 780 case scUMaxExpr: 781 case scSMinExpr: 782 case scUMinExpr: { 783 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 784 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 785 786 // Lexicographically compare n-ary expressions. 787 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 788 if (LNumOps != RNumOps) 789 return (int)LNumOps - (int)RNumOps; 790 791 for (unsigned i = 0; i != LNumOps; ++i) { 792 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 793 LC->getOperand(i), RC->getOperand(i), DT, 794 Depth + 1); 795 if (X != 0) 796 return X; 797 } 798 EqCacheSCEV.unionSets(LHS, RHS); 799 return 0; 800 } 801 802 case scUDivExpr: { 803 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 804 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 805 806 // Lexicographically compare udiv expressions. 807 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 808 RC->getLHS(), DT, Depth + 1); 809 if (X != 0) 810 return X; 811 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 812 RC->getRHS(), DT, Depth + 1); 813 if (X == 0) 814 EqCacheSCEV.unionSets(LHS, RHS); 815 return X; 816 } 817 818 case scPtrToInt: 819 case scTruncate: 820 case scZeroExtend: 821 case scSignExtend: { 822 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 823 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 824 825 // Compare cast expressions by operand. 826 auto X = 827 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 828 RC->getOperand(), DT, Depth + 1); 829 if (X == 0) 830 EqCacheSCEV.unionSets(LHS, RHS); 831 return X; 832 } 833 834 case scCouldNotCompute: 835 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 836 } 837 llvm_unreachable("Unknown SCEV kind!"); 838 } 839 840 /// Given a list of SCEV objects, order them by their complexity, and group 841 /// objects of the same complexity together by value. When this routine is 842 /// finished, we know that any duplicates in the vector are consecutive and that 843 /// complexity is monotonically increasing. 844 /// 845 /// Note that we go take special precautions to ensure that we get deterministic 846 /// results from this routine. In other words, we don't want the results of 847 /// this to depend on where the addresses of various SCEV objects happened to 848 /// land in memory. 849 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 850 LoopInfo *LI, DominatorTree &DT) { 851 if (Ops.size() < 2) return; // Noop 852 853 EquivalenceClasses<const SCEV *> EqCacheSCEV; 854 EquivalenceClasses<const Value *> EqCacheValue; 855 856 // Whether LHS has provably less complexity than RHS. 857 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 858 auto Complexity = 859 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 860 return Complexity && *Complexity < 0; 861 }; 862 if (Ops.size() == 2) { 863 // This is the common case, which also happens to be trivially simple. 864 // Special case it. 865 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 866 if (IsLessComplex(RHS, LHS)) 867 std::swap(LHS, RHS); 868 return; 869 } 870 871 // Do the rough sort by complexity. 872 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 873 return IsLessComplex(LHS, RHS); 874 }); 875 876 // Now that we are sorted by complexity, group elements of the same 877 // complexity. Note that this is, at worst, N^2, but the vector is likely to 878 // be extremely short in practice. Note that we take this approach because we 879 // do not want to depend on the addresses of the objects we are grouping. 880 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 881 const SCEV *S = Ops[i]; 882 unsigned Complexity = S->getSCEVType(); 883 884 // If there are any objects of the same complexity and same value as this 885 // one, group them. 886 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 887 if (Ops[j] == S) { // Found a duplicate. 888 // Move it to immediately after i'th element. 889 std::swap(Ops[i+1], Ops[j]); 890 ++i; // no need to rescan it. 891 if (i == e-2) return; // Done! 892 } 893 } 894 } 895 } 896 897 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 898 /// least HugeExprThreshold nodes). 899 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 900 return any_of(Ops, [](const SCEV *S) { 901 return S->getExpressionSize() >= HugeExprThreshold; 902 }); 903 } 904 905 //===----------------------------------------------------------------------===// 906 // Simple SCEV method implementations 907 //===----------------------------------------------------------------------===// 908 909 /// Compute BC(It, K). The result has width W. Assume, K > 0. 910 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 911 ScalarEvolution &SE, 912 Type *ResultTy) { 913 // Handle the simplest case efficiently. 914 if (K == 1) 915 return SE.getTruncateOrZeroExtend(It, ResultTy); 916 917 // We are using the following formula for BC(It, K): 918 // 919 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 920 // 921 // Suppose, W is the bitwidth of the return value. We must be prepared for 922 // overflow. Hence, we must assure that the result of our computation is 923 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 924 // safe in modular arithmetic. 925 // 926 // However, this code doesn't use exactly that formula; the formula it uses 927 // is something like the following, where T is the number of factors of 2 in 928 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 929 // exponentiation: 930 // 931 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 932 // 933 // This formula is trivially equivalent to the previous formula. However, 934 // this formula can be implemented much more efficiently. The trick is that 935 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 936 // arithmetic. To do exact division in modular arithmetic, all we have 937 // to do is multiply by the inverse. Therefore, this step can be done at 938 // width W. 939 // 940 // The next issue is how to safely do the division by 2^T. The way this 941 // is done is by doing the multiplication step at a width of at least W + T 942 // bits. This way, the bottom W+T bits of the product are accurate. Then, 943 // when we perform the division by 2^T (which is equivalent to a right shift 944 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 945 // truncated out after the division by 2^T. 946 // 947 // In comparison to just directly using the first formula, this technique 948 // is much more efficient; using the first formula requires W * K bits, 949 // but this formula less than W + K bits. Also, the first formula requires 950 // a division step, whereas this formula only requires multiplies and shifts. 951 // 952 // It doesn't matter whether the subtraction step is done in the calculation 953 // width or the input iteration count's width; if the subtraction overflows, 954 // the result must be zero anyway. We prefer here to do it in the width of 955 // the induction variable because it helps a lot for certain cases; CodeGen 956 // isn't smart enough to ignore the overflow, which leads to much less 957 // efficient code if the width of the subtraction is wider than the native 958 // register width. 959 // 960 // (It's possible to not widen at all by pulling out factors of 2 before 961 // the multiplication; for example, K=2 can be calculated as 962 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 963 // extra arithmetic, so it's not an obvious win, and it gets 964 // much more complicated for K > 3.) 965 966 // Protection from insane SCEVs; this bound is conservative, 967 // but it probably doesn't matter. 968 if (K > 1000) 969 return SE.getCouldNotCompute(); 970 971 unsigned W = SE.getTypeSizeInBits(ResultTy); 972 973 // Calculate K! / 2^T and T; we divide out the factors of two before 974 // multiplying for calculating K! / 2^T to avoid overflow. 975 // Other overflow doesn't matter because we only care about the bottom 976 // W bits of the result. 977 APInt OddFactorial(W, 1); 978 unsigned T = 1; 979 for (unsigned i = 3; i <= K; ++i) { 980 APInt Mult(W, i); 981 unsigned TwoFactors = Mult.countTrailingZeros(); 982 T += TwoFactors; 983 Mult.lshrInPlace(TwoFactors); 984 OddFactorial *= Mult; 985 } 986 987 // We need at least W + T bits for the multiplication step 988 unsigned CalculationBits = W + T; 989 990 // Calculate 2^T, at width T+W. 991 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 992 993 // Calculate the multiplicative inverse of K! / 2^T; 994 // this multiplication factor will perform the exact division by 995 // K! / 2^T. 996 APInt Mod = APInt::getSignedMinValue(W+1); 997 APInt MultiplyFactor = OddFactorial.zext(W+1); 998 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 999 MultiplyFactor = MultiplyFactor.trunc(W); 1000 1001 // Calculate the product, at width T+W 1002 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1003 CalculationBits); 1004 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1005 for (unsigned i = 1; i != K; ++i) { 1006 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1007 Dividend = SE.getMulExpr(Dividend, 1008 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1009 } 1010 1011 // Divide by 2^T 1012 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1013 1014 // Truncate the result, and divide by K! / 2^T. 1015 1016 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1017 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1018 } 1019 1020 /// Return the value of this chain of recurrences at the specified iteration 1021 /// number. We can evaluate this recurrence by multiplying each element in the 1022 /// chain by the binomial coefficient corresponding to it. In other words, we 1023 /// can evaluate {A,+,B,+,C,+,D} as: 1024 /// 1025 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1026 /// 1027 /// where BC(It, k) stands for binomial coefficient. 1028 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1029 ScalarEvolution &SE) const { 1030 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1031 } 1032 1033 const SCEV * 1034 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1035 const SCEV *It, ScalarEvolution &SE) { 1036 assert(Operands.size() > 0); 1037 const SCEV *Result = Operands[0]; 1038 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1039 // The computation is correct in the face of overflow provided that the 1040 // multiplication is performed _after_ the evaluation of the binomial 1041 // coefficient. 1042 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1043 if (isa<SCEVCouldNotCompute>(Coeff)) 1044 return Coeff; 1045 1046 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1047 } 1048 return Result; 1049 } 1050 1051 //===----------------------------------------------------------------------===// 1052 // SCEV Expression folder implementations 1053 //===----------------------------------------------------------------------===// 1054 1055 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1056 unsigned Depth) { 1057 assert(Depth <= 1 && 1058 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1059 1060 // We could be called with an integer-typed operands during SCEV rewrites. 1061 // Since the operand is an integer already, just perform zext/trunc/self cast. 1062 if (!Op->getType()->isPointerTy()) 1063 return Op; 1064 1065 // What would be an ID for such a SCEV cast expression? 1066 FoldingSetNodeID ID; 1067 ID.AddInteger(scPtrToInt); 1068 ID.AddPointer(Op); 1069 1070 void *IP = nullptr; 1071 1072 // Is there already an expression for such a cast? 1073 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1074 return S; 1075 1076 // It isn't legal for optimizations to construct new ptrtoint expressions 1077 // for non-integral pointers. 1078 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1079 return getCouldNotCompute(); 1080 1081 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1082 1083 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1084 // is sufficiently wide to represent all possible pointer values. 1085 // We could theoretically teach SCEV to truncate wider pointers, but 1086 // that isn't implemented for now. 1087 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1088 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1089 return getCouldNotCompute(); 1090 1091 // If not, is this expression something we can't reduce any further? 1092 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1093 // Perform some basic constant folding. If the operand of the ptr2int cast 1094 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1095 // left as-is), but produce a zero constant. 1096 // NOTE: We could handle a more general case, but lack motivational cases. 1097 if (isa<ConstantPointerNull>(U->getValue())) 1098 return getZero(IntPtrTy); 1099 1100 // Create an explicit cast node. 1101 // We can reuse the existing insert position since if we get here, 1102 // we won't have made any changes which would invalidate it. 1103 SCEV *S = new (SCEVAllocator) 1104 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1105 UniqueSCEVs.InsertNode(S, IP); 1106 addToLoopUseLists(S); 1107 return S; 1108 } 1109 1110 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1111 "non-SCEVUnknown's."); 1112 1113 // Otherwise, we've got some expression that is more complex than just a 1114 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1115 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1116 // only, and the expressions must otherwise be integer-typed. 1117 // So sink the cast down to the SCEVUnknown's. 1118 1119 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1120 /// which computes a pointer-typed value, and rewrites the whole expression 1121 /// tree so that *all* the computations are done on integers, and the only 1122 /// pointer-typed operands in the expression are SCEVUnknown. 1123 class SCEVPtrToIntSinkingRewriter 1124 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1125 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1126 1127 public: 1128 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1129 1130 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1131 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1132 return Rewriter.visit(Scev); 1133 } 1134 1135 const SCEV *visit(const SCEV *S) { 1136 Type *STy = S->getType(); 1137 // If the expression is not pointer-typed, just keep it as-is. 1138 if (!STy->isPointerTy()) 1139 return S; 1140 // Else, recursively sink the cast down into it. 1141 return Base::visit(S); 1142 } 1143 1144 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1145 SmallVector<const SCEV *, 2> Operands; 1146 bool Changed = false; 1147 for (auto *Op : Expr->operands()) { 1148 Operands.push_back(visit(Op)); 1149 Changed |= Op != Operands.back(); 1150 } 1151 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1152 } 1153 1154 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1155 SmallVector<const SCEV *, 2> Operands; 1156 bool Changed = false; 1157 for (auto *Op : Expr->operands()) { 1158 Operands.push_back(visit(Op)); 1159 Changed |= Op != Operands.back(); 1160 } 1161 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1162 } 1163 1164 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1165 assert(Expr->getType()->isPointerTy() && 1166 "Should only reach pointer-typed SCEVUnknown's."); 1167 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1168 } 1169 }; 1170 1171 // And actually perform the cast sinking. 1172 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1173 assert(IntOp->getType()->isIntegerTy() && 1174 "We must have succeeded in sinking the cast, " 1175 "and ending up with an integer-typed expression!"); 1176 return IntOp; 1177 } 1178 1179 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1180 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1181 1182 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1183 if (isa<SCEVCouldNotCompute>(IntOp)) 1184 return IntOp; 1185 1186 return getTruncateOrZeroExtend(IntOp, Ty); 1187 } 1188 1189 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1190 unsigned Depth) { 1191 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1192 "This is not a truncating conversion!"); 1193 assert(isSCEVable(Ty) && 1194 "This is not a conversion to a SCEVable type!"); 1195 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1196 Ty = getEffectiveSCEVType(Ty); 1197 1198 FoldingSetNodeID ID; 1199 ID.AddInteger(scTruncate); 1200 ID.AddPointer(Op); 1201 ID.AddPointer(Ty); 1202 void *IP = nullptr; 1203 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1204 1205 // Fold if the operand is constant. 1206 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1207 return getConstant( 1208 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1209 1210 // trunc(trunc(x)) --> trunc(x) 1211 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1212 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1213 1214 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1215 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1216 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1217 1218 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1219 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1220 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1221 1222 if (Depth > MaxCastDepth) { 1223 SCEV *S = 1224 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1225 UniqueSCEVs.InsertNode(S, IP); 1226 addToLoopUseLists(S); 1227 return S; 1228 } 1229 1230 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1231 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1232 // if after transforming we have at most one truncate, not counting truncates 1233 // that replace other casts. 1234 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1235 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1236 SmallVector<const SCEV *, 4> Operands; 1237 unsigned numTruncs = 0; 1238 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1239 ++i) { 1240 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1241 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1242 isa<SCEVTruncateExpr>(S)) 1243 numTruncs++; 1244 Operands.push_back(S); 1245 } 1246 if (numTruncs < 2) { 1247 if (isa<SCEVAddExpr>(Op)) 1248 return getAddExpr(Operands); 1249 else if (isa<SCEVMulExpr>(Op)) 1250 return getMulExpr(Operands); 1251 else 1252 llvm_unreachable("Unexpected SCEV type for Op."); 1253 } 1254 // Although we checked in the beginning that ID is not in the cache, it is 1255 // possible that during recursion and different modification ID was inserted 1256 // into the cache. So if we find it, just return it. 1257 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1258 return S; 1259 } 1260 1261 // If the input value is a chrec scev, truncate the chrec's operands. 1262 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1263 SmallVector<const SCEV *, 4> Operands; 1264 for (const SCEV *Op : AddRec->operands()) 1265 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1266 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1267 } 1268 1269 // Return zero if truncating to known zeros. 1270 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1271 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1272 return getZero(Ty); 1273 1274 // The cast wasn't folded; create an explicit cast node. We can reuse 1275 // the existing insert position since if we get here, we won't have 1276 // made any changes which would invalidate it. 1277 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1278 Op, Ty); 1279 UniqueSCEVs.InsertNode(S, IP); 1280 addToLoopUseLists(S); 1281 return S; 1282 } 1283 1284 // Get the limit of a recurrence such that incrementing by Step cannot cause 1285 // signed overflow as long as the value of the recurrence within the 1286 // loop does not exceed this limit before incrementing. 1287 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1288 ICmpInst::Predicate *Pred, 1289 ScalarEvolution *SE) { 1290 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1291 if (SE->isKnownPositive(Step)) { 1292 *Pred = ICmpInst::ICMP_SLT; 1293 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1294 SE->getSignedRangeMax(Step)); 1295 } 1296 if (SE->isKnownNegative(Step)) { 1297 *Pred = ICmpInst::ICMP_SGT; 1298 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1299 SE->getSignedRangeMin(Step)); 1300 } 1301 return nullptr; 1302 } 1303 1304 // Get the limit of a recurrence such that incrementing by Step cannot cause 1305 // unsigned overflow as long as the value of the recurrence within the loop does 1306 // not exceed this limit before incrementing. 1307 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1308 ICmpInst::Predicate *Pred, 1309 ScalarEvolution *SE) { 1310 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1311 *Pred = ICmpInst::ICMP_ULT; 1312 1313 return SE->getConstant(APInt::getMinValue(BitWidth) - 1314 SE->getUnsignedRangeMax(Step)); 1315 } 1316 1317 namespace { 1318 1319 struct ExtendOpTraitsBase { 1320 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1321 unsigned); 1322 }; 1323 1324 // Used to make code generic over signed and unsigned overflow. 1325 template <typename ExtendOp> struct ExtendOpTraits { 1326 // Members present: 1327 // 1328 // static const SCEV::NoWrapFlags WrapType; 1329 // 1330 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1331 // 1332 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1333 // ICmpInst::Predicate *Pred, 1334 // ScalarEvolution *SE); 1335 }; 1336 1337 template <> 1338 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1339 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1340 1341 static const GetExtendExprTy GetExtendExpr; 1342 1343 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1344 ICmpInst::Predicate *Pred, 1345 ScalarEvolution *SE) { 1346 return getSignedOverflowLimitForStep(Step, Pred, SE); 1347 } 1348 }; 1349 1350 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1351 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1352 1353 template <> 1354 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1355 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1356 1357 static const GetExtendExprTy GetExtendExpr; 1358 1359 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1360 ICmpInst::Predicate *Pred, 1361 ScalarEvolution *SE) { 1362 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1363 } 1364 }; 1365 1366 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1367 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1368 1369 } // end anonymous namespace 1370 1371 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1372 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1373 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1374 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1375 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1376 // expression "Step + sext/zext(PreIncAR)" is congruent with 1377 // "sext/zext(PostIncAR)" 1378 template <typename ExtendOpTy> 1379 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1380 ScalarEvolution *SE, unsigned Depth) { 1381 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1382 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1383 1384 const Loop *L = AR->getLoop(); 1385 const SCEV *Start = AR->getStart(); 1386 const SCEV *Step = AR->getStepRecurrence(*SE); 1387 1388 // Check for a simple looking step prior to loop entry. 1389 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1390 if (!SA) 1391 return nullptr; 1392 1393 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1394 // subtraction is expensive. For this purpose, perform a quick and dirty 1395 // difference, by checking for Step in the operand list. 1396 SmallVector<const SCEV *, 4> DiffOps; 1397 for (const SCEV *Op : SA->operands()) 1398 if (Op != Step) 1399 DiffOps.push_back(Op); 1400 1401 if (DiffOps.size() == SA->getNumOperands()) 1402 return nullptr; 1403 1404 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1405 // `Step`: 1406 1407 // 1. NSW/NUW flags on the step increment. 1408 auto PreStartFlags = 1409 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1410 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1411 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1412 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1413 1414 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1415 // "S+X does not sign/unsign-overflow". 1416 // 1417 1418 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1419 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1420 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1421 return PreStart; 1422 1423 // 2. Direct overflow check on the step operation's expression. 1424 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1425 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1426 const SCEV *OperandExtendedStart = 1427 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1428 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1429 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1430 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1431 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1432 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1433 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1434 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1435 } 1436 return PreStart; 1437 } 1438 1439 // 3. Loop precondition. 1440 ICmpInst::Predicate Pred; 1441 const SCEV *OverflowLimit = 1442 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1443 1444 if (OverflowLimit && 1445 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1446 return PreStart; 1447 1448 return nullptr; 1449 } 1450 1451 // Get the normalized zero or sign extended expression for this AddRec's Start. 1452 template <typename ExtendOpTy> 1453 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1454 ScalarEvolution *SE, 1455 unsigned Depth) { 1456 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1457 1458 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1459 if (!PreStart) 1460 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1461 1462 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1463 Depth), 1464 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1465 } 1466 1467 // Try to prove away overflow by looking at "nearby" add recurrences. A 1468 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1469 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1470 // 1471 // Formally: 1472 // 1473 // {S,+,X} == {S-T,+,X} + T 1474 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1475 // 1476 // If ({S-T,+,X} + T) does not overflow ... (1) 1477 // 1478 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1479 // 1480 // If {S-T,+,X} does not overflow ... (2) 1481 // 1482 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1483 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1484 // 1485 // If (S-T)+T does not overflow ... (3) 1486 // 1487 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1488 // == {Ext(S),+,Ext(X)} == LHS 1489 // 1490 // Thus, if (1), (2) and (3) are true for some T, then 1491 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1492 // 1493 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1494 // does not overflow" restricted to the 0th iteration. Therefore we only need 1495 // to check for (1) and (2). 1496 // 1497 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1498 // is `Delta` (defined below). 1499 template <typename ExtendOpTy> 1500 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1501 const SCEV *Step, 1502 const Loop *L) { 1503 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1504 1505 // We restrict `Start` to a constant to prevent SCEV from spending too much 1506 // time here. It is correct (but more expensive) to continue with a 1507 // non-constant `Start` and do a general SCEV subtraction to compute 1508 // `PreStart` below. 1509 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1510 if (!StartC) 1511 return false; 1512 1513 APInt StartAI = StartC->getAPInt(); 1514 1515 for (unsigned Delta : {-2, -1, 1, 2}) { 1516 const SCEV *PreStart = getConstant(StartAI - Delta); 1517 1518 FoldingSetNodeID ID; 1519 ID.AddInteger(scAddRecExpr); 1520 ID.AddPointer(PreStart); 1521 ID.AddPointer(Step); 1522 ID.AddPointer(L); 1523 void *IP = nullptr; 1524 const auto *PreAR = 1525 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1526 1527 // Give up if we don't already have the add recurrence we need because 1528 // actually constructing an add recurrence is relatively expensive. 1529 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1530 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1531 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1532 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1533 DeltaS, &Pred, this); 1534 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1535 return true; 1536 } 1537 } 1538 1539 return false; 1540 } 1541 1542 // Finds an integer D for an expression (C + x + y + ...) such that the top 1543 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1544 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1545 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1546 // the (C + x + y + ...) expression is \p WholeAddExpr. 1547 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1548 const SCEVConstant *ConstantTerm, 1549 const SCEVAddExpr *WholeAddExpr) { 1550 const APInt &C = ConstantTerm->getAPInt(); 1551 const unsigned BitWidth = C.getBitWidth(); 1552 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1553 uint32_t TZ = BitWidth; 1554 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1555 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1556 if (TZ) { 1557 // Set D to be as many least significant bits of C as possible while still 1558 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1559 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1560 } 1561 return APInt(BitWidth, 0); 1562 } 1563 1564 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1565 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1566 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1567 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1568 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1569 const APInt &ConstantStart, 1570 const SCEV *Step) { 1571 const unsigned BitWidth = ConstantStart.getBitWidth(); 1572 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1573 if (TZ) 1574 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1575 : ConstantStart; 1576 return APInt(BitWidth, 0); 1577 } 1578 1579 const SCEV * 1580 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1581 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1582 "This is not an extending conversion!"); 1583 assert(isSCEVable(Ty) && 1584 "This is not a conversion to a SCEVable type!"); 1585 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1586 Ty = getEffectiveSCEVType(Ty); 1587 1588 // Fold if the operand is constant. 1589 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1590 return getConstant( 1591 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1592 1593 // zext(zext(x)) --> zext(x) 1594 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1595 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1596 1597 // Before doing any expensive analysis, check to see if we've already 1598 // computed a SCEV for this Op and Ty. 1599 FoldingSetNodeID ID; 1600 ID.AddInteger(scZeroExtend); 1601 ID.AddPointer(Op); 1602 ID.AddPointer(Ty); 1603 void *IP = nullptr; 1604 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1605 if (Depth > MaxCastDepth) { 1606 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1607 Op, Ty); 1608 UniqueSCEVs.InsertNode(S, IP); 1609 addToLoopUseLists(S); 1610 return S; 1611 } 1612 1613 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1614 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1615 // It's possible the bits taken off by the truncate were all zero bits. If 1616 // so, we should be able to simplify this further. 1617 const SCEV *X = ST->getOperand(); 1618 ConstantRange CR = getUnsignedRange(X); 1619 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1620 unsigned NewBits = getTypeSizeInBits(Ty); 1621 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1622 CR.zextOrTrunc(NewBits))) 1623 return getTruncateOrZeroExtend(X, Ty, Depth); 1624 } 1625 1626 // If the input value is a chrec scev, and we can prove that the value 1627 // did not overflow the old, smaller, value, we can zero extend all of the 1628 // operands (often constants). This allows analysis of something like 1629 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1630 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1631 if (AR->isAffine()) { 1632 const SCEV *Start = AR->getStart(); 1633 const SCEV *Step = AR->getStepRecurrence(*this); 1634 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1635 const Loop *L = AR->getLoop(); 1636 1637 if (!AR->hasNoUnsignedWrap()) { 1638 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1639 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1640 } 1641 1642 // If we have special knowledge that this addrec won't overflow, 1643 // we don't need to do any further analysis. 1644 if (AR->hasNoUnsignedWrap()) 1645 return getAddRecExpr( 1646 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1647 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1648 1649 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1650 // Note that this serves two purposes: It filters out loops that are 1651 // simply not analyzable, and it covers the case where this code is 1652 // being called from within backedge-taken count analysis, such that 1653 // attempting to ask for the backedge-taken count would likely result 1654 // in infinite recursion. In the later case, the analysis code will 1655 // cope with a conservative value, and it will take care to purge 1656 // that value once it has finished. 1657 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1658 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1659 // Manually compute the final value for AR, checking for overflow. 1660 1661 // Check whether the backedge-taken count can be losslessly casted to 1662 // the addrec's type. The count is always unsigned. 1663 const SCEV *CastedMaxBECount = 1664 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1665 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1666 CastedMaxBECount, MaxBECount->getType(), Depth); 1667 if (MaxBECount == RecastedMaxBECount) { 1668 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1669 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1670 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1671 SCEV::FlagAnyWrap, Depth + 1); 1672 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1673 SCEV::FlagAnyWrap, 1674 Depth + 1), 1675 WideTy, Depth + 1); 1676 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1677 const SCEV *WideMaxBECount = 1678 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1679 const SCEV *OperandExtendedAdd = 1680 getAddExpr(WideStart, 1681 getMulExpr(WideMaxBECount, 1682 getZeroExtendExpr(Step, WideTy, Depth + 1), 1683 SCEV::FlagAnyWrap, Depth + 1), 1684 SCEV::FlagAnyWrap, Depth + 1); 1685 if (ZAdd == OperandExtendedAdd) { 1686 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1687 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1688 // Return the expression with the addrec on the outside. 1689 return getAddRecExpr( 1690 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1691 Depth + 1), 1692 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1693 AR->getNoWrapFlags()); 1694 } 1695 // Similar to above, only this time treat the step value as signed. 1696 // This covers loops that count down. 1697 OperandExtendedAdd = 1698 getAddExpr(WideStart, 1699 getMulExpr(WideMaxBECount, 1700 getSignExtendExpr(Step, WideTy, Depth + 1), 1701 SCEV::FlagAnyWrap, Depth + 1), 1702 SCEV::FlagAnyWrap, Depth + 1); 1703 if (ZAdd == OperandExtendedAdd) { 1704 // Cache knowledge of AR NW, which is propagated to this AddRec. 1705 // Negative step causes unsigned wrap, but it still can't self-wrap. 1706 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1707 // Return the expression with the addrec on the outside. 1708 return getAddRecExpr( 1709 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1710 Depth + 1), 1711 getSignExtendExpr(Step, Ty, Depth + 1), L, 1712 AR->getNoWrapFlags()); 1713 } 1714 } 1715 } 1716 1717 // Normally, in the cases we can prove no-overflow via a 1718 // backedge guarding condition, we can also compute a backedge 1719 // taken count for the loop. The exceptions are assumptions and 1720 // guards present in the loop -- SCEV is not great at exploiting 1721 // these to compute max backedge taken counts, but can still use 1722 // these to prove lack of overflow. Use this fact to avoid 1723 // doing extra work that may not pay off. 1724 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1725 !AC.assumptions().empty()) { 1726 1727 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1728 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1729 if (AR->hasNoUnsignedWrap()) { 1730 // Same as nuw case above - duplicated here to avoid a compile time 1731 // issue. It's not clear that the order of checks does matter, but 1732 // it's one of two issue possible causes for a change which was 1733 // reverted. Be conservative for the moment. 1734 return getAddRecExpr( 1735 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1736 Depth + 1), 1737 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1738 AR->getNoWrapFlags()); 1739 } 1740 1741 // For a negative step, we can extend the operands iff doing so only 1742 // traverses values in the range zext([0,UINT_MAX]). 1743 if (isKnownNegative(Step)) { 1744 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1745 getSignedRangeMin(Step)); 1746 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1747 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1748 // Cache knowledge of AR NW, which is propagated to this 1749 // AddRec. Negative step causes unsigned wrap, but it 1750 // still can't self-wrap. 1751 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1752 // Return the expression with the addrec on the outside. 1753 return getAddRecExpr( 1754 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1755 Depth + 1), 1756 getSignExtendExpr(Step, Ty, Depth + 1), L, 1757 AR->getNoWrapFlags()); 1758 } 1759 } 1760 } 1761 1762 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1763 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1764 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1765 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1766 const APInt &C = SC->getAPInt(); 1767 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1768 if (D != 0) { 1769 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1770 const SCEV *SResidual = 1771 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1772 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1773 return getAddExpr(SZExtD, SZExtR, 1774 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1775 Depth + 1); 1776 } 1777 } 1778 1779 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1780 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1781 return getAddRecExpr( 1782 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1783 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1784 } 1785 } 1786 1787 // zext(A % B) --> zext(A) % zext(B) 1788 { 1789 const SCEV *LHS; 1790 const SCEV *RHS; 1791 if (matchURem(Op, LHS, RHS)) 1792 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1793 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1794 } 1795 1796 // zext(A / B) --> zext(A) / zext(B). 1797 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1798 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1799 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1800 1801 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1802 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1803 if (SA->hasNoUnsignedWrap()) { 1804 // If the addition does not unsign overflow then we can, by definition, 1805 // commute the zero extension with the addition operation. 1806 SmallVector<const SCEV *, 4> Ops; 1807 for (const auto *Op : SA->operands()) 1808 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1809 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1810 } 1811 1812 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1813 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1814 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1815 // 1816 // Often address arithmetics contain expressions like 1817 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1818 // This transformation is useful while proving that such expressions are 1819 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1820 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1821 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1822 if (D != 0) { 1823 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1824 const SCEV *SResidual = 1825 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1826 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1827 return getAddExpr(SZExtD, SZExtR, 1828 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1829 Depth + 1); 1830 } 1831 } 1832 } 1833 1834 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1835 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1836 if (SM->hasNoUnsignedWrap()) { 1837 // If the multiply does not unsign overflow then we can, by definition, 1838 // commute the zero extension with the multiply operation. 1839 SmallVector<const SCEV *, 4> Ops; 1840 for (const auto *Op : SM->operands()) 1841 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1842 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1843 } 1844 1845 // zext(2^K * (trunc X to iN)) to iM -> 1846 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1847 // 1848 // Proof: 1849 // 1850 // zext(2^K * (trunc X to iN)) to iM 1851 // = zext((trunc X to iN) << K) to iM 1852 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1853 // (because shl removes the top K bits) 1854 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1855 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1856 // 1857 if (SM->getNumOperands() == 2) 1858 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1859 if (MulLHS->getAPInt().isPowerOf2()) 1860 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1861 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1862 MulLHS->getAPInt().logBase2(); 1863 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1864 return getMulExpr( 1865 getZeroExtendExpr(MulLHS, Ty), 1866 getZeroExtendExpr( 1867 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1868 SCEV::FlagNUW, Depth + 1); 1869 } 1870 } 1871 1872 // The cast wasn't folded; create an explicit cast node. 1873 // Recompute the insert position, as it may have been invalidated. 1874 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1875 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1876 Op, Ty); 1877 UniqueSCEVs.InsertNode(S, IP); 1878 addToLoopUseLists(S); 1879 return S; 1880 } 1881 1882 const SCEV * 1883 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1884 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1885 "This is not an extending conversion!"); 1886 assert(isSCEVable(Ty) && 1887 "This is not a conversion to a SCEVable type!"); 1888 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1889 Ty = getEffectiveSCEVType(Ty); 1890 1891 // Fold if the operand is constant. 1892 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1893 return getConstant( 1894 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1895 1896 // sext(sext(x)) --> sext(x) 1897 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1898 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1899 1900 // sext(zext(x)) --> zext(x) 1901 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1902 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1903 1904 // Before doing any expensive analysis, check to see if we've already 1905 // computed a SCEV for this Op and Ty. 1906 FoldingSetNodeID ID; 1907 ID.AddInteger(scSignExtend); 1908 ID.AddPointer(Op); 1909 ID.AddPointer(Ty); 1910 void *IP = nullptr; 1911 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1912 // Limit recursion depth. 1913 if (Depth > MaxCastDepth) { 1914 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1915 Op, Ty); 1916 UniqueSCEVs.InsertNode(S, IP); 1917 addToLoopUseLists(S); 1918 return S; 1919 } 1920 1921 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1922 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1923 // It's possible the bits taken off by the truncate were all sign bits. If 1924 // so, we should be able to simplify this further. 1925 const SCEV *X = ST->getOperand(); 1926 ConstantRange CR = getSignedRange(X); 1927 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1928 unsigned NewBits = getTypeSizeInBits(Ty); 1929 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1930 CR.sextOrTrunc(NewBits))) 1931 return getTruncateOrSignExtend(X, Ty, Depth); 1932 } 1933 1934 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1935 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1936 if (SA->hasNoSignedWrap()) { 1937 // If the addition does not sign overflow then we can, by definition, 1938 // commute the sign extension with the addition operation. 1939 SmallVector<const SCEV *, 4> Ops; 1940 for (const auto *Op : SA->operands()) 1941 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1942 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1943 } 1944 1945 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1946 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1947 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1948 // 1949 // For instance, this will bring two seemingly different expressions: 1950 // 1 + sext(5 + 20 * %x + 24 * %y) and 1951 // sext(6 + 20 * %x + 24 * %y) 1952 // to the same form: 1953 // 2 + sext(4 + 20 * %x + 24 * %y) 1954 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1955 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1956 if (D != 0) { 1957 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1958 const SCEV *SResidual = 1959 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1960 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1961 return getAddExpr(SSExtD, SSExtR, 1962 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1963 Depth + 1); 1964 } 1965 } 1966 } 1967 // If the input value is a chrec scev, and we can prove that the value 1968 // did not overflow the old, smaller, value, we can sign extend all of the 1969 // operands (often constants). This allows analysis of something like 1970 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1971 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1972 if (AR->isAffine()) { 1973 const SCEV *Start = AR->getStart(); 1974 const SCEV *Step = AR->getStepRecurrence(*this); 1975 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1976 const Loop *L = AR->getLoop(); 1977 1978 if (!AR->hasNoSignedWrap()) { 1979 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1980 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1981 } 1982 1983 // If we have special knowledge that this addrec won't overflow, 1984 // we don't need to do any further analysis. 1985 if (AR->hasNoSignedWrap()) 1986 return getAddRecExpr( 1987 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1988 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1989 1990 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1991 // Note that this serves two purposes: It filters out loops that are 1992 // simply not analyzable, and it covers the case where this code is 1993 // being called from within backedge-taken count analysis, such that 1994 // attempting to ask for the backedge-taken count would likely result 1995 // in infinite recursion. In the later case, the analysis code will 1996 // cope with a conservative value, and it will take care to purge 1997 // that value once it has finished. 1998 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1999 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2000 // Manually compute the final value for AR, checking for 2001 // overflow. 2002 2003 // Check whether the backedge-taken count can be losslessly casted to 2004 // the addrec's type. The count is always unsigned. 2005 const SCEV *CastedMaxBECount = 2006 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2007 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2008 CastedMaxBECount, MaxBECount->getType(), Depth); 2009 if (MaxBECount == RecastedMaxBECount) { 2010 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2011 // Check whether Start+Step*MaxBECount has no signed overflow. 2012 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2013 SCEV::FlagAnyWrap, Depth + 1); 2014 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2015 SCEV::FlagAnyWrap, 2016 Depth + 1), 2017 WideTy, Depth + 1); 2018 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2019 const SCEV *WideMaxBECount = 2020 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2021 const SCEV *OperandExtendedAdd = 2022 getAddExpr(WideStart, 2023 getMulExpr(WideMaxBECount, 2024 getSignExtendExpr(Step, WideTy, Depth + 1), 2025 SCEV::FlagAnyWrap, Depth + 1), 2026 SCEV::FlagAnyWrap, Depth + 1); 2027 if (SAdd == OperandExtendedAdd) { 2028 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2029 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2030 // Return the expression with the addrec on the outside. 2031 return getAddRecExpr( 2032 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2033 Depth + 1), 2034 getSignExtendExpr(Step, Ty, Depth + 1), L, 2035 AR->getNoWrapFlags()); 2036 } 2037 // Similar to above, only this time treat the step value as unsigned. 2038 // This covers loops that count up with an unsigned step. 2039 OperandExtendedAdd = 2040 getAddExpr(WideStart, 2041 getMulExpr(WideMaxBECount, 2042 getZeroExtendExpr(Step, WideTy, Depth + 1), 2043 SCEV::FlagAnyWrap, Depth + 1), 2044 SCEV::FlagAnyWrap, Depth + 1); 2045 if (SAdd == OperandExtendedAdd) { 2046 // If AR wraps around then 2047 // 2048 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2049 // => SAdd != OperandExtendedAdd 2050 // 2051 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2052 // (SAdd == OperandExtendedAdd => AR is NW) 2053 2054 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2055 2056 // Return the expression with the addrec on the outside. 2057 return getAddRecExpr( 2058 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2059 Depth + 1), 2060 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2061 AR->getNoWrapFlags()); 2062 } 2063 } 2064 } 2065 2066 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2067 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2068 if (AR->hasNoSignedWrap()) { 2069 // Same as nsw case above - duplicated here to avoid a compile time 2070 // issue. It's not clear that the order of checks does matter, but 2071 // it's one of two issue possible causes for a change which was 2072 // reverted. Be conservative for the moment. 2073 return getAddRecExpr( 2074 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2075 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2076 } 2077 2078 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2079 // if D + (C - D + Step * n) could be proven to not signed wrap 2080 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2081 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2082 const APInt &C = SC->getAPInt(); 2083 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2084 if (D != 0) { 2085 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2086 const SCEV *SResidual = 2087 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2088 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2089 return getAddExpr(SSExtD, SSExtR, 2090 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2091 Depth + 1); 2092 } 2093 } 2094 2095 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2096 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2097 return getAddRecExpr( 2098 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2099 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2100 } 2101 } 2102 2103 // If the input value is provably positive and we could not simplify 2104 // away the sext build a zext instead. 2105 if (isKnownNonNegative(Op)) 2106 return getZeroExtendExpr(Op, Ty, Depth + 1); 2107 2108 // The cast wasn't folded; create an explicit cast node. 2109 // Recompute the insert position, as it may have been invalidated. 2110 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2111 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2112 Op, Ty); 2113 UniqueSCEVs.InsertNode(S, IP); 2114 addToLoopUseLists(S); 2115 return S; 2116 } 2117 2118 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2119 /// unspecified bits out to the given type. 2120 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2121 Type *Ty) { 2122 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2123 "This is not an extending conversion!"); 2124 assert(isSCEVable(Ty) && 2125 "This is not a conversion to a SCEVable type!"); 2126 Ty = getEffectiveSCEVType(Ty); 2127 2128 // Sign-extend negative constants. 2129 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2130 if (SC->getAPInt().isNegative()) 2131 return getSignExtendExpr(Op, Ty); 2132 2133 // Peel off a truncate cast. 2134 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2135 const SCEV *NewOp = T->getOperand(); 2136 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2137 return getAnyExtendExpr(NewOp, Ty); 2138 return getTruncateOrNoop(NewOp, Ty); 2139 } 2140 2141 // Next try a zext cast. If the cast is folded, use it. 2142 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2143 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2144 return ZExt; 2145 2146 // Next try a sext cast. If the cast is folded, use it. 2147 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2148 if (!isa<SCEVSignExtendExpr>(SExt)) 2149 return SExt; 2150 2151 // Force the cast to be folded into the operands of an addrec. 2152 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2153 SmallVector<const SCEV *, 4> Ops; 2154 for (const SCEV *Op : AR->operands()) 2155 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2156 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2157 } 2158 2159 // If the expression is obviously signed, use the sext cast value. 2160 if (isa<SCEVSMaxExpr>(Op)) 2161 return SExt; 2162 2163 // Absent any other information, use the zext cast value. 2164 return ZExt; 2165 } 2166 2167 /// Process the given Ops list, which is a list of operands to be added under 2168 /// the given scale, update the given map. This is a helper function for 2169 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2170 /// that would form an add expression like this: 2171 /// 2172 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2173 /// 2174 /// where A and B are constants, update the map with these values: 2175 /// 2176 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2177 /// 2178 /// and add 13 + A*B*29 to AccumulatedConstant. 2179 /// This will allow getAddRecExpr to produce this: 2180 /// 2181 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2182 /// 2183 /// This form often exposes folding opportunities that are hidden in 2184 /// the original operand list. 2185 /// 2186 /// Return true iff it appears that any interesting folding opportunities 2187 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2188 /// the common case where no interesting opportunities are present, and 2189 /// is also used as a check to avoid infinite recursion. 2190 static bool 2191 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2192 SmallVectorImpl<const SCEV *> &NewOps, 2193 APInt &AccumulatedConstant, 2194 const SCEV *const *Ops, size_t NumOperands, 2195 const APInt &Scale, 2196 ScalarEvolution &SE) { 2197 bool Interesting = false; 2198 2199 // Iterate over the add operands. They are sorted, with constants first. 2200 unsigned i = 0; 2201 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2202 ++i; 2203 // Pull a buried constant out to the outside. 2204 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2205 Interesting = true; 2206 AccumulatedConstant += Scale * C->getAPInt(); 2207 } 2208 2209 // Next comes everything else. We're especially interested in multiplies 2210 // here, but they're in the middle, so just visit the rest with one loop. 2211 for (; i != NumOperands; ++i) { 2212 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2213 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2214 APInt NewScale = 2215 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2216 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2217 // A multiplication of a constant with another add; recurse. 2218 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2219 Interesting |= 2220 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2221 Add->op_begin(), Add->getNumOperands(), 2222 NewScale, SE); 2223 } else { 2224 // A multiplication of a constant with some other value. Update 2225 // the map. 2226 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2227 const SCEV *Key = SE.getMulExpr(MulOps); 2228 auto Pair = M.insert({Key, NewScale}); 2229 if (Pair.second) { 2230 NewOps.push_back(Pair.first->first); 2231 } else { 2232 Pair.first->second += NewScale; 2233 // The map already had an entry for this value, which may indicate 2234 // a folding opportunity. 2235 Interesting = true; 2236 } 2237 } 2238 } else { 2239 // An ordinary operand. Update the map. 2240 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2241 M.insert({Ops[i], Scale}); 2242 if (Pair.second) { 2243 NewOps.push_back(Pair.first->first); 2244 } else { 2245 Pair.first->second += Scale; 2246 // The map already had an entry for this value, which may indicate 2247 // a folding opportunity. 2248 Interesting = true; 2249 } 2250 } 2251 } 2252 2253 return Interesting; 2254 } 2255 2256 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2257 const SCEV *LHS, const SCEV *RHS) { 2258 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2259 SCEV::NoWrapFlags, unsigned); 2260 switch (BinOp) { 2261 default: 2262 llvm_unreachable("Unsupported binary op"); 2263 case Instruction::Add: 2264 Operation = &ScalarEvolution::getAddExpr; 2265 break; 2266 case Instruction::Sub: 2267 Operation = &ScalarEvolution::getMinusSCEV; 2268 break; 2269 case Instruction::Mul: 2270 Operation = &ScalarEvolution::getMulExpr; 2271 break; 2272 } 2273 2274 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2275 Signed ? &ScalarEvolution::getSignExtendExpr 2276 : &ScalarEvolution::getZeroExtendExpr; 2277 2278 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2279 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2280 auto *WideTy = 2281 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2282 2283 const SCEV *A = (this->*Extension)( 2284 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2285 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2286 (this->*Extension)(RHS, WideTy, 0), 2287 SCEV::FlagAnyWrap, 0); 2288 return A == B; 2289 } 2290 2291 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2292 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2293 const OverflowingBinaryOperator *OBO) { 2294 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2295 2296 if (OBO->hasNoUnsignedWrap()) 2297 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2298 if (OBO->hasNoSignedWrap()) 2299 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2300 2301 bool Deduced = false; 2302 2303 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2304 return {Flags, Deduced}; 2305 2306 if (OBO->getOpcode() != Instruction::Add && 2307 OBO->getOpcode() != Instruction::Sub && 2308 OBO->getOpcode() != Instruction::Mul) 2309 return {Flags, Deduced}; 2310 2311 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2312 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2313 2314 if (!OBO->hasNoUnsignedWrap() && 2315 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2316 /* Signed */ false, LHS, RHS)) { 2317 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2318 Deduced = true; 2319 } 2320 2321 if (!OBO->hasNoSignedWrap() && 2322 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2323 /* Signed */ true, LHS, RHS)) { 2324 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2325 Deduced = true; 2326 } 2327 2328 return {Flags, Deduced}; 2329 } 2330 2331 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2332 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2333 // can't-overflow flags for the operation if possible. 2334 static SCEV::NoWrapFlags 2335 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2336 const ArrayRef<const SCEV *> Ops, 2337 SCEV::NoWrapFlags Flags) { 2338 using namespace std::placeholders; 2339 2340 using OBO = OverflowingBinaryOperator; 2341 2342 bool CanAnalyze = 2343 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2344 (void)CanAnalyze; 2345 assert(CanAnalyze && "don't call from other places!"); 2346 2347 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2348 SCEV::NoWrapFlags SignOrUnsignWrap = 2349 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2350 2351 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2352 auto IsKnownNonNegative = [&](const SCEV *S) { 2353 return SE->isKnownNonNegative(S); 2354 }; 2355 2356 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2357 Flags = 2358 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2359 2360 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2361 2362 if (SignOrUnsignWrap != SignOrUnsignMask && 2363 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2364 isa<SCEVConstant>(Ops[0])) { 2365 2366 auto Opcode = [&] { 2367 switch (Type) { 2368 case scAddExpr: 2369 return Instruction::Add; 2370 case scMulExpr: 2371 return Instruction::Mul; 2372 default: 2373 llvm_unreachable("Unexpected SCEV op."); 2374 } 2375 }(); 2376 2377 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2378 2379 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2380 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2381 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2382 Opcode, C, OBO::NoSignedWrap); 2383 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2384 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2385 } 2386 2387 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2388 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2389 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2390 Opcode, C, OBO::NoUnsignedWrap); 2391 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2392 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2393 } 2394 } 2395 2396 return Flags; 2397 } 2398 2399 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2400 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2401 } 2402 2403 /// Get a canonical add expression, or something simpler if possible. 2404 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2405 SCEV::NoWrapFlags OrigFlags, 2406 unsigned Depth) { 2407 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2408 "only nuw or nsw allowed"); 2409 assert(!Ops.empty() && "Cannot get empty add!"); 2410 if (Ops.size() == 1) return Ops[0]; 2411 #ifndef NDEBUG 2412 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2413 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2414 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2415 "SCEVAddExpr operand types don't match!"); 2416 unsigned NumPtrs = count_if( 2417 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2418 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2419 #endif 2420 2421 // Sort by complexity, this groups all similar expression types together. 2422 GroupByComplexity(Ops, &LI, DT); 2423 2424 // If there are any constants, fold them together. 2425 unsigned Idx = 0; 2426 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2427 ++Idx; 2428 assert(Idx < Ops.size()); 2429 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2430 // We found two constants, fold them together! 2431 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2432 if (Ops.size() == 2) return Ops[0]; 2433 Ops.erase(Ops.begin()+1); // Erase the folded element 2434 LHSC = cast<SCEVConstant>(Ops[0]); 2435 } 2436 2437 // If we are left with a constant zero being added, strip it off. 2438 if (LHSC->getValue()->isZero()) { 2439 Ops.erase(Ops.begin()); 2440 --Idx; 2441 } 2442 2443 if (Ops.size() == 1) return Ops[0]; 2444 } 2445 2446 // Delay expensive flag strengthening until necessary. 2447 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2448 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2449 }; 2450 2451 // Limit recursion calls depth. 2452 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2453 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2454 2455 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2456 // Don't strengthen flags if we have no new information. 2457 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2458 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2459 Add->setNoWrapFlags(ComputeFlags(Ops)); 2460 return S; 2461 } 2462 2463 // Okay, check to see if the same value occurs in the operand list more than 2464 // once. If so, merge them together into an multiply expression. Since we 2465 // sorted the list, these values are required to be adjacent. 2466 Type *Ty = Ops[0]->getType(); 2467 bool FoundMatch = false; 2468 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2469 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2470 // Scan ahead to count how many equal operands there are. 2471 unsigned Count = 2; 2472 while (i+Count != e && Ops[i+Count] == Ops[i]) 2473 ++Count; 2474 // Merge the values into a multiply. 2475 const SCEV *Scale = getConstant(Ty, Count); 2476 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2477 if (Ops.size() == Count) 2478 return Mul; 2479 Ops[i] = Mul; 2480 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2481 --i; e -= Count - 1; 2482 FoundMatch = true; 2483 } 2484 if (FoundMatch) 2485 return getAddExpr(Ops, OrigFlags, Depth + 1); 2486 2487 // Check for truncates. If all the operands are truncated from the same 2488 // type, see if factoring out the truncate would permit the result to be 2489 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2490 // if the contents of the resulting outer trunc fold to something simple. 2491 auto FindTruncSrcType = [&]() -> Type * { 2492 // We're ultimately looking to fold an addrec of truncs and muls of only 2493 // constants and truncs, so if we find any other types of SCEV 2494 // as operands of the addrec then we bail and return nullptr here. 2495 // Otherwise, we return the type of the operand of a trunc that we find. 2496 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2497 return T->getOperand()->getType(); 2498 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2499 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2500 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2501 return T->getOperand()->getType(); 2502 } 2503 return nullptr; 2504 }; 2505 if (auto *SrcType = FindTruncSrcType()) { 2506 SmallVector<const SCEV *, 8> LargeOps; 2507 bool Ok = true; 2508 // Check all the operands to see if they can be represented in the 2509 // source type of the truncate. 2510 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2511 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2512 if (T->getOperand()->getType() != SrcType) { 2513 Ok = false; 2514 break; 2515 } 2516 LargeOps.push_back(T->getOperand()); 2517 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2518 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2519 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2520 SmallVector<const SCEV *, 8> LargeMulOps; 2521 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2522 if (const SCEVTruncateExpr *T = 2523 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2524 if (T->getOperand()->getType() != SrcType) { 2525 Ok = false; 2526 break; 2527 } 2528 LargeMulOps.push_back(T->getOperand()); 2529 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2530 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2531 } else { 2532 Ok = false; 2533 break; 2534 } 2535 } 2536 if (Ok) 2537 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2538 } else { 2539 Ok = false; 2540 break; 2541 } 2542 } 2543 if (Ok) { 2544 // Evaluate the expression in the larger type. 2545 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2546 // If it folds to something simple, use it. Otherwise, don't. 2547 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2548 return getTruncateExpr(Fold, Ty); 2549 } 2550 } 2551 2552 if (Ops.size() == 2) { 2553 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2554 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2555 // C1). 2556 const SCEV *A = Ops[0]; 2557 const SCEV *B = Ops[1]; 2558 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2559 auto *C = dyn_cast<SCEVConstant>(A); 2560 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2561 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2562 auto C2 = C->getAPInt(); 2563 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2564 2565 APInt ConstAdd = C1 + C2; 2566 auto AddFlags = AddExpr->getNoWrapFlags(); 2567 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2568 if (ScalarEvolution::maskFlags(AddFlags, SCEV::FlagNUW) == 2569 SCEV::FlagNUW && 2570 ConstAdd.ule(C1)) { 2571 PreservedFlags = 2572 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2573 } 2574 2575 // Adding a constant with the same sign and small magnitude is NSW, if the 2576 // original AddExpr was NSW. 2577 if (ScalarEvolution::maskFlags(AddFlags, SCEV::FlagNSW) == 2578 SCEV::FlagNSW && 2579 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2580 ConstAdd.abs().ule(C1.abs())) { 2581 PreservedFlags = 2582 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2583 } 2584 2585 if (PreservedFlags != SCEV::FlagAnyWrap) { 2586 SmallVector<const SCEV *, 4> NewOps(AddExpr->op_begin(), 2587 AddExpr->op_end()); 2588 NewOps[0] = getConstant(ConstAdd); 2589 return getAddExpr(NewOps, PreservedFlags); 2590 } 2591 } 2592 } 2593 2594 // Skip past any other cast SCEVs. 2595 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2596 ++Idx; 2597 2598 // If there are add operands they would be next. 2599 if (Idx < Ops.size()) { 2600 bool DeletedAdd = false; 2601 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2602 // common NUW flag for expression after inlining. Other flags cannot be 2603 // preserved, because they may depend on the original order of operations. 2604 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2605 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2606 if (Ops.size() > AddOpsInlineThreshold || 2607 Add->getNumOperands() > AddOpsInlineThreshold) 2608 break; 2609 // If we have an add, expand the add operands onto the end of the operands 2610 // list. 2611 Ops.erase(Ops.begin()+Idx); 2612 Ops.append(Add->op_begin(), Add->op_end()); 2613 DeletedAdd = true; 2614 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2615 } 2616 2617 // If we deleted at least one add, we added operands to the end of the list, 2618 // and they are not necessarily sorted. Recurse to resort and resimplify 2619 // any operands we just acquired. 2620 if (DeletedAdd) 2621 return getAddExpr(Ops, CommonFlags, Depth + 1); 2622 } 2623 2624 // Skip over the add expression until we get to a multiply. 2625 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2626 ++Idx; 2627 2628 // Check to see if there are any folding opportunities present with 2629 // operands multiplied by constant values. 2630 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2631 uint64_t BitWidth = getTypeSizeInBits(Ty); 2632 DenseMap<const SCEV *, APInt> M; 2633 SmallVector<const SCEV *, 8> NewOps; 2634 APInt AccumulatedConstant(BitWidth, 0); 2635 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2636 Ops.data(), Ops.size(), 2637 APInt(BitWidth, 1), *this)) { 2638 struct APIntCompare { 2639 bool operator()(const APInt &LHS, const APInt &RHS) const { 2640 return LHS.ult(RHS); 2641 } 2642 }; 2643 2644 // Some interesting folding opportunity is present, so its worthwhile to 2645 // re-generate the operands list. Group the operands by constant scale, 2646 // to avoid multiplying by the same constant scale multiple times. 2647 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2648 for (const SCEV *NewOp : NewOps) 2649 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2650 // Re-generate the operands list. 2651 Ops.clear(); 2652 if (AccumulatedConstant != 0) 2653 Ops.push_back(getConstant(AccumulatedConstant)); 2654 for (auto &MulOp : MulOpLists) { 2655 if (MulOp.first == 1) { 2656 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2657 } else if (MulOp.first != 0) { 2658 Ops.push_back(getMulExpr( 2659 getConstant(MulOp.first), 2660 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2661 SCEV::FlagAnyWrap, Depth + 1)); 2662 } 2663 } 2664 if (Ops.empty()) 2665 return getZero(Ty); 2666 if (Ops.size() == 1) 2667 return Ops[0]; 2668 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2669 } 2670 } 2671 2672 // If we are adding something to a multiply expression, make sure the 2673 // something is not already an operand of the multiply. If so, merge it into 2674 // the multiply. 2675 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2676 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2677 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2678 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2679 if (isa<SCEVConstant>(MulOpSCEV)) 2680 continue; 2681 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2682 if (MulOpSCEV == Ops[AddOp]) { 2683 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2684 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2685 if (Mul->getNumOperands() != 2) { 2686 // If the multiply has more than two operands, we must get the 2687 // Y*Z term. 2688 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2689 Mul->op_begin()+MulOp); 2690 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2691 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2692 } 2693 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2694 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2695 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2696 SCEV::FlagAnyWrap, Depth + 1); 2697 if (Ops.size() == 2) return OuterMul; 2698 if (AddOp < Idx) { 2699 Ops.erase(Ops.begin()+AddOp); 2700 Ops.erase(Ops.begin()+Idx-1); 2701 } else { 2702 Ops.erase(Ops.begin()+Idx); 2703 Ops.erase(Ops.begin()+AddOp-1); 2704 } 2705 Ops.push_back(OuterMul); 2706 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2707 } 2708 2709 // Check this multiply against other multiplies being added together. 2710 for (unsigned OtherMulIdx = Idx+1; 2711 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2712 ++OtherMulIdx) { 2713 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2714 // If MulOp occurs in OtherMul, we can fold the two multiplies 2715 // together. 2716 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2717 OMulOp != e; ++OMulOp) 2718 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2719 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2720 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2721 if (Mul->getNumOperands() != 2) { 2722 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2723 Mul->op_begin()+MulOp); 2724 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2725 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2726 } 2727 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2728 if (OtherMul->getNumOperands() != 2) { 2729 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2730 OtherMul->op_begin()+OMulOp); 2731 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2732 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2733 } 2734 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2735 const SCEV *InnerMulSum = 2736 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2737 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2738 SCEV::FlagAnyWrap, Depth + 1); 2739 if (Ops.size() == 2) return OuterMul; 2740 Ops.erase(Ops.begin()+Idx); 2741 Ops.erase(Ops.begin()+OtherMulIdx-1); 2742 Ops.push_back(OuterMul); 2743 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2744 } 2745 } 2746 } 2747 } 2748 2749 // If there are any add recurrences in the operands list, see if any other 2750 // added values are loop invariant. If so, we can fold them into the 2751 // recurrence. 2752 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2753 ++Idx; 2754 2755 // Scan over all recurrences, trying to fold loop invariants into them. 2756 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2757 // Scan all of the other operands to this add and add them to the vector if 2758 // they are loop invariant w.r.t. the recurrence. 2759 SmallVector<const SCEV *, 8> LIOps; 2760 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2761 const Loop *AddRecLoop = AddRec->getLoop(); 2762 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2763 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2764 LIOps.push_back(Ops[i]); 2765 Ops.erase(Ops.begin()+i); 2766 --i; --e; 2767 } 2768 2769 // If we found some loop invariants, fold them into the recurrence. 2770 if (!LIOps.empty()) { 2771 // Compute nowrap flags for the addition of the loop-invariant ops and 2772 // the addrec. Temporarily push it as an operand for that purpose. 2773 LIOps.push_back(AddRec); 2774 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2775 LIOps.pop_back(); 2776 2777 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2778 LIOps.push_back(AddRec->getStart()); 2779 2780 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2781 // This follows from the fact that the no-wrap flags on the outer add 2782 // expression are applicable on the 0th iteration, when the add recurrence 2783 // will be equal to its start value. 2784 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2785 2786 // Build the new addrec. Propagate the NUW and NSW flags if both the 2787 // outer add and the inner addrec are guaranteed to have no overflow. 2788 // Always propagate NW. 2789 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2790 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2791 2792 // If all of the other operands were loop invariant, we are done. 2793 if (Ops.size() == 1) return NewRec; 2794 2795 // Otherwise, add the folded AddRec by the non-invariant parts. 2796 for (unsigned i = 0;; ++i) 2797 if (Ops[i] == AddRec) { 2798 Ops[i] = NewRec; 2799 break; 2800 } 2801 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2802 } 2803 2804 // Okay, if there weren't any loop invariants to be folded, check to see if 2805 // there are multiple AddRec's with the same loop induction variable being 2806 // added together. If so, we can fold them. 2807 for (unsigned OtherIdx = Idx+1; 2808 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2809 ++OtherIdx) { 2810 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2811 // so that the 1st found AddRecExpr is dominated by all others. 2812 assert(DT.dominates( 2813 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2814 AddRec->getLoop()->getHeader()) && 2815 "AddRecExprs are not sorted in reverse dominance order?"); 2816 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2817 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2818 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2819 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2820 ++OtherIdx) { 2821 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2822 if (OtherAddRec->getLoop() == AddRecLoop) { 2823 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2824 i != e; ++i) { 2825 if (i >= AddRecOps.size()) { 2826 AddRecOps.append(OtherAddRec->op_begin()+i, 2827 OtherAddRec->op_end()); 2828 break; 2829 } 2830 SmallVector<const SCEV *, 2> TwoOps = { 2831 AddRecOps[i], OtherAddRec->getOperand(i)}; 2832 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2833 } 2834 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2835 } 2836 } 2837 // Step size has changed, so we cannot guarantee no self-wraparound. 2838 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2839 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2840 } 2841 } 2842 2843 // Otherwise couldn't fold anything into this recurrence. Move onto the 2844 // next one. 2845 } 2846 2847 // Okay, it looks like we really DO need an add expr. Check to see if we 2848 // already have one, otherwise create a new one. 2849 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2850 } 2851 2852 const SCEV * 2853 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2854 SCEV::NoWrapFlags Flags) { 2855 FoldingSetNodeID ID; 2856 ID.AddInteger(scAddExpr); 2857 for (const SCEV *Op : Ops) 2858 ID.AddPointer(Op); 2859 void *IP = nullptr; 2860 SCEVAddExpr *S = 2861 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2862 if (!S) { 2863 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2864 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2865 S = new (SCEVAllocator) 2866 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2867 UniqueSCEVs.InsertNode(S, IP); 2868 addToLoopUseLists(S); 2869 } 2870 S->setNoWrapFlags(Flags); 2871 return S; 2872 } 2873 2874 const SCEV * 2875 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2876 const Loop *L, SCEV::NoWrapFlags Flags) { 2877 FoldingSetNodeID ID; 2878 ID.AddInteger(scAddRecExpr); 2879 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2880 ID.AddPointer(Ops[i]); 2881 ID.AddPointer(L); 2882 void *IP = nullptr; 2883 SCEVAddRecExpr *S = 2884 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2885 if (!S) { 2886 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2887 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2888 S = new (SCEVAllocator) 2889 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2890 UniqueSCEVs.InsertNode(S, IP); 2891 addToLoopUseLists(S); 2892 } 2893 setNoWrapFlags(S, Flags); 2894 return S; 2895 } 2896 2897 const SCEV * 2898 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2899 SCEV::NoWrapFlags Flags) { 2900 FoldingSetNodeID ID; 2901 ID.AddInteger(scMulExpr); 2902 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2903 ID.AddPointer(Ops[i]); 2904 void *IP = nullptr; 2905 SCEVMulExpr *S = 2906 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2907 if (!S) { 2908 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2909 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2910 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2911 O, Ops.size()); 2912 UniqueSCEVs.InsertNode(S, IP); 2913 addToLoopUseLists(S); 2914 } 2915 S->setNoWrapFlags(Flags); 2916 return S; 2917 } 2918 2919 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2920 uint64_t k = i*j; 2921 if (j > 1 && k / j != i) Overflow = true; 2922 return k; 2923 } 2924 2925 /// Compute the result of "n choose k", the binomial coefficient. If an 2926 /// intermediate computation overflows, Overflow will be set and the return will 2927 /// be garbage. Overflow is not cleared on absence of overflow. 2928 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2929 // We use the multiplicative formula: 2930 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2931 // At each iteration, we take the n-th term of the numeral and divide by the 2932 // (k-n)th term of the denominator. This division will always produce an 2933 // integral result, and helps reduce the chance of overflow in the 2934 // intermediate computations. However, we can still overflow even when the 2935 // final result would fit. 2936 2937 if (n == 0 || n == k) return 1; 2938 if (k > n) return 0; 2939 2940 if (k > n/2) 2941 k = n-k; 2942 2943 uint64_t r = 1; 2944 for (uint64_t i = 1; i <= k; ++i) { 2945 r = umul_ov(r, n-(i-1), Overflow); 2946 r /= i; 2947 } 2948 return r; 2949 } 2950 2951 /// Determine if any of the operands in this SCEV are a constant or if 2952 /// any of the add or multiply expressions in this SCEV contain a constant. 2953 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2954 struct FindConstantInAddMulChain { 2955 bool FoundConstant = false; 2956 2957 bool follow(const SCEV *S) { 2958 FoundConstant |= isa<SCEVConstant>(S); 2959 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2960 } 2961 2962 bool isDone() const { 2963 return FoundConstant; 2964 } 2965 }; 2966 2967 FindConstantInAddMulChain F; 2968 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2969 ST.visitAll(StartExpr); 2970 return F.FoundConstant; 2971 } 2972 2973 /// Get a canonical multiply expression, or something simpler if possible. 2974 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2975 SCEV::NoWrapFlags OrigFlags, 2976 unsigned Depth) { 2977 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2978 "only nuw or nsw allowed"); 2979 assert(!Ops.empty() && "Cannot get empty mul!"); 2980 if (Ops.size() == 1) return Ops[0]; 2981 #ifndef NDEBUG 2982 Type *ETy = Ops[0]->getType(); 2983 assert(!ETy->isPointerTy()); 2984 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2985 assert(Ops[i]->getType() == ETy && 2986 "SCEVMulExpr operand types don't match!"); 2987 #endif 2988 2989 // Sort by complexity, this groups all similar expression types together. 2990 GroupByComplexity(Ops, &LI, DT); 2991 2992 // If there are any constants, fold them together. 2993 unsigned Idx = 0; 2994 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2995 ++Idx; 2996 assert(Idx < Ops.size()); 2997 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2998 // We found two constants, fold them together! 2999 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3000 if (Ops.size() == 2) return Ops[0]; 3001 Ops.erase(Ops.begin()+1); // Erase the folded element 3002 LHSC = cast<SCEVConstant>(Ops[0]); 3003 } 3004 3005 // If we have a multiply of zero, it will always be zero. 3006 if (LHSC->getValue()->isZero()) 3007 return LHSC; 3008 3009 // If we are left with a constant one being multiplied, strip it off. 3010 if (LHSC->getValue()->isOne()) { 3011 Ops.erase(Ops.begin()); 3012 --Idx; 3013 } 3014 3015 if (Ops.size() == 1) 3016 return Ops[0]; 3017 } 3018 3019 // Delay expensive flag strengthening until necessary. 3020 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3021 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3022 }; 3023 3024 // Limit recursion calls depth. 3025 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3026 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3027 3028 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 3029 // Don't strengthen flags if we have no new information. 3030 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3031 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3032 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3033 return S; 3034 } 3035 3036 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3037 if (Ops.size() == 2) { 3038 // C1*(C2+V) -> C1*C2 + C1*V 3039 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3040 // If any of Add's ops are Adds or Muls with a constant, apply this 3041 // transformation as well. 3042 // 3043 // TODO: There are some cases where this transformation is not 3044 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3045 // this transformation should be narrowed down. 3046 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3047 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3048 SCEV::FlagAnyWrap, Depth + 1), 3049 getMulExpr(LHSC, Add->getOperand(1), 3050 SCEV::FlagAnyWrap, Depth + 1), 3051 SCEV::FlagAnyWrap, Depth + 1); 3052 3053 if (Ops[0]->isAllOnesValue()) { 3054 // If we have a mul by -1 of an add, try distributing the -1 among the 3055 // add operands. 3056 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3057 SmallVector<const SCEV *, 4> NewOps; 3058 bool AnyFolded = false; 3059 for (const SCEV *AddOp : Add->operands()) { 3060 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3061 Depth + 1); 3062 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3063 NewOps.push_back(Mul); 3064 } 3065 if (AnyFolded) 3066 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3067 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3068 // Negation preserves a recurrence's no self-wrap property. 3069 SmallVector<const SCEV *, 4> Operands; 3070 for (const SCEV *AddRecOp : AddRec->operands()) 3071 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3072 Depth + 1)); 3073 3074 return getAddRecExpr(Operands, AddRec->getLoop(), 3075 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3076 } 3077 } 3078 } 3079 } 3080 3081 // Skip over the add expression until we get to a multiply. 3082 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3083 ++Idx; 3084 3085 // If there are mul operands inline them all into this expression. 3086 if (Idx < Ops.size()) { 3087 bool DeletedMul = false; 3088 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3089 if (Ops.size() > MulOpsInlineThreshold) 3090 break; 3091 // If we have an mul, expand the mul operands onto the end of the 3092 // operands list. 3093 Ops.erase(Ops.begin()+Idx); 3094 Ops.append(Mul->op_begin(), Mul->op_end()); 3095 DeletedMul = true; 3096 } 3097 3098 // If we deleted at least one mul, we added operands to the end of the 3099 // list, and they are not necessarily sorted. Recurse to resort and 3100 // resimplify any operands we just acquired. 3101 if (DeletedMul) 3102 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3103 } 3104 3105 // If there are any add recurrences in the operands list, see if any other 3106 // added values are loop invariant. If so, we can fold them into the 3107 // recurrence. 3108 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3109 ++Idx; 3110 3111 // Scan over all recurrences, trying to fold loop invariants into them. 3112 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3113 // Scan all of the other operands to this mul and add them to the vector 3114 // if they are loop invariant w.r.t. the recurrence. 3115 SmallVector<const SCEV *, 8> LIOps; 3116 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3117 const Loop *AddRecLoop = AddRec->getLoop(); 3118 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3119 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3120 LIOps.push_back(Ops[i]); 3121 Ops.erase(Ops.begin()+i); 3122 --i; --e; 3123 } 3124 3125 // If we found some loop invariants, fold them into the recurrence. 3126 if (!LIOps.empty()) { 3127 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3128 SmallVector<const SCEV *, 4> NewOps; 3129 NewOps.reserve(AddRec->getNumOperands()); 3130 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3131 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3132 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3133 SCEV::FlagAnyWrap, Depth + 1)); 3134 3135 // Build the new addrec. Propagate the NUW and NSW flags if both the 3136 // outer mul and the inner addrec are guaranteed to have no overflow. 3137 // 3138 // No self-wrap cannot be guaranteed after changing the step size, but 3139 // will be inferred if either NUW or NSW is true. 3140 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3141 const SCEV *NewRec = getAddRecExpr( 3142 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3143 3144 // If all of the other operands were loop invariant, we are done. 3145 if (Ops.size() == 1) return NewRec; 3146 3147 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3148 for (unsigned i = 0;; ++i) 3149 if (Ops[i] == AddRec) { 3150 Ops[i] = NewRec; 3151 break; 3152 } 3153 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3154 } 3155 3156 // Okay, if there weren't any loop invariants to be folded, check to see 3157 // if there are multiple AddRec's with the same loop induction variable 3158 // being multiplied together. If so, we can fold them. 3159 3160 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3161 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3162 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3163 // ]]],+,...up to x=2n}. 3164 // Note that the arguments to choose() are always integers with values 3165 // known at compile time, never SCEV objects. 3166 // 3167 // The implementation avoids pointless extra computations when the two 3168 // addrec's are of different length (mathematically, it's equivalent to 3169 // an infinite stream of zeros on the right). 3170 bool OpsModified = false; 3171 for (unsigned OtherIdx = Idx+1; 3172 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3173 ++OtherIdx) { 3174 const SCEVAddRecExpr *OtherAddRec = 3175 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3176 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3177 continue; 3178 3179 // Limit max number of arguments to avoid creation of unreasonably big 3180 // SCEVAddRecs with very complex operands. 3181 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3182 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3183 continue; 3184 3185 bool Overflow = false; 3186 Type *Ty = AddRec->getType(); 3187 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3188 SmallVector<const SCEV*, 7> AddRecOps; 3189 for (int x = 0, xe = AddRec->getNumOperands() + 3190 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3191 SmallVector <const SCEV *, 7> SumOps; 3192 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3193 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3194 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3195 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3196 z < ze && !Overflow; ++z) { 3197 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3198 uint64_t Coeff; 3199 if (LargerThan64Bits) 3200 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3201 else 3202 Coeff = Coeff1*Coeff2; 3203 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3204 const SCEV *Term1 = AddRec->getOperand(y-z); 3205 const SCEV *Term2 = OtherAddRec->getOperand(z); 3206 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3207 SCEV::FlagAnyWrap, Depth + 1)); 3208 } 3209 } 3210 if (SumOps.empty()) 3211 SumOps.push_back(getZero(Ty)); 3212 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3213 } 3214 if (!Overflow) { 3215 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3216 SCEV::FlagAnyWrap); 3217 if (Ops.size() == 2) return NewAddRec; 3218 Ops[Idx] = NewAddRec; 3219 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3220 OpsModified = true; 3221 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3222 if (!AddRec) 3223 break; 3224 } 3225 } 3226 if (OpsModified) 3227 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3228 3229 // Otherwise couldn't fold anything into this recurrence. Move onto the 3230 // next one. 3231 } 3232 3233 // Okay, it looks like we really DO need an mul expr. Check to see if we 3234 // already have one, otherwise create a new one. 3235 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3236 } 3237 3238 /// Represents an unsigned remainder expression based on unsigned division. 3239 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3240 const SCEV *RHS) { 3241 assert(getEffectiveSCEVType(LHS->getType()) == 3242 getEffectiveSCEVType(RHS->getType()) && 3243 "SCEVURemExpr operand types don't match!"); 3244 3245 // Short-circuit easy cases 3246 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3247 // If constant is one, the result is trivial 3248 if (RHSC->getValue()->isOne()) 3249 return getZero(LHS->getType()); // X urem 1 --> 0 3250 3251 // If constant is a power of two, fold into a zext(trunc(LHS)). 3252 if (RHSC->getAPInt().isPowerOf2()) { 3253 Type *FullTy = LHS->getType(); 3254 Type *TruncTy = 3255 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3256 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3257 } 3258 } 3259 3260 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3261 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3262 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3263 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3264 } 3265 3266 /// Get a canonical unsigned division expression, or something simpler if 3267 /// possible. 3268 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3269 const SCEV *RHS) { 3270 assert(!LHS->getType()->isPointerTy() && 3271 "SCEVUDivExpr operand can't be pointer!"); 3272 assert(LHS->getType() == RHS->getType() && 3273 "SCEVUDivExpr operand types don't match!"); 3274 3275 FoldingSetNodeID ID; 3276 ID.AddInteger(scUDivExpr); 3277 ID.AddPointer(LHS); 3278 ID.AddPointer(RHS); 3279 void *IP = nullptr; 3280 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3281 return S; 3282 3283 // 0 udiv Y == 0 3284 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3285 if (LHSC->getValue()->isZero()) 3286 return LHS; 3287 3288 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3289 if (RHSC->getValue()->isOne()) 3290 return LHS; // X udiv 1 --> x 3291 // If the denominator is zero, the result of the udiv is undefined. Don't 3292 // try to analyze it, because the resolution chosen here may differ from 3293 // the resolution chosen in other parts of the compiler. 3294 if (!RHSC->getValue()->isZero()) { 3295 // Determine if the division can be folded into the operands of 3296 // its operands. 3297 // TODO: Generalize this to non-constants by using known-bits information. 3298 Type *Ty = LHS->getType(); 3299 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3300 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3301 // For non-power-of-two values, effectively round the value up to the 3302 // nearest power of two. 3303 if (!RHSC->getAPInt().isPowerOf2()) 3304 ++MaxShiftAmt; 3305 IntegerType *ExtTy = 3306 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3307 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3308 if (const SCEVConstant *Step = 3309 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3310 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3311 const APInt &StepInt = Step->getAPInt(); 3312 const APInt &DivInt = RHSC->getAPInt(); 3313 if (!StepInt.urem(DivInt) && 3314 getZeroExtendExpr(AR, ExtTy) == 3315 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3316 getZeroExtendExpr(Step, ExtTy), 3317 AR->getLoop(), SCEV::FlagAnyWrap)) { 3318 SmallVector<const SCEV *, 4> Operands; 3319 for (const SCEV *Op : AR->operands()) 3320 Operands.push_back(getUDivExpr(Op, RHS)); 3321 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3322 } 3323 /// Get a canonical UDivExpr for a recurrence. 3324 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3325 // We can currently only fold X%N if X is constant. 3326 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3327 if (StartC && !DivInt.urem(StepInt) && 3328 getZeroExtendExpr(AR, ExtTy) == 3329 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3330 getZeroExtendExpr(Step, ExtTy), 3331 AR->getLoop(), SCEV::FlagAnyWrap)) { 3332 const APInt &StartInt = StartC->getAPInt(); 3333 const APInt &StartRem = StartInt.urem(StepInt); 3334 if (StartRem != 0) { 3335 const SCEV *NewLHS = 3336 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3337 AR->getLoop(), SCEV::FlagNW); 3338 if (LHS != NewLHS) { 3339 LHS = NewLHS; 3340 3341 // Reset the ID to include the new LHS, and check if it is 3342 // already cached. 3343 ID.clear(); 3344 ID.AddInteger(scUDivExpr); 3345 ID.AddPointer(LHS); 3346 ID.AddPointer(RHS); 3347 IP = nullptr; 3348 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3349 return S; 3350 } 3351 } 3352 } 3353 } 3354 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3355 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3356 SmallVector<const SCEV *, 4> Operands; 3357 for (const SCEV *Op : M->operands()) 3358 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3359 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3360 // Find an operand that's safely divisible. 3361 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3362 const SCEV *Op = M->getOperand(i); 3363 const SCEV *Div = getUDivExpr(Op, RHSC); 3364 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3365 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3366 Operands[i] = Div; 3367 return getMulExpr(Operands); 3368 } 3369 } 3370 } 3371 3372 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3373 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3374 if (auto *DivisorConstant = 3375 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3376 bool Overflow = false; 3377 APInt NewRHS = 3378 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3379 if (Overflow) { 3380 return getConstant(RHSC->getType(), 0, false); 3381 } 3382 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3383 } 3384 } 3385 3386 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3387 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3388 SmallVector<const SCEV *, 4> Operands; 3389 for (const SCEV *Op : A->operands()) 3390 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3391 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3392 Operands.clear(); 3393 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3394 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3395 if (isa<SCEVUDivExpr>(Op) || 3396 getMulExpr(Op, RHS) != A->getOperand(i)) 3397 break; 3398 Operands.push_back(Op); 3399 } 3400 if (Operands.size() == A->getNumOperands()) 3401 return getAddExpr(Operands); 3402 } 3403 } 3404 3405 // Fold if both operands are constant. 3406 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3407 Constant *LHSCV = LHSC->getValue(); 3408 Constant *RHSCV = RHSC->getValue(); 3409 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3410 RHSCV))); 3411 } 3412 } 3413 } 3414 3415 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3416 // changes). Make sure we get a new one. 3417 IP = nullptr; 3418 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3419 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3420 LHS, RHS); 3421 UniqueSCEVs.InsertNode(S, IP); 3422 addToLoopUseLists(S); 3423 return S; 3424 } 3425 3426 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3427 APInt A = C1->getAPInt().abs(); 3428 APInt B = C2->getAPInt().abs(); 3429 uint32_t ABW = A.getBitWidth(); 3430 uint32_t BBW = B.getBitWidth(); 3431 3432 if (ABW > BBW) 3433 B = B.zext(ABW); 3434 else if (ABW < BBW) 3435 A = A.zext(BBW); 3436 3437 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3438 } 3439 3440 /// Get a canonical unsigned division expression, or something simpler if 3441 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3442 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3443 /// it's not exact because the udiv may be clearing bits. 3444 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3445 const SCEV *RHS) { 3446 // TODO: we could try to find factors in all sorts of things, but for now we 3447 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3448 // end of this file for inspiration. 3449 3450 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3451 if (!Mul || !Mul->hasNoUnsignedWrap()) 3452 return getUDivExpr(LHS, RHS); 3453 3454 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3455 // If the mulexpr multiplies by a constant, then that constant must be the 3456 // first element of the mulexpr. 3457 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3458 if (LHSCst == RHSCst) { 3459 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3460 return getMulExpr(Operands); 3461 } 3462 3463 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3464 // that there's a factor provided by one of the other terms. We need to 3465 // check. 3466 APInt Factor = gcd(LHSCst, RHSCst); 3467 if (!Factor.isIntN(1)) { 3468 LHSCst = 3469 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3470 RHSCst = 3471 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3472 SmallVector<const SCEV *, 2> Operands; 3473 Operands.push_back(LHSCst); 3474 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3475 LHS = getMulExpr(Operands); 3476 RHS = RHSCst; 3477 Mul = dyn_cast<SCEVMulExpr>(LHS); 3478 if (!Mul) 3479 return getUDivExactExpr(LHS, RHS); 3480 } 3481 } 3482 } 3483 3484 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3485 if (Mul->getOperand(i) == RHS) { 3486 SmallVector<const SCEV *, 2> Operands; 3487 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3488 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3489 return getMulExpr(Operands); 3490 } 3491 } 3492 3493 return getUDivExpr(LHS, RHS); 3494 } 3495 3496 /// Get an add recurrence expression for the specified loop. Simplify the 3497 /// expression as much as possible. 3498 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3499 const Loop *L, 3500 SCEV::NoWrapFlags Flags) { 3501 SmallVector<const SCEV *, 4> Operands; 3502 Operands.push_back(Start); 3503 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3504 if (StepChrec->getLoop() == L) { 3505 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3506 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3507 } 3508 3509 Operands.push_back(Step); 3510 return getAddRecExpr(Operands, L, Flags); 3511 } 3512 3513 /// Get an add recurrence expression for the specified loop. Simplify the 3514 /// expression as much as possible. 3515 const SCEV * 3516 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3517 const Loop *L, SCEV::NoWrapFlags Flags) { 3518 if (Operands.size() == 1) return Operands[0]; 3519 #ifndef NDEBUG 3520 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3521 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3522 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3523 "SCEVAddRecExpr operand types don't match!"); 3524 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3525 } 3526 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3527 assert(isLoopInvariant(Operands[i], L) && 3528 "SCEVAddRecExpr operand is not loop-invariant!"); 3529 #endif 3530 3531 if (Operands.back()->isZero()) { 3532 Operands.pop_back(); 3533 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3534 } 3535 3536 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3537 // use that information to infer NUW and NSW flags. However, computing a 3538 // BE count requires calling getAddRecExpr, so we may not yet have a 3539 // meaningful BE count at this point (and if we don't, we'd be stuck 3540 // with a SCEVCouldNotCompute as the cached BE count). 3541 3542 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3543 3544 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3545 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3546 const Loop *NestedLoop = NestedAR->getLoop(); 3547 if (L->contains(NestedLoop) 3548 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3549 : (!NestedLoop->contains(L) && 3550 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3551 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3552 Operands[0] = NestedAR->getStart(); 3553 // AddRecs require their operands be loop-invariant with respect to their 3554 // loops. Don't perform this transformation if it would break this 3555 // requirement. 3556 bool AllInvariant = all_of( 3557 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3558 3559 if (AllInvariant) { 3560 // Create a recurrence for the outer loop with the same step size. 3561 // 3562 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3563 // inner recurrence has the same property. 3564 SCEV::NoWrapFlags OuterFlags = 3565 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3566 3567 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3568 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3569 return isLoopInvariant(Op, NestedLoop); 3570 }); 3571 3572 if (AllInvariant) { 3573 // Ok, both add recurrences are valid after the transformation. 3574 // 3575 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3576 // the outer recurrence has the same property. 3577 SCEV::NoWrapFlags InnerFlags = 3578 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3579 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3580 } 3581 } 3582 // Reset Operands to its original state. 3583 Operands[0] = NestedAR; 3584 } 3585 } 3586 3587 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3588 // already have one, otherwise create a new one. 3589 return getOrCreateAddRecExpr(Operands, L, Flags); 3590 } 3591 3592 const SCEV * 3593 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3594 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3595 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3596 // getSCEV(Base)->getType() has the same address space as Base->getType() 3597 // because SCEV::getType() preserves the address space. 3598 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3599 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3600 // instruction to its SCEV, because the Instruction may be guarded by control 3601 // flow and the no-overflow bits may not be valid for the expression in any 3602 // context. This can be fixed similarly to how these flags are handled for 3603 // adds. 3604 SCEV::NoWrapFlags OffsetWrap = 3605 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3606 3607 Type *CurTy = GEP->getType(); 3608 bool FirstIter = true; 3609 SmallVector<const SCEV *, 4> Offsets; 3610 for (const SCEV *IndexExpr : IndexExprs) { 3611 // Compute the (potentially symbolic) offset in bytes for this index. 3612 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3613 // For a struct, add the member offset. 3614 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3615 unsigned FieldNo = Index->getZExtValue(); 3616 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3617 Offsets.push_back(FieldOffset); 3618 3619 // Update CurTy to the type of the field at Index. 3620 CurTy = STy->getTypeAtIndex(Index); 3621 } else { 3622 // Update CurTy to its element type. 3623 if (FirstIter) { 3624 assert(isa<PointerType>(CurTy) && 3625 "The first index of a GEP indexes a pointer"); 3626 CurTy = GEP->getSourceElementType(); 3627 FirstIter = false; 3628 } else { 3629 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3630 } 3631 // For an array, add the element offset, explicitly scaled. 3632 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3633 // Getelementptr indices are signed. 3634 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3635 3636 // Multiply the index by the element size to compute the element offset. 3637 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3638 Offsets.push_back(LocalOffset); 3639 } 3640 } 3641 3642 // Handle degenerate case of GEP without offsets. 3643 if (Offsets.empty()) 3644 return BaseExpr; 3645 3646 // Add the offsets together, assuming nsw if inbounds. 3647 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3648 // Add the base address and the offset. We cannot use the nsw flag, as the 3649 // base address is unsigned. However, if we know that the offset is 3650 // non-negative, we can use nuw. 3651 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3652 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3653 return getAddExpr(BaseExpr, Offset, BaseWrap); 3654 } 3655 3656 std::tuple<SCEV *, FoldingSetNodeID, void *> 3657 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3658 ArrayRef<const SCEV *> Ops) { 3659 FoldingSetNodeID ID; 3660 void *IP = nullptr; 3661 ID.AddInteger(SCEVType); 3662 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3663 ID.AddPointer(Ops[i]); 3664 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3665 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3666 } 3667 3668 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3669 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3670 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3671 } 3672 3673 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3674 SmallVectorImpl<const SCEV *> &Ops) { 3675 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3676 if (Ops.size() == 1) return Ops[0]; 3677 #ifndef NDEBUG 3678 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3679 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3680 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3681 "Operand types don't match!"); 3682 assert(Ops[0]->getType()->isPointerTy() == 3683 Ops[i]->getType()->isPointerTy() && 3684 "min/max should be consistently pointerish"); 3685 } 3686 #endif 3687 3688 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3689 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3690 3691 // Sort by complexity, this groups all similar expression types together. 3692 GroupByComplexity(Ops, &LI, DT); 3693 3694 // Check if we have created the same expression before. 3695 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3696 return S; 3697 } 3698 3699 // If there are any constants, fold them together. 3700 unsigned Idx = 0; 3701 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3702 ++Idx; 3703 assert(Idx < Ops.size()); 3704 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3705 if (Kind == scSMaxExpr) 3706 return APIntOps::smax(LHS, RHS); 3707 else if (Kind == scSMinExpr) 3708 return APIntOps::smin(LHS, RHS); 3709 else if (Kind == scUMaxExpr) 3710 return APIntOps::umax(LHS, RHS); 3711 else if (Kind == scUMinExpr) 3712 return APIntOps::umin(LHS, RHS); 3713 llvm_unreachable("Unknown SCEV min/max opcode"); 3714 }; 3715 3716 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3717 // We found two constants, fold them together! 3718 ConstantInt *Fold = ConstantInt::get( 3719 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3720 Ops[0] = getConstant(Fold); 3721 Ops.erase(Ops.begin()+1); // Erase the folded element 3722 if (Ops.size() == 1) return Ops[0]; 3723 LHSC = cast<SCEVConstant>(Ops[0]); 3724 } 3725 3726 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3727 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3728 3729 if (IsMax ? IsMinV : IsMaxV) { 3730 // If we are left with a constant minimum(/maximum)-int, strip it off. 3731 Ops.erase(Ops.begin()); 3732 --Idx; 3733 } else if (IsMax ? IsMaxV : IsMinV) { 3734 // If we have a max(/min) with a constant maximum(/minimum)-int, 3735 // it will always be the extremum. 3736 return LHSC; 3737 } 3738 3739 if (Ops.size() == 1) return Ops[0]; 3740 } 3741 3742 // Find the first operation of the same kind 3743 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3744 ++Idx; 3745 3746 // Check to see if one of the operands is of the same kind. If so, expand its 3747 // operands onto our operand list, and recurse to simplify. 3748 if (Idx < Ops.size()) { 3749 bool DeletedAny = false; 3750 while (Ops[Idx]->getSCEVType() == Kind) { 3751 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3752 Ops.erase(Ops.begin()+Idx); 3753 Ops.append(SMME->op_begin(), SMME->op_end()); 3754 DeletedAny = true; 3755 } 3756 3757 if (DeletedAny) 3758 return getMinMaxExpr(Kind, Ops); 3759 } 3760 3761 // Okay, check to see if the same value occurs in the operand list twice. If 3762 // so, delete one. Since we sorted the list, these values are required to 3763 // be adjacent. 3764 llvm::CmpInst::Predicate GEPred = 3765 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3766 llvm::CmpInst::Predicate LEPred = 3767 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3768 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3769 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3770 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3771 if (Ops[i] == Ops[i + 1] || 3772 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3773 // X op Y op Y --> X op Y 3774 // X op Y --> X, if we know X, Y are ordered appropriately 3775 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3776 --i; 3777 --e; 3778 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3779 Ops[i + 1])) { 3780 // X op Y --> Y, if we know X, Y are ordered appropriately 3781 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3782 --i; 3783 --e; 3784 } 3785 } 3786 3787 if (Ops.size() == 1) return Ops[0]; 3788 3789 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3790 3791 // Okay, it looks like we really DO need an expr. Check to see if we 3792 // already have one, otherwise create a new one. 3793 const SCEV *ExistingSCEV; 3794 FoldingSetNodeID ID; 3795 void *IP; 3796 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3797 if (ExistingSCEV) 3798 return ExistingSCEV; 3799 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3800 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3801 SCEV *S = new (SCEVAllocator) 3802 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3803 3804 UniqueSCEVs.InsertNode(S, IP); 3805 addToLoopUseLists(S); 3806 return S; 3807 } 3808 3809 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3810 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3811 return getSMaxExpr(Ops); 3812 } 3813 3814 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3815 return getMinMaxExpr(scSMaxExpr, Ops); 3816 } 3817 3818 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3819 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3820 return getUMaxExpr(Ops); 3821 } 3822 3823 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3824 return getMinMaxExpr(scUMaxExpr, Ops); 3825 } 3826 3827 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3828 const SCEV *RHS) { 3829 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3830 return getSMinExpr(Ops); 3831 } 3832 3833 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3834 return getMinMaxExpr(scSMinExpr, Ops); 3835 } 3836 3837 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3838 const SCEV *RHS) { 3839 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3840 return getUMinExpr(Ops); 3841 } 3842 3843 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3844 return getMinMaxExpr(scUMinExpr, Ops); 3845 } 3846 3847 const SCEV * 3848 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3849 ScalableVectorType *ScalableTy) { 3850 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3851 Constant *One = ConstantInt::get(IntTy, 1); 3852 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3853 // Note that the expression we created is the final expression, we don't 3854 // want to simplify it any further Also, if we call a normal getSCEV(), 3855 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3856 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3857 } 3858 3859 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3860 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3861 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3862 // We can bypass creating a target-independent constant expression and then 3863 // folding it back into a ConstantInt. This is just a compile-time 3864 // optimization. 3865 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3866 } 3867 3868 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3869 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3870 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3871 // We can bypass creating a target-independent constant expression and then 3872 // folding it back into a ConstantInt. This is just a compile-time 3873 // optimization. 3874 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3875 } 3876 3877 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3878 StructType *STy, 3879 unsigned FieldNo) { 3880 // We can bypass creating a target-independent constant expression and then 3881 // folding it back into a ConstantInt. This is just a compile-time 3882 // optimization. 3883 return getConstant( 3884 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3885 } 3886 3887 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3888 // Don't attempt to do anything other than create a SCEVUnknown object 3889 // here. createSCEV only calls getUnknown after checking for all other 3890 // interesting possibilities, and any other code that calls getUnknown 3891 // is doing so in order to hide a value from SCEV canonicalization. 3892 3893 FoldingSetNodeID ID; 3894 ID.AddInteger(scUnknown); 3895 ID.AddPointer(V); 3896 void *IP = nullptr; 3897 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3898 assert(cast<SCEVUnknown>(S)->getValue() == V && 3899 "Stale SCEVUnknown in uniquing map!"); 3900 return S; 3901 } 3902 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3903 FirstUnknown); 3904 FirstUnknown = cast<SCEVUnknown>(S); 3905 UniqueSCEVs.InsertNode(S, IP); 3906 return S; 3907 } 3908 3909 //===----------------------------------------------------------------------===// 3910 // Basic SCEV Analysis and PHI Idiom Recognition Code 3911 // 3912 3913 /// Test if values of the given type are analyzable within the SCEV 3914 /// framework. This primarily includes integer types, and it can optionally 3915 /// include pointer types if the ScalarEvolution class has access to 3916 /// target-specific information. 3917 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3918 // Integers and pointers are always SCEVable. 3919 return Ty->isIntOrPtrTy(); 3920 } 3921 3922 /// Return the size in bits of the specified type, for which isSCEVable must 3923 /// return true. 3924 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3925 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3926 if (Ty->isPointerTy()) 3927 return getDataLayout().getIndexTypeSizeInBits(Ty); 3928 return getDataLayout().getTypeSizeInBits(Ty); 3929 } 3930 3931 /// Return a type with the same bitwidth as the given type and which represents 3932 /// how SCEV will treat the given type, for which isSCEVable must return 3933 /// true. For pointer types, this is the pointer index sized integer type. 3934 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3935 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3936 3937 if (Ty->isIntegerTy()) 3938 return Ty; 3939 3940 // The only other support type is pointer. 3941 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3942 return getDataLayout().getIndexType(Ty); 3943 } 3944 3945 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3946 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3947 } 3948 3949 const SCEV *ScalarEvolution::getCouldNotCompute() { 3950 return CouldNotCompute.get(); 3951 } 3952 3953 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3954 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3955 auto *SU = dyn_cast<SCEVUnknown>(S); 3956 return SU && SU->getValue() == nullptr; 3957 }); 3958 3959 return !ContainsNulls; 3960 } 3961 3962 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3963 HasRecMapType::iterator I = HasRecMap.find(S); 3964 if (I != HasRecMap.end()) 3965 return I->second; 3966 3967 bool FoundAddRec = 3968 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3969 HasRecMap.insert({S, FoundAddRec}); 3970 return FoundAddRec; 3971 } 3972 3973 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3974 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3975 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3976 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3977 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3978 if (!Add) 3979 return {S, nullptr}; 3980 3981 if (Add->getNumOperands() != 2) 3982 return {S, nullptr}; 3983 3984 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3985 if (!ConstOp) 3986 return {S, nullptr}; 3987 3988 return {Add->getOperand(1), ConstOp->getValue()}; 3989 } 3990 3991 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3992 /// by the value and offset from any ValueOffsetPair in the set. 3993 ScalarEvolution::ValueOffsetPairSetVector * 3994 ScalarEvolution::getSCEVValues(const SCEV *S) { 3995 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3996 if (SI == ExprValueMap.end()) 3997 return nullptr; 3998 #ifndef NDEBUG 3999 if (VerifySCEVMap) { 4000 // Check there is no dangling Value in the set returned. 4001 for (const auto &VE : SI->second) 4002 assert(ValueExprMap.count(VE.first)); 4003 } 4004 #endif 4005 return &SI->second; 4006 } 4007 4008 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4009 /// cannot be used separately. eraseValueFromMap should be used to remove 4010 /// V from ValueExprMap and ExprValueMap at the same time. 4011 void ScalarEvolution::eraseValueFromMap(Value *V) { 4012 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4013 if (I != ValueExprMap.end()) { 4014 const SCEV *S = I->second; 4015 // Remove {V, 0} from the set of ExprValueMap[S] 4016 if (auto *SV = getSCEVValues(S)) 4017 SV->remove({V, nullptr}); 4018 4019 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4020 const SCEV *Stripped; 4021 ConstantInt *Offset; 4022 std::tie(Stripped, Offset) = splitAddExpr(S); 4023 if (Offset != nullptr) { 4024 if (auto *SV = getSCEVValues(Stripped)) 4025 SV->remove({V, Offset}); 4026 } 4027 ValueExprMap.erase(V); 4028 } 4029 } 4030 4031 /// Check whether value has nuw/nsw/exact set but SCEV does not. 4032 /// TODO: In reality it is better to check the poison recursively 4033 /// but this is better than nothing. 4034 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 4035 if (auto *I = dyn_cast<Instruction>(V)) { 4036 if (isa<OverflowingBinaryOperator>(I)) { 4037 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 4038 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 4039 return true; 4040 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 4041 return true; 4042 } 4043 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 4044 return true; 4045 } 4046 return false; 4047 } 4048 4049 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4050 /// create a new one. 4051 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4052 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4053 4054 const SCEV *S = getExistingSCEV(V); 4055 if (S == nullptr) { 4056 S = createSCEV(V); 4057 // During PHI resolution, it is possible to create two SCEVs for the same 4058 // V, so it is needed to double check whether V->S is inserted into 4059 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4060 std::pair<ValueExprMapType::iterator, bool> Pair = 4061 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4062 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 4063 ExprValueMap[S].insert({V, nullptr}); 4064 4065 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4066 // ExprValueMap. 4067 const SCEV *Stripped = S; 4068 ConstantInt *Offset = nullptr; 4069 std::tie(Stripped, Offset) = splitAddExpr(S); 4070 // If stripped is SCEVUnknown, don't bother to save 4071 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4072 // increase the complexity of the expansion code. 4073 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4074 // because it may generate add/sub instead of GEP in SCEV expansion. 4075 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4076 !isa<GetElementPtrInst>(V)) 4077 ExprValueMap[Stripped].insert({V, Offset}); 4078 } 4079 } 4080 return S; 4081 } 4082 4083 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4084 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4085 4086 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4087 if (I != ValueExprMap.end()) { 4088 const SCEV *S = I->second; 4089 if (checkValidity(S)) 4090 return S; 4091 eraseValueFromMap(V); 4092 forgetMemoizedResults(S); 4093 } 4094 return nullptr; 4095 } 4096 4097 /// Return a SCEV corresponding to -V = -1*V 4098 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4099 SCEV::NoWrapFlags Flags) { 4100 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4101 return getConstant( 4102 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4103 4104 Type *Ty = V->getType(); 4105 Ty = getEffectiveSCEVType(Ty); 4106 return getMulExpr(V, getMinusOne(Ty), Flags); 4107 } 4108 4109 /// If Expr computes ~A, return A else return nullptr 4110 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4111 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4112 if (!Add || Add->getNumOperands() != 2 || 4113 !Add->getOperand(0)->isAllOnesValue()) 4114 return nullptr; 4115 4116 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4117 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4118 !AddRHS->getOperand(0)->isAllOnesValue()) 4119 return nullptr; 4120 4121 return AddRHS->getOperand(1); 4122 } 4123 4124 /// Return a SCEV corresponding to ~V = -1-V 4125 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4126 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4127 return getConstant( 4128 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4129 4130 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4131 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4132 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4133 SmallVector<const SCEV *, 2> MatchedOperands; 4134 for (const SCEV *Operand : MME->operands()) { 4135 const SCEV *Matched = MatchNotExpr(Operand); 4136 if (!Matched) 4137 return (const SCEV *)nullptr; 4138 MatchedOperands.push_back(Matched); 4139 } 4140 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4141 MatchedOperands); 4142 }; 4143 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4144 return Replaced; 4145 } 4146 4147 Type *Ty = V->getType(); 4148 Ty = getEffectiveSCEVType(Ty); 4149 return getMinusSCEV(getMinusOne(Ty), V); 4150 } 4151 4152 /// Compute an expression equivalent to S - getPointerBase(S). 4153 static const SCEV *removePointerBase(ScalarEvolution *SE, const SCEV *P) { 4154 assert(P->getType()->isPointerTy()); 4155 4156 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4157 // The base of an AddRec is the first operand. 4158 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4159 Ops[0] = removePointerBase(SE, Ops[0]); 4160 // Don't try to transfer nowrap flags for now. We could in some cases 4161 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4162 return SE->getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4163 } 4164 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4165 // The base of an Add is the pointer operand. 4166 SmallVector<const SCEV *> Ops{Add->operands()}; 4167 const SCEV **PtrOp = nullptr; 4168 for (const SCEV *&AddOp : Ops) { 4169 if (AddOp->getType()->isPointerTy()) { 4170 // If we find an Add with multiple pointer operands, treat it as a 4171 // pointer base to be consistent with getPointerBase. Eventually 4172 // we should be able to assert this is impossible. 4173 if (PtrOp) 4174 return SE->getZero(P->getType()); 4175 PtrOp = &AddOp; 4176 } 4177 } 4178 *PtrOp = removePointerBase(SE, *PtrOp); 4179 // Don't try to transfer nowrap flags for now. We could in some cases 4180 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4181 return SE->getAddExpr(Ops); 4182 } 4183 // Any other expression must be a pointer base. 4184 return SE->getZero(P->getType()); 4185 } 4186 4187 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4188 SCEV::NoWrapFlags Flags, 4189 unsigned Depth) { 4190 // Fast path: X - X --> 0. 4191 if (LHS == RHS) 4192 return getZero(LHS->getType()); 4193 4194 // If we subtract two pointers with different pointer bases, bail. 4195 // Eventually, we're going to add an assertion to getMulExpr that we 4196 // can't multiply by a pointer. 4197 if (RHS->getType()->isPointerTy()) { 4198 if (!LHS->getType()->isPointerTy() || 4199 getPointerBase(LHS) != getPointerBase(RHS)) 4200 return getCouldNotCompute(); 4201 LHS = removePointerBase(this, LHS); 4202 RHS = removePointerBase(this, RHS); 4203 } 4204 4205 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4206 // makes it so that we cannot make much use of NUW. 4207 auto AddFlags = SCEV::FlagAnyWrap; 4208 const bool RHSIsNotMinSigned = 4209 !getSignedRangeMin(RHS).isMinSignedValue(); 4210 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4211 // Let M be the minimum representable signed value. Then (-1)*RHS 4212 // signed-wraps if and only if RHS is M. That can happen even for 4213 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4214 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4215 // (-1)*RHS, we need to prove that RHS != M. 4216 // 4217 // If LHS is non-negative and we know that LHS - RHS does not 4218 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4219 // either by proving that RHS > M or that LHS >= 0. 4220 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4221 AddFlags = SCEV::FlagNSW; 4222 } 4223 } 4224 4225 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4226 // RHS is NSW and LHS >= 0. 4227 // 4228 // The difficulty here is that the NSW flag may have been proven 4229 // relative to a loop that is to be found in a recurrence in LHS and 4230 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4231 // larger scope than intended. 4232 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4233 4234 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4235 } 4236 4237 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4238 unsigned Depth) { 4239 Type *SrcTy = V->getType(); 4240 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4241 "Cannot truncate or zero extend with non-integer arguments!"); 4242 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4243 return V; // No conversion 4244 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4245 return getTruncateExpr(V, Ty, Depth); 4246 return getZeroExtendExpr(V, Ty, Depth); 4247 } 4248 4249 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4250 unsigned Depth) { 4251 Type *SrcTy = V->getType(); 4252 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4253 "Cannot truncate or zero extend with non-integer arguments!"); 4254 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4255 return V; // No conversion 4256 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4257 return getTruncateExpr(V, Ty, Depth); 4258 return getSignExtendExpr(V, Ty, Depth); 4259 } 4260 4261 const SCEV * 4262 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4263 Type *SrcTy = V->getType(); 4264 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4265 "Cannot noop or zero extend with non-integer arguments!"); 4266 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4267 "getNoopOrZeroExtend cannot truncate!"); 4268 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4269 return V; // No conversion 4270 return getZeroExtendExpr(V, Ty); 4271 } 4272 4273 const SCEV * 4274 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4275 Type *SrcTy = V->getType(); 4276 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4277 "Cannot noop or sign extend with non-integer arguments!"); 4278 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4279 "getNoopOrSignExtend cannot truncate!"); 4280 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4281 return V; // No conversion 4282 return getSignExtendExpr(V, Ty); 4283 } 4284 4285 const SCEV * 4286 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4287 Type *SrcTy = V->getType(); 4288 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4289 "Cannot noop or any extend with non-integer arguments!"); 4290 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4291 "getNoopOrAnyExtend cannot truncate!"); 4292 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4293 return V; // No conversion 4294 return getAnyExtendExpr(V, Ty); 4295 } 4296 4297 const SCEV * 4298 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4299 Type *SrcTy = V->getType(); 4300 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4301 "Cannot truncate or noop with non-integer arguments!"); 4302 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4303 "getTruncateOrNoop cannot extend!"); 4304 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4305 return V; // No conversion 4306 return getTruncateExpr(V, Ty); 4307 } 4308 4309 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4310 const SCEV *RHS) { 4311 const SCEV *PromotedLHS = LHS; 4312 const SCEV *PromotedRHS = RHS; 4313 4314 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4315 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4316 else 4317 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4318 4319 return getUMaxExpr(PromotedLHS, PromotedRHS); 4320 } 4321 4322 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4323 const SCEV *RHS) { 4324 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4325 return getUMinFromMismatchedTypes(Ops); 4326 } 4327 4328 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4329 SmallVectorImpl<const SCEV *> &Ops) { 4330 assert(!Ops.empty() && "At least one operand must be!"); 4331 // Trivial case. 4332 if (Ops.size() == 1) 4333 return Ops[0]; 4334 4335 // Find the max type first. 4336 Type *MaxType = nullptr; 4337 for (auto *S : Ops) 4338 if (MaxType) 4339 MaxType = getWiderType(MaxType, S->getType()); 4340 else 4341 MaxType = S->getType(); 4342 assert(MaxType && "Failed to find maximum type!"); 4343 4344 // Extend all ops to max type. 4345 SmallVector<const SCEV *, 2> PromotedOps; 4346 for (auto *S : Ops) 4347 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4348 4349 // Generate umin. 4350 return getUMinExpr(PromotedOps); 4351 } 4352 4353 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4354 // A pointer operand may evaluate to a nonpointer expression, such as null. 4355 if (!V->getType()->isPointerTy()) 4356 return V; 4357 4358 while (true) { 4359 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4360 V = AddRec->getStart(); 4361 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4362 const SCEV *PtrOp = nullptr; 4363 for (const SCEV *AddOp : Add->operands()) { 4364 if (AddOp->getType()->isPointerTy()) { 4365 // Cannot find the base of an expression with multiple pointer ops. 4366 if (PtrOp) 4367 return V; 4368 PtrOp = AddOp; 4369 } 4370 } 4371 if (!PtrOp) // All operands were non-pointer. 4372 return V; 4373 V = PtrOp; 4374 } else // Not something we can look further into. 4375 return V; 4376 } 4377 } 4378 4379 /// Push users of the given Instruction onto the given Worklist. 4380 static void 4381 PushDefUseChildren(Instruction *I, 4382 SmallVectorImpl<Instruction *> &Worklist) { 4383 // Push the def-use children onto the Worklist stack. 4384 for (User *U : I->users()) 4385 Worklist.push_back(cast<Instruction>(U)); 4386 } 4387 4388 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4389 SmallVector<Instruction *, 16> Worklist; 4390 PushDefUseChildren(PN, Worklist); 4391 4392 SmallPtrSet<Instruction *, 8> Visited; 4393 Visited.insert(PN); 4394 while (!Worklist.empty()) { 4395 Instruction *I = Worklist.pop_back_val(); 4396 if (!Visited.insert(I).second) 4397 continue; 4398 4399 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4400 if (It != ValueExprMap.end()) { 4401 const SCEV *Old = It->second; 4402 4403 // Short-circuit the def-use traversal if the symbolic name 4404 // ceases to appear in expressions. 4405 if (Old != SymName && !hasOperand(Old, SymName)) 4406 continue; 4407 4408 // SCEVUnknown for a PHI either means that it has an unrecognized 4409 // structure, it's a PHI that's in the progress of being computed 4410 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4411 // additional loop trip count information isn't going to change anything. 4412 // In the second case, createNodeForPHI will perform the necessary 4413 // updates on its own when it gets to that point. In the third, we do 4414 // want to forget the SCEVUnknown. 4415 if (!isa<PHINode>(I) || 4416 !isa<SCEVUnknown>(Old) || 4417 (I != PN && Old == SymName)) { 4418 eraseValueFromMap(It->first); 4419 forgetMemoizedResults(Old); 4420 } 4421 } 4422 4423 PushDefUseChildren(I, Worklist); 4424 } 4425 } 4426 4427 namespace { 4428 4429 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4430 /// expression in case its Loop is L. If it is not L then 4431 /// if IgnoreOtherLoops is true then use AddRec itself 4432 /// otherwise rewrite cannot be done. 4433 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4434 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4435 public: 4436 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4437 bool IgnoreOtherLoops = true) { 4438 SCEVInitRewriter Rewriter(L, SE); 4439 const SCEV *Result = Rewriter.visit(S); 4440 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4441 return SE.getCouldNotCompute(); 4442 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4443 ? SE.getCouldNotCompute() 4444 : Result; 4445 } 4446 4447 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4448 if (!SE.isLoopInvariant(Expr, L)) 4449 SeenLoopVariantSCEVUnknown = true; 4450 return Expr; 4451 } 4452 4453 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4454 // Only re-write AddRecExprs for this loop. 4455 if (Expr->getLoop() == L) 4456 return Expr->getStart(); 4457 SeenOtherLoops = true; 4458 return Expr; 4459 } 4460 4461 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4462 4463 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4464 4465 private: 4466 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4467 : SCEVRewriteVisitor(SE), L(L) {} 4468 4469 const Loop *L; 4470 bool SeenLoopVariantSCEVUnknown = false; 4471 bool SeenOtherLoops = false; 4472 }; 4473 4474 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4475 /// increment expression in case its Loop is L. If it is not L then 4476 /// use AddRec itself. 4477 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4478 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4479 public: 4480 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4481 SCEVPostIncRewriter Rewriter(L, SE); 4482 const SCEV *Result = Rewriter.visit(S); 4483 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4484 ? SE.getCouldNotCompute() 4485 : Result; 4486 } 4487 4488 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4489 if (!SE.isLoopInvariant(Expr, L)) 4490 SeenLoopVariantSCEVUnknown = true; 4491 return Expr; 4492 } 4493 4494 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4495 // Only re-write AddRecExprs for this loop. 4496 if (Expr->getLoop() == L) 4497 return Expr->getPostIncExpr(SE); 4498 SeenOtherLoops = true; 4499 return Expr; 4500 } 4501 4502 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4503 4504 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4505 4506 private: 4507 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4508 : SCEVRewriteVisitor(SE), L(L) {} 4509 4510 const Loop *L; 4511 bool SeenLoopVariantSCEVUnknown = false; 4512 bool SeenOtherLoops = false; 4513 }; 4514 4515 /// This class evaluates the compare condition by matching it against the 4516 /// condition of loop latch. If there is a match we assume a true value 4517 /// for the condition while building SCEV nodes. 4518 class SCEVBackedgeConditionFolder 4519 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4520 public: 4521 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4522 ScalarEvolution &SE) { 4523 bool IsPosBECond = false; 4524 Value *BECond = nullptr; 4525 if (BasicBlock *Latch = L->getLoopLatch()) { 4526 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4527 if (BI && BI->isConditional()) { 4528 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4529 "Both outgoing branches should not target same header!"); 4530 BECond = BI->getCondition(); 4531 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4532 } else { 4533 return S; 4534 } 4535 } 4536 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4537 return Rewriter.visit(S); 4538 } 4539 4540 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4541 const SCEV *Result = Expr; 4542 bool InvariantF = SE.isLoopInvariant(Expr, L); 4543 4544 if (!InvariantF) { 4545 Instruction *I = cast<Instruction>(Expr->getValue()); 4546 switch (I->getOpcode()) { 4547 case Instruction::Select: { 4548 SelectInst *SI = cast<SelectInst>(I); 4549 Optional<const SCEV *> Res = 4550 compareWithBackedgeCondition(SI->getCondition()); 4551 if (Res.hasValue()) { 4552 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4553 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4554 } 4555 break; 4556 } 4557 default: { 4558 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4559 if (Res.hasValue()) 4560 Result = Res.getValue(); 4561 break; 4562 } 4563 } 4564 } 4565 return Result; 4566 } 4567 4568 private: 4569 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4570 bool IsPosBECond, ScalarEvolution &SE) 4571 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4572 IsPositiveBECond(IsPosBECond) {} 4573 4574 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4575 4576 const Loop *L; 4577 /// Loop back condition. 4578 Value *BackedgeCond = nullptr; 4579 /// Set to true if loop back is on positive branch condition. 4580 bool IsPositiveBECond; 4581 }; 4582 4583 Optional<const SCEV *> 4584 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4585 4586 // If value matches the backedge condition for loop latch, 4587 // then return a constant evolution node based on loopback 4588 // branch taken. 4589 if (BackedgeCond == IC) 4590 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4591 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4592 return None; 4593 } 4594 4595 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4596 public: 4597 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4598 ScalarEvolution &SE) { 4599 SCEVShiftRewriter Rewriter(L, SE); 4600 const SCEV *Result = Rewriter.visit(S); 4601 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4602 } 4603 4604 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4605 // Only allow AddRecExprs for this loop. 4606 if (!SE.isLoopInvariant(Expr, L)) 4607 Valid = false; 4608 return Expr; 4609 } 4610 4611 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4612 if (Expr->getLoop() == L && Expr->isAffine()) 4613 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4614 Valid = false; 4615 return Expr; 4616 } 4617 4618 bool isValid() { return Valid; } 4619 4620 private: 4621 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4622 : SCEVRewriteVisitor(SE), L(L) {} 4623 4624 const Loop *L; 4625 bool Valid = true; 4626 }; 4627 4628 } // end anonymous namespace 4629 4630 SCEV::NoWrapFlags 4631 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4632 if (!AR->isAffine()) 4633 return SCEV::FlagAnyWrap; 4634 4635 using OBO = OverflowingBinaryOperator; 4636 4637 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4638 4639 if (!AR->hasNoSignedWrap()) { 4640 ConstantRange AddRecRange = getSignedRange(AR); 4641 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4642 4643 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4644 Instruction::Add, IncRange, OBO::NoSignedWrap); 4645 if (NSWRegion.contains(AddRecRange)) 4646 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4647 } 4648 4649 if (!AR->hasNoUnsignedWrap()) { 4650 ConstantRange AddRecRange = getUnsignedRange(AR); 4651 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4652 4653 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4654 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4655 if (NUWRegion.contains(AddRecRange)) 4656 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4657 } 4658 4659 return Result; 4660 } 4661 4662 SCEV::NoWrapFlags 4663 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4664 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4665 4666 if (AR->hasNoSignedWrap()) 4667 return Result; 4668 4669 if (!AR->isAffine()) 4670 return Result; 4671 4672 const SCEV *Step = AR->getStepRecurrence(*this); 4673 const Loop *L = AR->getLoop(); 4674 4675 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4676 // Note that this serves two purposes: It filters out loops that are 4677 // simply not analyzable, and it covers the case where this code is 4678 // being called from within backedge-taken count analysis, such that 4679 // attempting to ask for the backedge-taken count would likely result 4680 // in infinite recursion. In the later case, the analysis code will 4681 // cope with a conservative value, and it will take care to purge 4682 // that value once it has finished. 4683 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4684 4685 // Normally, in the cases we can prove no-overflow via a 4686 // backedge guarding condition, we can also compute a backedge 4687 // taken count for the loop. The exceptions are assumptions and 4688 // guards present in the loop -- SCEV is not great at exploiting 4689 // these to compute max backedge taken counts, but can still use 4690 // these to prove lack of overflow. Use this fact to avoid 4691 // doing extra work that may not pay off. 4692 4693 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4694 AC.assumptions().empty()) 4695 return Result; 4696 4697 // If the backedge is guarded by a comparison with the pre-inc value the 4698 // addrec is safe. Also, if the entry is guarded by a comparison with the 4699 // start value and the backedge is guarded by a comparison with the post-inc 4700 // value, the addrec is safe. 4701 ICmpInst::Predicate Pred; 4702 const SCEV *OverflowLimit = 4703 getSignedOverflowLimitForStep(Step, &Pred, this); 4704 if (OverflowLimit && 4705 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4706 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4707 Result = setFlags(Result, SCEV::FlagNSW); 4708 } 4709 return Result; 4710 } 4711 SCEV::NoWrapFlags 4712 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4713 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4714 4715 if (AR->hasNoUnsignedWrap()) 4716 return Result; 4717 4718 if (!AR->isAffine()) 4719 return Result; 4720 4721 const SCEV *Step = AR->getStepRecurrence(*this); 4722 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4723 const Loop *L = AR->getLoop(); 4724 4725 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4726 // Note that this serves two purposes: It filters out loops that are 4727 // simply not analyzable, and it covers the case where this code is 4728 // being called from within backedge-taken count analysis, such that 4729 // attempting to ask for the backedge-taken count would likely result 4730 // in infinite recursion. In the later case, the analysis code will 4731 // cope with a conservative value, and it will take care to purge 4732 // that value once it has finished. 4733 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4734 4735 // Normally, in the cases we can prove no-overflow via a 4736 // backedge guarding condition, we can also compute a backedge 4737 // taken count for the loop. The exceptions are assumptions and 4738 // guards present in the loop -- SCEV is not great at exploiting 4739 // these to compute max backedge taken counts, but can still use 4740 // these to prove lack of overflow. Use this fact to avoid 4741 // doing extra work that may not pay off. 4742 4743 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4744 AC.assumptions().empty()) 4745 return Result; 4746 4747 // If the backedge is guarded by a comparison with the pre-inc value the 4748 // addrec is safe. Also, if the entry is guarded by a comparison with the 4749 // start value and the backedge is guarded by a comparison with the post-inc 4750 // value, the addrec is safe. 4751 if (isKnownPositive(Step)) { 4752 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4753 getUnsignedRangeMax(Step)); 4754 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4755 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4756 Result = setFlags(Result, SCEV::FlagNUW); 4757 } 4758 } 4759 4760 return Result; 4761 } 4762 4763 namespace { 4764 4765 /// Represents an abstract binary operation. This may exist as a 4766 /// normal instruction or constant expression, or may have been 4767 /// derived from an expression tree. 4768 struct BinaryOp { 4769 unsigned Opcode; 4770 Value *LHS; 4771 Value *RHS; 4772 bool IsNSW = false; 4773 bool IsNUW = false; 4774 4775 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4776 /// constant expression. 4777 Operator *Op = nullptr; 4778 4779 explicit BinaryOp(Operator *Op) 4780 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4781 Op(Op) { 4782 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4783 IsNSW = OBO->hasNoSignedWrap(); 4784 IsNUW = OBO->hasNoUnsignedWrap(); 4785 } 4786 } 4787 4788 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4789 bool IsNUW = false) 4790 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4791 }; 4792 4793 } // end anonymous namespace 4794 4795 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4796 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4797 auto *Op = dyn_cast<Operator>(V); 4798 if (!Op) 4799 return None; 4800 4801 // Implementation detail: all the cleverness here should happen without 4802 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4803 // SCEV expressions when possible, and we should not break that. 4804 4805 switch (Op->getOpcode()) { 4806 case Instruction::Add: 4807 case Instruction::Sub: 4808 case Instruction::Mul: 4809 case Instruction::UDiv: 4810 case Instruction::URem: 4811 case Instruction::And: 4812 case Instruction::Or: 4813 case Instruction::AShr: 4814 case Instruction::Shl: 4815 return BinaryOp(Op); 4816 4817 case Instruction::Xor: 4818 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4819 // If the RHS of the xor is a signmask, then this is just an add. 4820 // Instcombine turns add of signmask into xor as a strength reduction step. 4821 if (RHSC->getValue().isSignMask()) 4822 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4823 return BinaryOp(Op); 4824 4825 case Instruction::LShr: 4826 // Turn logical shift right of a constant into a unsigned divide. 4827 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4828 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4829 4830 // If the shift count is not less than the bitwidth, the result of 4831 // the shift is undefined. Don't try to analyze it, because the 4832 // resolution chosen here may differ from the resolution chosen in 4833 // other parts of the compiler. 4834 if (SA->getValue().ult(BitWidth)) { 4835 Constant *X = 4836 ConstantInt::get(SA->getContext(), 4837 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4838 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4839 } 4840 } 4841 return BinaryOp(Op); 4842 4843 case Instruction::ExtractValue: { 4844 auto *EVI = cast<ExtractValueInst>(Op); 4845 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4846 break; 4847 4848 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4849 if (!WO) 4850 break; 4851 4852 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4853 bool Signed = WO->isSigned(); 4854 // TODO: Should add nuw/nsw flags for mul as well. 4855 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4856 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4857 4858 // Now that we know that all uses of the arithmetic-result component of 4859 // CI are guarded by the overflow check, we can go ahead and pretend 4860 // that the arithmetic is non-overflowing. 4861 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4862 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4863 } 4864 4865 default: 4866 break; 4867 } 4868 4869 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4870 // semantics as a Sub, return a binary sub expression. 4871 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4872 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4873 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4874 4875 return None; 4876 } 4877 4878 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4879 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4880 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4881 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4882 /// follows one of the following patterns: 4883 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4884 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4885 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4886 /// we return the type of the truncation operation, and indicate whether the 4887 /// truncated type should be treated as signed/unsigned by setting 4888 /// \p Signed to true/false, respectively. 4889 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4890 bool &Signed, ScalarEvolution &SE) { 4891 // The case where Op == SymbolicPHI (that is, with no type conversions on 4892 // the way) is handled by the regular add recurrence creating logic and 4893 // would have already been triggered in createAddRecForPHI. Reaching it here 4894 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4895 // because one of the other operands of the SCEVAddExpr updating this PHI is 4896 // not invariant). 4897 // 4898 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4899 // this case predicates that allow us to prove that Op == SymbolicPHI will 4900 // be added. 4901 if (Op == SymbolicPHI) 4902 return nullptr; 4903 4904 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4905 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4906 if (SourceBits != NewBits) 4907 return nullptr; 4908 4909 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4910 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4911 if (!SExt && !ZExt) 4912 return nullptr; 4913 const SCEVTruncateExpr *Trunc = 4914 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4915 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4916 if (!Trunc) 4917 return nullptr; 4918 const SCEV *X = Trunc->getOperand(); 4919 if (X != SymbolicPHI) 4920 return nullptr; 4921 Signed = SExt != nullptr; 4922 return Trunc->getType(); 4923 } 4924 4925 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4926 if (!PN->getType()->isIntegerTy()) 4927 return nullptr; 4928 const Loop *L = LI.getLoopFor(PN->getParent()); 4929 if (!L || L->getHeader() != PN->getParent()) 4930 return nullptr; 4931 return L; 4932 } 4933 4934 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4935 // computation that updates the phi follows the following pattern: 4936 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4937 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4938 // If so, try to see if it can be rewritten as an AddRecExpr under some 4939 // Predicates. If successful, return them as a pair. Also cache the results 4940 // of the analysis. 4941 // 4942 // Example usage scenario: 4943 // Say the Rewriter is called for the following SCEV: 4944 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4945 // where: 4946 // %X = phi i64 (%Start, %BEValue) 4947 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4948 // and call this function with %SymbolicPHI = %X. 4949 // 4950 // The analysis will find that the value coming around the backedge has 4951 // the following SCEV: 4952 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4953 // Upon concluding that this matches the desired pattern, the function 4954 // will return the pair {NewAddRec, SmallPredsVec} where: 4955 // NewAddRec = {%Start,+,%Step} 4956 // SmallPredsVec = {P1, P2, P3} as follows: 4957 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4958 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4959 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4960 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4961 // under the predicates {P1,P2,P3}. 4962 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4963 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4964 // 4965 // TODO's: 4966 // 4967 // 1) Extend the Induction descriptor to also support inductions that involve 4968 // casts: When needed (namely, when we are called in the context of the 4969 // vectorizer induction analysis), a Set of cast instructions will be 4970 // populated by this method, and provided back to isInductionPHI. This is 4971 // needed to allow the vectorizer to properly record them to be ignored by 4972 // the cost model and to avoid vectorizing them (otherwise these casts, 4973 // which are redundant under the runtime overflow checks, will be 4974 // vectorized, which can be costly). 4975 // 4976 // 2) Support additional induction/PHISCEV patterns: We also want to support 4977 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4978 // after the induction update operation (the induction increment): 4979 // 4980 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4981 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4982 // 4983 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4984 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4985 // 4986 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4987 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4988 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4989 SmallVector<const SCEVPredicate *, 3> Predicates; 4990 4991 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4992 // return an AddRec expression under some predicate. 4993 4994 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4995 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4996 assert(L && "Expecting an integer loop header phi"); 4997 4998 // The loop may have multiple entrances or multiple exits; we can analyze 4999 // this phi as an addrec if it has a unique entry value and a unique 5000 // backedge value. 5001 Value *BEValueV = nullptr, *StartValueV = nullptr; 5002 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5003 Value *V = PN->getIncomingValue(i); 5004 if (L->contains(PN->getIncomingBlock(i))) { 5005 if (!BEValueV) { 5006 BEValueV = V; 5007 } else if (BEValueV != V) { 5008 BEValueV = nullptr; 5009 break; 5010 } 5011 } else if (!StartValueV) { 5012 StartValueV = V; 5013 } else if (StartValueV != V) { 5014 StartValueV = nullptr; 5015 break; 5016 } 5017 } 5018 if (!BEValueV || !StartValueV) 5019 return None; 5020 5021 const SCEV *BEValue = getSCEV(BEValueV); 5022 5023 // If the value coming around the backedge is an add with the symbolic 5024 // value we just inserted, possibly with casts that we can ignore under 5025 // an appropriate runtime guard, then we found a simple induction variable! 5026 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5027 if (!Add) 5028 return None; 5029 5030 // If there is a single occurrence of the symbolic value, possibly 5031 // casted, replace it with a recurrence. 5032 unsigned FoundIndex = Add->getNumOperands(); 5033 Type *TruncTy = nullptr; 5034 bool Signed; 5035 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5036 if ((TruncTy = 5037 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5038 if (FoundIndex == e) { 5039 FoundIndex = i; 5040 break; 5041 } 5042 5043 if (FoundIndex == Add->getNumOperands()) 5044 return None; 5045 5046 // Create an add with everything but the specified operand. 5047 SmallVector<const SCEV *, 8> Ops; 5048 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5049 if (i != FoundIndex) 5050 Ops.push_back(Add->getOperand(i)); 5051 const SCEV *Accum = getAddExpr(Ops); 5052 5053 // The runtime checks will not be valid if the step amount is 5054 // varying inside the loop. 5055 if (!isLoopInvariant(Accum, L)) 5056 return None; 5057 5058 // *** Part2: Create the predicates 5059 5060 // Analysis was successful: we have a phi-with-cast pattern for which we 5061 // can return an AddRec expression under the following predicates: 5062 // 5063 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5064 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5065 // P2: An Equal predicate that guarantees that 5066 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5067 // P3: An Equal predicate that guarantees that 5068 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5069 // 5070 // As we next prove, the above predicates guarantee that: 5071 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5072 // 5073 // 5074 // More formally, we want to prove that: 5075 // Expr(i+1) = Start + (i+1) * Accum 5076 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5077 // 5078 // Given that: 5079 // 1) Expr(0) = Start 5080 // 2) Expr(1) = Start + Accum 5081 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5082 // 3) Induction hypothesis (step i): 5083 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5084 // 5085 // Proof: 5086 // Expr(i+1) = 5087 // = Start + (i+1)*Accum 5088 // = (Start + i*Accum) + Accum 5089 // = Expr(i) + Accum 5090 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5091 // :: from step i 5092 // 5093 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5094 // 5095 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5096 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5097 // + Accum :: from P3 5098 // 5099 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5100 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5101 // 5102 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5103 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5104 // 5105 // By induction, the same applies to all iterations 1<=i<n: 5106 // 5107 5108 // Create a truncated addrec for which we will add a no overflow check (P1). 5109 const SCEV *StartVal = getSCEV(StartValueV); 5110 const SCEV *PHISCEV = 5111 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5112 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5113 5114 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5115 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5116 // will be constant. 5117 // 5118 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5119 // add P1. 5120 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5121 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5122 Signed ? SCEVWrapPredicate::IncrementNSSW 5123 : SCEVWrapPredicate::IncrementNUSW; 5124 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5125 Predicates.push_back(AddRecPred); 5126 } 5127 5128 // Create the Equal Predicates P2,P3: 5129 5130 // It is possible that the predicates P2 and/or P3 are computable at 5131 // compile time due to StartVal and/or Accum being constants. 5132 // If either one is, then we can check that now and escape if either P2 5133 // or P3 is false. 5134 5135 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5136 // for each of StartVal and Accum 5137 auto getExtendedExpr = [&](const SCEV *Expr, 5138 bool CreateSignExtend) -> const SCEV * { 5139 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5140 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5141 const SCEV *ExtendedExpr = 5142 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5143 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5144 return ExtendedExpr; 5145 }; 5146 5147 // Given: 5148 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5149 // = getExtendedExpr(Expr) 5150 // Determine whether the predicate P: Expr == ExtendedExpr 5151 // is known to be false at compile time 5152 auto PredIsKnownFalse = [&](const SCEV *Expr, 5153 const SCEV *ExtendedExpr) -> bool { 5154 return Expr != ExtendedExpr && 5155 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5156 }; 5157 5158 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5159 if (PredIsKnownFalse(StartVal, StartExtended)) { 5160 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5161 return None; 5162 } 5163 5164 // The Step is always Signed (because the overflow checks are either 5165 // NSSW or NUSW) 5166 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5167 if (PredIsKnownFalse(Accum, AccumExtended)) { 5168 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5169 return None; 5170 } 5171 5172 auto AppendPredicate = [&](const SCEV *Expr, 5173 const SCEV *ExtendedExpr) -> void { 5174 if (Expr != ExtendedExpr && 5175 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5176 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5177 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5178 Predicates.push_back(Pred); 5179 } 5180 }; 5181 5182 AppendPredicate(StartVal, StartExtended); 5183 AppendPredicate(Accum, AccumExtended); 5184 5185 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5186 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5187 // into NewAR if it will also add the runtime overflow checks specified in 5188 // Predicates. 5189 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5190 5191 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5192 std::make_pair(NewAR, Predicates); 5193 // Remember the result of the analysis for this SCEV at this locayyytion. 5194 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5195 return PredRewrite; 5196 } 5197 5198 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5199 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5200 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5201 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5202 if (!L) 5203 return None; 5204 5205 // Check to see if we already analyzed this PHI. 5206 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5207 if (I != PredicatedSCEVRewrites.end()) { 5208 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5209 I->second; 5210 // Analysis was done before and failed to create an AddRec: 5211 if (Rewrite.first == SymbolicPHI) 5212 return None; 5213 // Analysis was done before and succeeded to create an AddRec under 5214 // a predicate: 5215 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5216 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5217 return Rewrite; 5218 } 5219 5220 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5221 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5222 5223 // Record in the cache that the analysis failed 5224 if (!Rewrite) { 5225 SmallVector<const SCEVPredicate *, 3> Predicates; 5226 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5227 return None; 5228 } 5229 5230 return Rewrite; 5231 } 5232 5233 // FIXME: This utility is currently required because the Rewriter currently 5234 // does not rewrite this expression: 5235 // {0, +, (sext ix (trunc iy to ix) to iy)} 5236 // into {0, +, %step}, 5237 // even when the following Equal predicate exists: 5238 // "%step == (sext ix (trunc iy to ix) to iy)". 5239 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5240 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5241 if (AR1 == AR2) 5242 return true; 5243 5244 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5245 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5246 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5247 return false; 5248 return true; 5249 }; 5250 5251 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5252 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5253 return false; 5254 return true; 5255 } 5256 5257 /// A helper function for createAddRecFromPHI to handle simple cases. 5258 /// 5259 /// This function tries to find an AddRec expression for the simplest (yet most 5260 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5261 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5262 /// technique for finding the AddRec expression. 5263 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5264 Value *BEValueV, 5265 Value *StartValueV) { 5266 const Loop *L = LI.getLoopFor(PN->getParent()); 5267 assert(L && L->getHeader() == PN->getParent()); 5268 assert(BEValueV && StartValueV); 5269 5270 auto BO = MatchBinaryOp(BEValueV, DT); 5271 if (!BO) 5272 return nullptr; 5273 5274 if (BO->Opcode != Instruction::Add) 5275 return nullptr; 5276 5277 const SCEV *Accum = nullptr; 5278 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5279 Accum = getSCEV(BO->RHS); 5280 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5281 Accum = getSCEV(BO->LHS); 5282 5283 if (!Accum) 5284 return nullptr; 5285 5286 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5287 if (BO->IsNUW) 5288 Flags = setFlags(Flags, SCEV::FlagNUW); 5289 if (BO->IsNSW) 5290 Flags = setFlags(Flags, SCEV::FlagNSW); 5291 5292 const SCEV *StartVal = getSCEV(StartValueV); 5293 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5294 5295 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5296 5297 // We can add Flags to the post-inc expression only if we 5298 // know that it is *undefined behavior* for BEValueV to 5299 // overflow. 5300 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5301 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5302 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5303 5304 return PHISCEV; 5305 } 5306 5307 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5308 const Loop *L = LI.getLoopFor(PN->getParent()); 5309 if (!L || L->getHeader() != PN->getParent()) 5310 return nullptr; 5311 5312 // The loop may have multiple entrances or multiple exits; we can analyze 5313 // this phi as an addrec if it has a unique entry value and a unique 5314 // backedge value. 5315 Value *BEValueV = nullptr, *StartValueV = nullptr; 5316 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5317 Value *V = PN->getIncomingValue(i); 5318 if (L->contains(PN->getIncomingBlock(i))) { 5319 if (!BEValueV) { 5320 BEValueV = V; 5321 } else if (BEValueV != V) { 5322 BEValueV = nullptr; 5323 break; 5324 } 5325 } else if (!StartValueV) { 5326 StartValueV = V; 5327 } else if (StartValueV != V) { 5328 StartValueV = nullptr; 5329 break; 5330 } 5331 } 5332 if (!BEValueV || !StartValueV) 5333 return nullptr; 5334 5335 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5336 "PHI node already processed?"); 5337 5338 // First, try to find AddRec expression without creating a fictituos symbolic 5339 // value for PN. 5340 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5341 return S; 5342 5343 // Handle PHI node value symbolically. 5344 const SCEV *SymbolicName = getUnknown(PN); 5345 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5346 5347 // Using this symbolic name for the PHI, analyze the value coming around 5348 // the back-edge. 5349 const SCEV *BEValue = getSCEV(BEValueV); 5350 5351 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5352 // has a special value for the first iteration of the loop. 5353 5354 // If the value coming around the backedge is an add with the symbolic 5355 // value we just inserted, then we found a simple induction variable! 5356 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5357 // If there is a single occurrence of the symbolic value, replace it 5358 // with a recurrence. 5359 unsigned FoundIndex = Add->getNumOperands(); 5360 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5361 if (Add->getOperand(i) == SymbolicName) 5362 if (FoundIndex == e) { 5363 FoundIndex = i; 5364 break; 5365 } 5366 5367 if (FoundIndex != Add->getNumOperands()) { 5368 // Create an add with everything but the specified operand. 5369 SmallVector<const SCEV *, 8> Ops; 5370 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5371 if (i != FoundIndex) 5372 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5373 L, *this)); 5374 const SCEV *Accum = getAddExpr(Ops); 5375 5376 // This is not a valid addrec if the step amount is varying each 5377 // loop iteration, but is not itself an addrec in this loop. 5378 if (isLoopInvariant(Accum, L) || 5379 (isa<SCEVAddRecExpr>(Accum) && 5380 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5381 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5382 5383 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5384 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5385 if (BO->IsNUW) 5386 Flags = setFlags(Flags, SCEV::FlagNUW); 5387 if (BO->IsNSW) 5388 Flags = setFlags(Flags, SCEV::FlagNSW); 5389 } 5390 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5391 // If the increment is an inbounds GEP, then we know the address 5392 // space cannot be wrapped around. We cannot make any guarantee 5393 // about signed or unsigned overflow because pointers are 5394 // unsigned but we may have a negative index from the base 5395 // pointer. We can guarantee that no unsigned wrap occurs if the 5396 // indices form a positive value. 5397 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5398 Flags = setFlags(Flags, SCEV::FlagNW); 5399 5400 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5401 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5402 Flags = setFlags(Flags, SCEV::FlagNUW); 5403 } 5404 5405 // We cannot transfer nuw and nsw flags from subtraction 5406 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5407 // for instance. 5408 } 5409 5410 const SCEV *StartVal = getSCEV(StartValueV); 5411 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5412 5413 // Okay, for the entire analysis of this edge we assumed the PHI 5414 // to be symbolic. We now need to go back and purge all of the 5415 // entries for the scalars that use the symbolic expression. 5416 forgetSymbolicName(PN, SymbolicName); 5417 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5418 5419 // We can add Flags to the post-inc expression only if we 5420 // know that it is *undefined behavior* for BEValueV to 5421 // overflow. 5422 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5423 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5424 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5425 5426 return PHISCEV; 5427 } 5428 } 5429 } else { 5430 // Otherwise, this could be a loop like this: 5431 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5432 // In this case, j = {1,+,1} and BEValue is j. 5433 // Because the other in-value of i (0) fits the evolution of BEValue 5434 // i really is an addrec evolution. 5435 // 5436 // We can generalize this saying that i is the shifted value of BEValue 5437 // by one iteration: 5438 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5439 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5440 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5441 if (Shifted != getCouldNotCompute() && 5442 Start != getCouldNotCompute()) { 5443 const SCEV *StartVal = getSCEV(StartValueV); 5444 if (Start == StartVal) { 5445 // Okay, for the entire analysis of this edge we assumed the PHI 5446 // to be symbolic. We now need to go back and purge all of the 5447 // entries for the scalars that use the symbolic expression. 5448 forgetSymbolicName(PN, SymbolicName); 5449 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5450 return Shifted; 5451 } 5452 } 5453 } 5454 5455 // Remove the temporary PHI node SCEV that has been inserted while intending 5456 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5457 // as it will prevent later (possibly simpler) SCEV expressions to be added 5458 // to the ValueExprMap. 5459 eraseValueFromMap(PN); 5460 5461 return nullptr; 5462 } 5463 5464 // Checks if the SCEV S is available at BB. S is considered available at BB 5465 // if S can be materialized at BB without introducing a fault. 5466 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5467 BasicBlock *BB) { 5468 struct CheckAvailable { 5469 bool TraversalDone = false; 5470 bool Available = true; 5471 5472 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5473 BasicBlock *BB = nullptr; 5474 DominatorTree &DT; 5475 5476 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5477 : L(L), BB(BB), DT(DT) {} 5478 5479 bool setUnavailable() { 5480 TraversalDone = true; 5481 Available = false; 5482 return false; 5483 } 5484 5485 bool follow(const SCEV *S) { 5486 switch (S->getSCEVType()) { 5487 case scConstant: 5488 case scPtrToInt: 5489 case scTruncate: 5490 case scZeroExtend: 5491 case scSignExtend: 5492 case scAddExpr: 5493 case scMulExpr: 5494 case scUMaxExpr: 5495 case scSMaxExpr: 5496 case scUMinExpr: 5497 case scSMinExpr: 5498 // These expressions are available if their operand(s) is/are. 5499 return true; 5500 5501 case scAddRecExpr: { 5502 // We allow add recurrences that are on the loop BB is in, or some 5503 // outer loop. This guarantees availability because the value of the 5504 // add recurrence at BB is simply the "current" value of the induction 5505 // variable. We can relax this in the future; for instance an add 5506 // recurrence on a sibling dominating loop is also available at BB. 5507 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5508 if (L && (ARLoop == L || ARLoop->contains(L))) 5509 return true; 5510 5511 return setUnavailable(); 5512 } 5513 5514 case scUnknown: { 5515 // For SCEVUnknown, we check for simple dominance. 5516 const auto *SU = cast<SCEVUnknown>(S); 5517 Value *V = SU->getValue(); 5518 5519 if (isa<Argument>(V)) 5520 return false; 5521 5522 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5523 return false; 5524 5525 return setUnavailable(); 5526 } 5527 5528 case scUDivExpr: 5529 case scCouldNotCompute: 5530 // We do not try to smart about these at all. 5531 return setUnavailable(); 5532 } 5533 llvm_unreachable("Unknown SCEV kind!"); 5534 } 5535 5536 bool isDone() { return TraversalDone; } 5537 }; 5538 5539 CheckAvailable CA(L, BB, DT); 5540 SCEVTraversal<CheckAvailable> ST(CA); 5541 5542 ST.visitAll(S); 5543 return CA.Available; 5544 } 5545 5546 // Try to match a control flow sequence that branches out at BI and merges back 5547 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5548 // match. 5549 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5550 Value *&C, Value *&LHS, Value *&RHS) { 5551 C = BI->getCondition(); 5552 5553 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5554 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5555 5556 if (!LeftEdge.isSingleEdge()) 5557 return false; 5558 5559 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5560 5561 Use &LeftUse = Merge->getOperandUse(0); 5562 Use &RightUse = Merge->getOperandUse(1); 5563 5564 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5565 LHS = LeftUse; 5566 RHS = RightUse; 5567 return true; 5568 } 5569 5570 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5571 LHS = RightUse; 5572 RHS = LeftUse; 5573 return true; 5574 } 5575 5576 return false; 5577 } 5578 5579 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5580 auto IsReachable = 5581 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5582 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5583 const Loop *L = LI.getLoopFor(PN->getParent()); 5584 5585 // We don't want to break LCSSA, even in a SCEV expression tree. 5586 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5587 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5588 return nullptr; 5589 5590 // Try to match 5591 // 5592 // br %cond, label %left, label %right 5593 // left: 5594 // br label %merge 5595 // right: 5596 // br label %merge 5597 // merge: 5598 // V = phi [ %x, %left ], [ %y, %right ] 5599 // 5600 // as "select %cond, %x, %y" 5601 5602 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5603 assert(IDom && "At least the entry block should dominate PN"); 5604 5605 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5606 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5607 5608 if (BI && BI->isConditional() && 5609 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5610 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5611 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5612 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5613 } 5614 5615 return nullptr; 5616 } 5617 5618 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5619 if (const SCEV *S = createAddRecFromPHI(PN)) 5620 return S; 5621 5622 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5623 return S; 5624 5625 // If the PHI has a single incoming value, follow that value, unless the 5626 // PHI's incoming blocks are in a different loop, in which case doing so 5627 // risks breaking LCSSA form. Instcombine would normally zap these, but 5628 // it doesn't have DominatorTree information, so it may miss cases. 5629 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5630 if (LI.replacementPreservesLCSSAForm(PN, V)) 5631 return getSCEV(V); 5632 5633 // If it's not a loop phi, we can't handle it yet. 5634 return getUnknown(PN); 5635 } 5636 5637 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5638 Value *Cond, 5639 Value *TrueVal, 5640 Value *FalseVal) { 5641 // Handle "constant" branch or select. This can occur for instance when a 5642 // loop pass transforms an inner loop and moves on to process the outer loop. 5643 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5644 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5645 5646 // Try to match some simple smax or umax patterns. 5647 auto *ICI = dyn_cast<ICmpInst>(Cond); 5648 if (!ICI) 5649 return getUnknown(I); 5650 5651 Value *LHS = ICI->getOperand(0); 5652 Value *RHS = ICI->getOperand(1); 5653 5654 switch (ICI->getPredicate()) { 5655 case ICmpInst::ICMP_SLT: 5656 case ICmpInst::ICMP_SLE: 5657 case ICmpInst::ICMP_ULT: 5658 case ICmpInst::ICMP_ULE: 5659 std::swap(LHS, RHS); 5660 LLVM_FALLTHROUGH; 5661 case ICmpInst::ICMP_SGT: 5662 case ICmpInst::ICMP_SGE: 5663 case ICmpInst::ICMP_UGT: 5664 case ICmpInst::ICMP_UGE: 5665 // a > b ? a+x : b+x -> max(a, b)+x 5666 // a > b ? b+x : a+x -> min(a, b)+x 5667 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5668 bool Signed = ICI->isSigned(); 5669 const SCEV *LA = getSCEV(TrueVal); 5670 const SCEV *RA = getSCEV(FalseVal); 5671 const SCEV *LS = getSCEV(LHS); 5672 const SCEV *RS = getSCEV(RHS); 5673 if (LA->getType()->isPointerTy()) { 5674 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5675 // Need to make sure we can't produce weird expressions involving 5676 // negated pointers. 5677 if (LA == LS && RA == RS) 5678 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5679 if (LA == RS && RA == LS) 5680 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5681 } 5682 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5683 if (Op->getType()->isPointerTy()) { 5684 Op = getLosslessPtrToIntExpr(Op); 5685 if (isa<SCEVCouldNotCompute>(Op)) 5686 return Op; 5687 } 5688 if (Signed) 5689 Op = getNoopOrSignExtend(Op, I->getType()); 5690 else 5691 Op = getNoopOrZeroExtend(Op, I->getType()); 5692 return Op; 5693 }; 5694 LS = CoerceOperand(LS); 5695 RS = CoerceOperand(RS); 5696 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5697 break; 5698 const SCEV *LDiff = getMinusSCEV(LA, LS); 5699 const SCEV *RDiff = getMinusSCEV(RA, RS); 5700 if (LDiff == RDiff) 5701 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5702 LDiff); 5703 LDiff = getMinusSCEV(LA, RS); 5704 RDiff = getMinusSCEV(RA, LS); 5705 if (LDiff == RDiff) 5706 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5707 LDiff); 5708 } 5709 break; 5710 case ICmpInst::ICMP_NE: 5711 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5712 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5713 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5714 const SCEV *One = getOne(I->getType()); 5715 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5716 const SCEV *LA = getSCEV(TrueVal); 5717 const SCEV *RA = getSCEV(FalseVal); 5718 const SCEV *LDiff = getMinusSCEV(LA, LS); 5719 const SCEV *RDiff = getMinusSCEV(RA, One); 5720 if (LDiff == RDiff) 5721 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5722 } 5723 break; 5724 case ICmpInst::ICMP_EQ: 5725 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5726 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5727 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5728 const SCEV *One = getOne(I->getType()); 5729 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5730 const SCEV *LA = getSCEV(TrueVal); 5731 const SCEV *RA = getSCEV(FalseVal); 5732 const SCEV *LDiff = getMinusSCEV(LA, One); 5733 const SCEV *RDiff = getMinusSCEV(RA, LS); 5734 if (LDiff == RDiff) 5735 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5736 } 5737 break; 5738 default: 5739 break; 5740 } 5741 5742 return getUnknown(I); 5743 } 5744 5745 /// Expand GEP instructions into add and multiply operations. This allows them 5746 /// to be analyzed by regular SCEV code. 5747 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5748 // Don't attempt to analyze GEPs over unsized objects. 5749 if (!GEP->getSourceElementType()->isSized()) 5750 return getUnknown(GEP); 5751 5752 SmallVector<const SCEV *, 4> IndexExprs; 5753 for (Value *Index : GEP->indices()) 5754 IndexExprs.push_back(getSCEV(Index)); 5755 return getGEPExpr(GEP, IndexExprs); 5756 } 5757 5758 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5759 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5760 return C->getAPInt().countTrailingZeros(); 5761 5762 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5763 return GetMinTrailingZeros(I->getOperand()); 5764 5765 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5766 return std::min(GetMinTrailingZeros(T->getOperand()), 5767 (uint32_t)getTypeSizeInBits(T->getType())); 5768 5769 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5770 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5771 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5772 ? getTypeSizeInBits(E->getType()) 5773 : OpRes; 5774 } 5775 5776 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5777 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5778 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5779 ? getTypeSizeInBits(E->getType()) 5780 : OpRes; 5781 } 5782 5783 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5784 // The result is the min of all operands results. 5785 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5786 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5787 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5788 return MinOpRes; 5789 } 5790 5791 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5792 // The result is the sum of all operands results. 5793 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5794 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5795 for (unsigned i = 1, e = M->getNumOperands(); 5796 SumOpRes != BitWidth && i != e; ++i) 5797 SumOpRes = 5798 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5799 return SumOpRes; 5800 } 5801 5802 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5803 // The result is the min of all operands results. 5804 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5805 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5806 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5807 return MinOpRes; 5808 } 5809 5810 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5811 // The result is the min of all operands results. 5812 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5813 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5814 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5815 return MinOpRes; 5816 } 5817 5818 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5819 // The result is the min of all operands results. 5820 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5821 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5822 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5823 return MinOpRes; 5824 } 5825 5826 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5827 // For a SCEVUnknown, ask ValueTracking. 5828 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5829 return Known.countMinTrailingZeros(); 5830 } 5831 5832 // SCEVUDivExpr 5833 return 0; 5834 } 5835 5836 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5837 auto I = MinTrailingZerosCache.find(S); 5838 if (I != MinTrailingZerosCache.end()) 5839 return I->second; 5840 5841 uint32_t Result = GetMinTrailingZerosImpl(S); 5842 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5843 assert(InsertPair.second && "Should insert a new key"); 5844 return InsertPair.first->second; 5845 } 5846 5847 /// Helper method to assign a range to V from metadata present in the IR. 5848 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5849 if (Instruction *I = dyn_cast<Instruction>(V)) 5850 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5851 return getConstantRangeFromMetadata(*MD); 5852 5853 return None; 5854 } 5855 5856 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5857 SCEV::NoWrapFlags Flags) { 5858 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5859 AddRec->setNoWrapFlags(Flags); 5860 UnsignedRanges.erase(AddRec); 5861 SignedRanges.erase(AddRec); 5862 } 5863 } 5864 5865 ConstantRange ScalarEvolution:: 5866 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5867 const DataLayout &DL = getDataLayout(); 5868 5869 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5870 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5871 5872 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5873 // use information about the trip count to improve our available range. Note 5874 // that the trip count independent cases are already handled by known bits. 5875 // WARNING: The definition of recurrence used here is subtly different than 5876 // the one used by AddRec (and thus most of this file). Step is allowed to 5877 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5878 // and other addrecs in the same loop (for non-affine addrecs). The code 5879 // below intentionally handles the case where step is not loop invariant. 5880 auto *P = dyn_cast<PHINode>(U->getValue()); 5881 if (!P) 5882 return FullSet; 5883 5884 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5885 // even the values that are not available in these blocks may come from them, 5886 // and this leads to false-positive recurrence test. 5887 for (auto *Pred : predecessors(P->getParent())) 5888 if (!DT.isReachableFromEntry(Pred)) 5889 return FullSet; 5890 5891 BinaryOperator *BO; 5892 Value *Start, *Step; 5893 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5894 return FullSet; 5895 5896 // If we found a recurrence in reachable code, we must be in a loop. Note 5897 // that BO might be in some subloop of L, and that's completely okay. 5898 auto *L = LI.getLoopFor(P->getParent()); 5899 assert(L && L->getHeader() == P->getParent()); 5900 if (!L->contains(BO->getParent())) 5901 // NOTE: This bailout should be an assert instead. However, asserting 5902 // the condition here exposes a case where LoopFusion is querying SCEV 5903 // with malformed loop information during the midst of the transform. 5904 // There doesn't appear to be an obvious fix, so for the moment bailout 5905 // until the caller issue can be fixed. PR49566 tracks the bug. 5906 return FullSet; 5907 5908 // TODO: Extend to other opcodes such as mul, and div 5909 switch (BO->getOpcode()) { 5910 default: 5911 return FullSet; 5912 case Instruction::AShr: 5913 case Instruction::LShr: 5914 case Instruction::Shl: 5915 break; 5916 }; 5917 5918 if (BO->getOperand(0) != P) 5919 // TODO: Handle the power function forms some day. 5920 return FullSet; 5921 5922 unsigned TC = getSmallConstantMaxTripCount(L); 5923 if (!TC || TC >= BitWidth) 5924 return FullSet; 5925 5926 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5927 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5928 assert(KnownStart.getBitWidth() == BitWidth && 5929 KnownStep.getBitWidth() == BitWidth); 5930 5931 // Compute total shift amount, being careful of overflow and bitwidths. 5932 auto MaxShiftAmt = KnownStep.getMaxValue(); 5933 APInt TCAP(BitWidth, TC-1); 5934 bool Overflow = false; 5935 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5936 if (Overflow) 5937 return FullSet; 5938 5939 switch (BO->getOpcode()) { 5940 default: 5941 llvm_unreachable("filtered out above"); 5942 case Instruction::AShr: { 5943 // For each ashr, three cases: 5944 // shift = 0 => unchanged value 5945 // saturation => 0 or -1 5946 // other => a value closer to zero (of the same sign) 5947 // Thus, the end value is closer to zero than the start. 5948 auto KnownEnd = KnownBits::ashr(KnownStart, 5949 KnownBits::makeConstant(TotalShift)); 5950 if (KnownStart.isNonNegative()) 5951 // Analogous to lshr (simply not yet canonicalized) 5952 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5953 KnownStart.getMaxValue() + 1); 5954 if (KnownStart.isNegative()) 5955 // End >=u Start && End <=s Start 5956 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5957 KnownEnd.getMaxValue() + 1); 5958 break; 5959 } 5960 case Instruction::LShr: { 5961 // For each lshr, three cases: 5962 // shift = 0 => unchanged value 5963 // saturation => 0 5964 // other => a smaller positive number 5965 // Thus, the low end of the unsigned range is the last value produced. 5966 auto KnownEnd = KnownBits::lshr(KnownStart, 5967 KnownBits::makeConstant(TotalShift)); 5968 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5969 KnownStart.getMaxValue() + 1); 5970 } 5971 case Instruction::Shl: { 5972 // Iff no bits are shifted out, value increases on every shift. 5973 auto KnownEnd = KnownBits::shl(KnownStart, 5974 KnownBits::makeConstant(TotalShift)); 5975 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5976 return ConstantRange(KnownStart.getMinValue(), 5977 KnownEnd.getMaxValue() + 1); 5978 break; 5979 } 5980 }; 5981 return FullSet; 5982 } 5983 5984 /// Determine the range for a particular SCEV. If SignHint is 5985 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5986 /// with a "cleaner" unsigned (resp. signed) representation. 5987 const ConstantRange & 5988 ScalarEvolution::getRangeRef(const SCEV *S, 5989 ScalarEvolution::RangeSignHint SignHint) { 5990 DenseMap<const SCEV *, ConstantRange> &Cache = 5991 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5992 : SignedRanges; 5993 ConstantRange::PreferredRangeType RangeType = 5994 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5995 ? ConstantRange::Unsigned : ConstantRange::Signed; 5996 5997 // See if we've computed this range already. 5998 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5999 if (I != Cache.end()) 6000 return I->second; 6001 6002 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6003 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6004 6005 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6006 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6007 using OBO = OverflowingBinaryOperator; 6008 6009 // If the value has known zeros, the maximum value will have those known zeros 6010 // as well. 6011 uint32_t TZ = GetMinTrailingZeros(S); 6012 if (TZ != 0) { 6013 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6014 ConservativeResult = 6015 ConstantRange(APInt::getMinValue(BitWidth), 6016 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6017 else 6018 ConservativeResult = ConstantRange( 6019 APInt::getSignedMinValue(BitWidth), 6020 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6021 } 6022 6023 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6024 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6025 unsigned WrapType = OBO::AnyWrap; 6026 if (Add->hasNoSignedWrap()) 6027 WrapType |= OBO::NoSignedWrap; 6028 if (Add->hasNoUnsignedWrap()) 6029 WrapType |= OBO::NoUnsignedWrap; 6030 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6031 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6032 WrapType, RangeType); 6033 return setRange(Add, SignHint, 6034 ConservativeResult.intersectWith(X, RangeType)); 6035 } 6036 6037 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6038 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6039 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6040 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6041 return setRange(Mul, SignHint, 6042 ConservativeResult.intersectWith(X, RangeType)); 6043 } 6044 6045 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6046 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6047 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6048 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6049 return setRange(SMax, SignHint, 6050 ConservativeResult.intersectWith(X, RangeType)); 6051 } 6052 6053 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6054 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6055 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6056 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6057 return setRange(UMax, SignHint, 6058 ConservativeResult.intersectWith(X, RangeType)); 6059 } 6060 6061 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6062 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6063 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6064 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6065 return setRange(SMin, SignHint, 6066 ConservativeResult.intersectWith(X, RangeType)); 6067 } 6068 6069 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6070 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6071 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6072 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6073 return setRange(UMin, SignHint, 6074 ConservativeResult.intersectWith(X, RangeType)); 6075 } 6076 6077 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6078 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6079 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6080 return setRange(UDiv, SignHint, 6081 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6082 } 6083 6084 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6085 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6086 return setRange(ZExt, SignHint, 6087 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6088 RangeType)); 6089 } 6090 6091 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6092 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6093 return setRange(SExt, SignHint, 6094 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6095 RangeType)); 6096 } 6097 6098 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6099 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6100 return setRange(PtrToInt, SignHint, X); 6101 } 6102 6103 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6104 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6105 return setRange(Trunc, SignHint, 6106 ConservativeResult.intersectWith(X.truncate(BitWidth), 6107 RangeType)); 6108 } 6109 6110 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6111 // If there's no unsigned wrap, the value will never be less than its 6112 // initial value. 6113 if (AddRec->hasNoUnsignedWrap()) { 6114 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6115 if (!UnsignedMinValue.isNullValue()) 6116 ConservativeResult = ConservativeResult.intersectWith( 6117 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6118 } 6119 6120 // If there's no signed wrap, and all the operands except initial value have 6121 // the same sign or zero, the value won't ever be: 6122 // 1: smaller than initial value if operands are non negative, 6123 // 2: bigger than initial value if operands are non positive. 6124 // For both cases, value can not cross signed min/max boundary. 6125 if (AddRec->hasNoSignedWrap()) { 6126 bool AllNonNeg = true; 6127 bool AllNonPos = true; 6128 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6129 if (!isKnownNonNegative(AddRec->getOperand(i))) 6130 AllNonNeg = false; 6131 if (!isKnownNonPositive(AddRec->getOperand(i))) 6132 AllNonPos = false; 6133 } 6134 if (AllNonNeg) 6135 ConservativeResult = ConservativeResult.intersectWith( 6136 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6137 APInt::getSignedMinValue(BitWidth)), 6138 RangeType); 6139 else if (AllNonPos) 6140 ConservativeResult = ConservativeResult.intersectWith( 6141 ConstantRange::getNonEmpty( 6142 APInt::getSignedMinValue(BitWidth), 6143 getSignedRangeMax(AddRec->getStart()) + 1), 6144 RangeType); 6145 } 6146 6147 // TODO: non-affine addrec 6148 if (AddRec->isAffine()) { 6149 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6150 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6151 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6152 auto RangeFromAffine = getRangeForAffineAR( 6153 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6154 BitWidth); 6155 ConservativeResult = 6156 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6157 6158 auto RangeFromFactoring = getRangeViaFactoring( 6159 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6160 BitWidth); 6161 ConservativeResult = 6162 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6163 } 6164 6165 // Now try symbolic BE count and more powerful methods. 6166 if (UseExpensiveRangeSharpening) { 6167 const SCEV *SymbolicMaxBECount = 6168 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6169 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6170 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6171 AddRec->hasNoSelfWrap()) { 6172 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6173 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6174 ConservativeResult = 6175 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6176 } 6177 } 6178 } 6179 6180 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6181 } 6182 6183 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6184 6185 // Check if the IR explicitly contains !range metadata. 6186 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6187 if (MDRange.hasValue()) 6188 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6189 RangeType); 6190 6191 // Use facts about recurrences in the underlying IR. Note that add 6192 // recurrences are AddRecExprs and thus don't hit this path. This 6193 // primarily handles shift recurrences. 6194 auto CR = getRangeForUnknownRecurrence(U); 6195 ConservativeResult = ConservativeResult.intersectWith(CR); 6196 6197 // See if ValueTracking can give us a useful range. 6198 const DataLayout &DL = getDataLayout(); 6199 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6200 if (Known.getBitWidth() != BitWidth) 6201 Known = Known.zextOrTrunc(BitWidth); 6202 6203 // ValueTracking may be able to compute a tighter result for the number of 6204 // sign bits than for the value of those sign bits. 6205 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6206 if (U->getType()->isPointerTy()) { 6207 // If the pointer size is larger than the index size type, this can cause 6208 // NS to be larger than BitWidth. So compensate for this. 6209 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6210 int ptrIdxDiff = ptrSize - BitWidth; 6211 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6212 NS -= ptrIdxDiff; 6213 } 6214 6215 if (NS > 1) { 6216 // If we know any of the sign bits, we know all of the sign bits. 6217 if (!Known.Zero.getHiBits(NS).isNullValue()) 6218 Known.Zero.setHighBits(NS); 6219 if (!Known.One.getHiBits(NS).isNullValue()) 6220 Known.One.setHighBits(NS); 6221 } 6222 6223 if (Known.getMinValue() != Known.getMaxValue() + 1) 6224 ConservativeResult = ConservativeResult.intersectWith( 6225 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6226 RangeType); 6227 if (NS > 1) 6228 ConservativeResult = ConservativeResult.intersectWith( 6229 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6230 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6231 RangeType); 6232 6233 // A range of Phi is a subset of union of all ranges of its input. 6234 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6235 // Make sure that we do not run over cycled Phis. 6236 if (PendingPhiRanges.insert(Phi).second) { 6237 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6238 for (auto &Op : Phi->operands()) { 6239 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6240 RangeFromOps = RangeFromOps.unionWith(OpRange); 6241 // No point to continue if we already have a full set. 6242 if (RangeFromOps.isFullSet()) 6243 break; 6244 } 6245 ConservativeResult = 6246 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6247 bool Erased = PendingPhiRanges.erase(Phi); 6248 assert(Erased && "Failed to erase Phi properly?"); 6249 (void) Erased; 6250 } 6251 } 6252 6253 return setRange(U, SignHint, std::move(ConservativeResult)); 6254 } 6255 6256 return setRange(S, SignHint, std::move(ConservativeResult)); 6257 } 6258 6259 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6260 // values that the expression can take. Initially, the expression has a value 6261 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6262 // argument defines if we treat Step as signed or unsigned. 6263 static ConstantRange getRangeForAffineARHelper(APInt Step, 6264 const ConstantRange &StartRange, 6265 const APInt &MaxBECount, 6266 unsigned BitWidth, bool Signed) { 6267 // If either Step or MaxBECount is 0, then the expression won't change, and we 6268 // just need to return the initial range. 6269 if (Step == 0 || MaxBECount == 0) 6270 return StartRange; 6271 6272 // If we don't know anything about the initial value (i.e. StartRange is 6273 // FullRange), then we don't know anything about the final range either. 6274 // Return FullRange. 6275 if (StartRange.isFullSet()) 6276 return ConstantRange::getFull(BitWidth); 6277 6278 // If Step is signed and negative, then we use its absolute value, but we also 6279 // note that we're moving in the opposite direction. 6280 bool Descending = Signed && Step.isNegative(); 6281 6282 if (Signed) 6283 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6284 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6285 // This equations hold true due to the well-defined wrap-around behavior of 6286 // APInt. 6287 Step = Step.abs(); 6288 6289 // Check if Offset is more than full span of BitWidth. If it is, the 6290 // expression is guaranteed to overflow. 6291 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6292 return ConstantRange::getFull(BitWidth); 6293 6294 // Offset is by how much the expression can change. Checks above guarantee no 6295 // overflow here. 6296 APInt Offset = Step * MaxBECount; 6297 6298 // Minimum value of the final range will match the minimal value of StartRange 6299 // if the expression is increasing and will be decreased by Offset otherwise. 6300 // Maximum value of the final range will match the maximal value of StartRange 6301 // if the expression is decreasing and will be increased by Offset otherwise. 6302 APInt StartLower = StartRange.getLower(); 6303 APInt StartUpper = StartRange.getUpper() - 1; 6304 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6305 : (StartUpper + std::move(Offset)); 6306 6307 // It's possible that the new minimum/maximum value will fall into the initial 6308 // range (due to wrap around). This means that the expression can take any 6309 // value in this bitwidth, and we have to return full range. 6310 if (StartRange.contains(MovedBoundary)) 6311 return ConstantRange::getFull(BitWidth); 6312 6313 APInt NewLower = 6314 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6315 APInt NewUpper = 6316 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6317 NewUpper += 1; 6318 6319 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6320 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6321 } 6322 6323 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6324 const SCEV *Step, 6325 const SCEV *MaxBECount, 6326 unsigned BitWidth) { 6327 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6328 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6329 "Precondition!"); 6330 6331 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6332 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6333 6334 // First, consider step signed. 6335 ConstantRange StartSRange = getSignedRange(Start); 6336 ConstantRange StepSRange = getSignedRange(Step); 6337 6338 // If Step can be both positive and negative, we need to find ranges for the 6339 // maximum absolute step values in both directions and union them. 6340 ConstantRange SR = 6341 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6342 MaxBECountValue, BitWidth, /* Signed = */ true); 6343 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6344 StartSRange, MaxBECountValue, 6345 BitWidth, /* Signed = */ true)); 6346 6347 // Next, consider step unsigned. 6348 ConstantRange UR = getRangeForAffineARHelper( 6349 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6350 MaxBECountValue, BitWidth, /* Signed = */ false); 6351 6352 // Finally, intersect signed and unsigned ranges. 6353 return SR.intersectWith(UR, ConstantRange::Smallest); 6354 } 6355 6356 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6357 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6358 ScalarEvolution::RangeSignHint SignHint) { 6359 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6360 assert(AddRec->hasNoSelfWrap() && 6361 "This only works for non-self-wrapping AddRecs!"); 6362 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6363 const SCEV *Step = AddRec->getStepRecurrence(*this); 6364 // Only deal with constant step to save compile time. 6365 if (!isa<SCEVConstant>(Step)) 6366 return ConstantRange::getFull(BitWidth); 6367 // Let's make sure that we can prove that we do not self-wrap during 6368 // MaxBECount iterations. We need this because MaxBECount is a maximum 6369 // iteration count estimate, and we might infer nw from some exit for which we 6370 // do not know max exit count (or any other side reasoning). 6371 // TODO: Turn into assert at some point. 6372 if (getTypeSizeInBits(MaxBECount->getType()) > 6373 getTypeSizeInBits(AddRec->getType())) 6374 return ConstantRange::getFull(BitWidth); 6375 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6376 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6377 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6378 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6379 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6380 MaxItersWithoutWrap)) 6381 return ConstantRange::getFull(BitWidth); 6382 6383 ICmpInst::Predicate LEPred = 6384 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6385 ICmpInst::Predicate GEPred = 6386 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6387 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6388 6389 // We know that there is no self-wrap. Let's take Start and End values and 6390 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6391 // the iteration. They either lie inside the range [Min(Start, End), 6392 // Max(Start, End)] or outside it: 6393 // 6394 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6395 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6396 // 6397 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6398 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6399 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6400 // Start <= End and step is positive, or Start >= End and step is negative. 6401 const SCEV *Start = AddRec->getStart(); 6402 ConstantRange StartRange = getRangeRef(Start, SignHint); 6403 ConstantRange EndRange = getRangeRef(End, SignHint); 6404 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6405 // If they already cover full iteration space, we will know nothing useful 6406 // even if we prove what we want to prove. 6407 if (RangeBetween.isFullSet()) 6408 return RangeBetween; 6409 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6410 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6411 : RangeBetween.isWrappedSet(); 6412 if (IsWrappedSet) 6413 return ConstantRange::getFull(BitWidth); 6414 6415 if (isKnownPositive(Step) && 6416 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6417 return RangeBetween; 6418 else if (isKnownNegative(Step) && 6419 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6420 return RangeBetween; 6421 return ConstantRange::getFull(BitWidth); 6422 } 6423 6424 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6425 const SCEV *Step, 6426 const SCEV *MaxBECount, 6427 unsigned BitWidth) { 6428 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6429 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6430 6431 struct SelectPattern { 6432 Value *Condition = nullptr; 6433 APInt TrueValue; 6434 APInt FalseValue; 6435 6436 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6437 const SCEV *S) { 6438 Optional<unsigned> CastOp; 6439 APInt Offset(BitWidth, 0); 6440 6441 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6442 "Should be!"); 6443 6444 // Peel off a constant offset: 6445 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6446 // In the future we could consider being smarter here and handle 6447 // {Start+Step,+,Step} too. 6448 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6449 return; 6450 6451 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6452 S = SA->getOperand(1); 6453 } 6454 6455 // Peel off a cast operation 6456 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6457 CastOp = SCast->getSCEVType(); 6458 S = SCast->getOperand(); 6459 } 6460 6461 using namespace llvm::PatternMatch; 6462 6463 auto *SU = dyn_cast<SCEVUnknown>(S); 6464 const APInt *TrueVal, *FalseVal; 6465 if (!SU || 6466 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6467 m_APInt(FalseVal)))) { 6468 Condition = nullptr; 6469 return; 6470 } 6471 6472 TrueValue = *TrueVal; 6473 FalseValue = *FalseVal; 6474 6475 // Re-apply the cast we peeled off earlier 6476 if (CastOp.hasValue()) 6477 switch (*CastOp) { 6478 default: 6479 llvm_unreachable("Unknown SCEV cast type!"); 6480 6481 case scTruncate: 6482 TrueValue = TrueValue.trunc(BitWidth); 6483 FalseValue = FalseValue.trunc(BitWidth); 6484 break; 6485 case scZeroExtend: 6486 TrueValue = TrueValue.zext(BitWidth); 6487 FalseValue = FalseValue.zext(BitWidth); 6488 break; 6489 case scSignExtend: 6490 TrueValue = TrueValue.sext(BitWidth); 6491 FalseValue = FalseValue.sext(BitWidth); 6492 break; 6493 } 6494 6495 // Re-apply the constant offset we peeled off earlier 6496 TrueValue += Offset; 6497 FalseValue += Offset; 6498 } 6499 6500 bool isRecognized() { return Condition != nullptr; } 6501 }; 6502 6503 SelectPattern StartPattern(*this, BitWidth, Start); 6504 if (!StartPattern.isRecognized()) 6505 return ConstantRange::getFull(BitWidth); 6506 6507 SelectPattern StepPattern(*this, BitWidth, Step); 6508 if (!StepPattern.isRecognized()) 6509 return ConstantRange::getFull(BitWidth); 6510 6511 if (StartPattern.Condition != StepPattern.Condition) { 6512 // We don't handle this case today; but we could, by considering four 6513 // possibilities below instead of two. I'm not sure if there are cases where 6514 // that will help over what getRange already does, though. 6515 return ConstantRange::getFull(BitWidth); 6516 } 6517 6518 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6519 // construct arbitrary general SCEV expressions here. This function is called 6520 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6521 // say) can end up caching a suboptimal value. 6522 6523 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6524 // C2352 and C2512 (otherwise it isn't needed). 6525 6526 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6527 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6528 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6529 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6530 6531 ConstantRange TrueRange = 6532 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6533 ConstantRange FalseRange = 6534 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6535 6536 return TrueRange.unionWith(FalseRange); 6537 } 6538 6539 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6540 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6541 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6542 6543 // Return early if there are no flags to propagate to the SCEV. 6544 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6545 if (BinOp->hasNoUnsignedWrap()) 6546 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6547 if (BinOp->hasNoSignedWrap()) 6548 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6549 if (Flags == SCEV::FlagAnyWrap) 6550 return SCEV::FlagAnyWrap; 6551 6552 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6553 } 6554 6555 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6556 // Here we check that I is in the header of the innermost loop containing I, 6557 // since we only deal with instructions in the loop header. The actual loop we 6558 // need to check later will come from an add recurrence, but getting that 6559 // requires computing the SCEV of the operands, which can be expensive. This 6560 // check we can do cheaply to rule out some cases early. 6561 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6562 if (InnermostContainingLoop == nullptr || 6563 InnermostContainingLoop->getHeader() != I->getParent()) 6564 return false; 6565 6566 // Only proceed if we can prove that I does not yield poison. 6567 if (!programUndefinedIfPoison(I)) 6568 return false; 6569 6570 // At this point we know that if I is executed, then it does not wrap 6571 // according to at least one of NSW or NUW. If I is not executed, then we do 6572 // not know if the calculation that I represents would wrap. Multiple 6573 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6574 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6575 // derived from other instructions that map to the same SCEV. We cannot make 6576 // that guarantee for cases where I is not executed. So we need to find the 6577 // loop that I is considered in relation to and prove that I is executed for 6578 // every iteration of that loop. That implies that the value that I 6579 // calculates does not wrap anywhere in the loop, so then we can apply the 6580 // flags to the SCEV. 6581 // 6582 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6583 // from different loops, so that we know which loop to prove that I is 6584 // executed in. 6585 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6586 // I could be an extractvalue from a call to an overflow intrinsic. 6587 // TODO: We can do better here in some cases. 6588 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6589 return false; 6590 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6591 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6592 bool AllOtherOpsLoopInvariant = true; 6593 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6594 ++OtherOpIndex) { 6595 if (OtherOpIndex != OpIndex) { 6596 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6597 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6598 AllOtherOpsLoopInvariant = false; 6599 break; 6600 } 6601 } 6602 } 6603 if (AllOtherOpsLoopInvariant && 6604 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6605 return true; 6606 } 6607 } 6608 return false; 6609 } 6610 6611 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6612 // If we know that \c I can never be poison period, then that's enough. 6613 if (isSCEVExprNeverPoison(I)) 6614 return true; 6615 6616 // For an add recurrence specifically, we assume that infinite loops without 6617 // side effects are undefined behavior, and then reason as follows: 6618 // 6619 // If the add recurrence is poison in any iteration, it is poison on all 6620 // future iterations (since incrementing poison yields poison). If the result 6621 // of the add recurrence is fed into the loop latch condition and the loop 6622 // does not contain any throws or exiting blocks other than the latch, we now 6623 // have the ability to "choose" whether the backedge is taken or not (by 6624 // choosing a sufficiently evil value for the poison feeding into the branch) 6625 // for every iteration including and after the one in which \p I first became 6626 // poison. There are two possibilities (let's call the iteration in which \p 6627 // I first became poison as K): 6628 // 6629 // 1. In the set of iterations including and after K, the loop body executes 6630 // no side effects. In this case executing the backege an infinte number 6631 // of times will yield undefined behavior. 6632 // 6633 // 2. In the set of iterations including and after K, the loop body executes 6634 // at least one side effect. In this case, that specific instance of side 6635 // effect is control dependent on poison, which also yields undefined 6636 // behavior. 6637 6638 auto *ExitingBB = L->getExitingBlock(); 6639 auto *LatchBB = L->getLoopLatch(); 6640 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6641 return false; 6642 6643 SmallPtrSet<const Instruction *, 16> Pushed; 6644 SmallVector<const Instruction *, 8> PoisonStack; 6645 6646 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6647 // things that are known to be poison under that assumption go on the 6648 // PoisonStack. 6649 Pushed.insert(I); 6650 PoisonStack.push_back(I); 6651 6652 bool LatchControlDependentOnPoison = false; 6653 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6654 const Instruction *Poison = PoisonStack.pop_back_val(); 6655 6656 for (auto *PoisonUser : Poison->users()) { 6657 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6658 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6659 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6660 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6661 assert(BI->isConditional() && "Only possibility!"); 6662 if (BI->getParent() == LatchBB) { 6663 LatchControlDependentOnPoison = true; 6664 break; 6665 } 6666 } 6667 } 6668 } 6669 6670 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6671 } 6672 6673 ScalarEvolution::LoopProperties 6674 ScalarEvolution::getLoopProperties(const Loop *L) { 6675 using LoopProperties = ScalarEvolution::LoopProperties; 6676 6677 auto Itr = LoopPropertiesCache.find(L); 6678 if (Itr == LoopPropertiesCache.end()) { 6679 auto HasSideEffects = [](Instruction *I) { 6680 if (auto *SI = dyn_cast<StoreInst>(I)) 6681 return !SI->isSimple(); 6682 6683 return I->mayHaveSideEffects(); 6684 }; 6685 6686 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6687 /*HasNoSideEffects*/ true}; 6688 6689 for (auto *BB : L->getBlocks()) 6690 for (auto &I : *BB) { 6691 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6692 LP.HasNoAbnormalExits = false; 6693 if (HasSideEffects(&I)) 6694 LP.HasNoSideEffects = false; 6695 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6696 break; // We're already as pessimistic as we can get. 6697 } 6698 6699 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6700 assert(InsertPair.second && "We just checked!"); 6701 Itr = InsertPair.first; 6702 } 6703 6704 return Itr->second; 6705 } 6706 6707 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6708 // A mustprogress loop without side effects must be finite. 6709 // TODO: The check used here is very conservative. It's only *specific* 6710 // side effects which are well defined in infinite loops. 6711 return isMustProgress(L) && loopHasNoSideEffects(L); 6712 } 6713 6714 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6715 if (!isSCEVable(V->getType())) 6716 return getUnknown(V); 6717 6718 if (Instruction *I = dyn_cast<Instruction>(V)) { 6719 // Don't attempt to analyze instructions in blocks that aren't 6720 // reachable. Such instructions don't matter, and they aren't required 6721 // to obey basic rules for definitions dominating uses which this 6722 // analysis depends on. 6723 if (!DT.isReachableFromEntry(I->getParent())) 6724 return getUnknown(UndefValue::get(V->getType())); 6725 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6726 return getConstant(CI); 6727 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6728 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6729 else if (!isa<ConstantExpr>(V)) 6730 return getUnknown(V); 6731 6732 Operator *U = cast<Operator>(V); 6733 if (auto BO = MatchBinaryOp(U, DT)) { 6734 switch (BO->Opcode) { 6735 case Instruction::Add: { 6736 // The simple thing to do would be to just call getSCEV on both operands 6737 // and call getAddExpr with the result. However if we're looking at a 6738 // bunch of things all added together, this can be quite inefficient, 6739 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6740 // Instead, gather up all the operands and make a single getAddExpr call. 6741 // LLVM IR canonical form means we need only traverse the left operands. 6742 SmallVector<const SCEV *, 4> AddOps; 6743 do { 6744 if (BO->Op) { 6745 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6746 AddOps.push_back(OpSCEV); 6747 break; 6748 } 6749 6750 // If a NUW or NSW flag can be applied to the SCEV for this 6751 // addition, then compute the SCEV for this addition by itself 6752 // with a separate call to getAddExpr. We need to do that 6753 // instead of pushing the operands of the addition onto AddOps, 6754 // since the flags are only known to apply to this particular 6755 // addition - they may not apply to other additions that can be 6756 // formed with operands from AddOps. 6757 const SCEV *RHS = getSCEV(BO->RHS); 6758 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6759 if (Flags != SCEV::FlagAnyWrap) { 6760 const SCEV *LHS = getSCEV(BO->LHS); 6761 if (BO->Opcode == Instruction::Sub) 6762 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6763 else 6764 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6765 break; 6766 } 6767 } 6768 6769 if (BO->Opcode == Instruction::Sub) 6770 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6771 else 6772 AddOps.push_back(getSCEV(BO->RHS)); 6773 6774 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6775 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6776 NewBO->Opcode != Instruction::Sub)) { 6777 AddOps.push_back(getSCEV(BO->LHS)); 6778 break; 6779 } 6780 BO = NewBO; 6781 } while (true); 6782 6783 return getAddExpr(AddOps); 6784 } 6785 6786 case Instruction::Mul: { 6787 SmallVector<const SCEV *, 4> MulOps; 6788 do { 6789 if (BO->Op) { 6790 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6791 MulOps.push_back(OpSCEV); 6792 break; 6793 } 6794 6795 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6796 if (Flags != SCEV::FlagAnyWrap) { 6797 MulOps.push_back( 6798 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6799 break; 6800 } 6801 } 6802 6803 MulOps.push_back(getSCEV(BO->RHS)); 6804 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6805 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6806 MulOps.push_back(getSCEV(BO->LHS)); 6807 break; 6808 } 6809 BO = NewBO; 6810 } while (true); 6811 6812 return getMulExpr(MulOps); 6813 } 6814 case Instruction::UDiv: 6815 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6816 case Instruction::URem: 6817 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6818 case Instruction::Sub: { 6819 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6820 if (BO->Op) 6821 Flags = getNoWrapFlagsFromUB(BO->Op); 6822 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6823 } 6824 case Instruction::And: 6825 // For an expression like x&255 that merely masks off the high bits, 6826 // use zext(trunc(x)) as the SCEV expression. 6827 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6828 if (CI->isZero()) 6829 return getSCEV(BO->RHS); 6830 if (CI->isMinusOne()) 6831 return getSCEV(BO->LHS); 6832 const APInt &A = CI->getValue(); 6833 6834 // Instcombine's ShrinkDemandedConstant may strip bits out of 6835 // constants, obscuring what would otherwise be a low-bits mask. 6836 // Use computeKnownBits to compute what ShrinkDemandedConstant 6837 // knew about to reconstruct a low-bits mask value. 6838 unsigned LZ = A.countLeadingZeros(); 6839 unsigned TZ = A.countTrailingZeros(); 6840 unsigned BitWidth = A.getBitWidth(); 6841 KnownBits Known(BitWidth); 6842 computeKnownBits(BO->LHS, Known, getDataLayout(), 6843 0, &AC, nullptr, &DT); 6844 6845 APInt EffectiveMask = 6846 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6847 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6848 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6849 const SCEV *LHS = getSCEV(BO->LHS); 6850 const SCEV *ShiftedLHS = nullptr; 6851 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6852 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6853 // For an expression like (x * 8) & 8, simplify the multiply. 6854 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6855 unsigned GCD = std::min(MulZeros, TZ); 6856 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6857 SmallVector<const SCEV*, 4> MulOps; 6858 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6859 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6860 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6861 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6862 } 6863 } 6864 if (!ShiftedLHS) 6865 ShiftedLHS = getUDivExpr(LHS, MulCount); 6866 return getMulExpr( 6867 getZeroExtendExpr( 6868 getTruncateExpr(ShiftedLHS, 6869 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6870 BO->LHS->getType()), 6871 MulCount); 6872 } 6873 } 6874 break; 6875 6876 case Instruction::Or: 6877 // If the RHS of the Or is a constant, we may have something like: 6878 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6879 // optimizations will transparently handle this case. 6880 // 6881 // In order for this transformation to be safe, the LHS must be of the 6882 // form X*(2^n) and the Or constant must be less than 2^n. 6883 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6884 const SCEV *LHS = getSCEV(BO->LHS); 6885 const APInt &CIVal = CI->getValue(); 6886 if (GetMinTrailingZeros(LHS) >= 6887 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6888 // Build a plain add SCEV. 6889 return getAddExpr(LHS, getSCEV(CI), 6890 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6891 } 6892 } 6893 break; 6894 6895 case Instruction::Xor: 6896 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6897 // If the RHS of xor is -1, then this is a not operation. 6898 if (CI->isMinusOne()) 6899 return getNotSCEV(getSCEV(BO->LHS)); 6900 6901 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6902 // This is a variant of the check for xor with -1, and it handles 6903 // the case where instcombine has trimmed non-demanded bits out 6904 // of an xor with -1. 6905 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6906 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6907 if (LBO->getOpcode() == Instruction::And && 6908 LCI->getValue() == CI->getValue()) 6909 if (const SCEVZeroExtendExpr *Z = 6910 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6911 Type *UTy = BO->LHS->getType(); 6912 const SCEV *Z0 = Z->getOperand(); 6913 Type *Z0Ty = Z0->getType(); 6914 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6915 6916 // If C is a low-bits mask, the zero extend is serving to 6917 // mask off the high bits. Complement the operand and 6918 // re-apply the zext. 6919 if (CI->getValue().isMask(Z0TySize)) 6920 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6921 6922 // If C is a single bit, it may be in the sign-bit position 6923 // before the zero-extend. In this case, represent the xor 6924 // using an add, which is equivalent, and re-apply the zext. 6925 APInt Trunc = CI->getValue().trunc(Z0TySize); 6926 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6927 Trunc.isSignMask()) 6928 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6929 UTy); 6930 } 6931 } 6932 break; 6933 6934 case Instruction::Shl: 6935 // Turn shift left of a constant amount into a multiply. 6936 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6937 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6938 6939 // If the shift count is not less than the bitwidth, the result of 6940 // the shift is undefined. Don't try to analyze it, because the 6941 // resolution chosen here may differ from the resolution chosen in 6942 // other parts of the compiler. 6943 if (SA->getValue().uge(BitWidth)) 6944 break; 6945 6946 // We can safely preserve the nuw flag in all cases. It's also safe to 6947 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6948 // requires special handling. It can be preserved as long as we're not 6949 // left shifting by bitwidth - 1. 6950 auto Flags = SCEV::FlagAnyWrap; 6951 if (BO->Op) { 6952 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6953 if ((MulFlags & SCEV::FlagNSW) && 6954 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6955 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6956 if (MulFlags & SCEV::FlagNUW) 6957 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6958 } 6959 6960 Constant *X = ConstantInt::get( 6961 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6962 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6963 } 6964 break; 6965 6966 case Instruction::AShr: { 6967 // AShr X, C, where C is a constant. 6968 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6969 if (!CI) 6970 break; 6971 6972 Type *OuterTy = BO->LHS->getType(); 6973 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6974 // If the shift count is not less than the bitwidth, the result of 6975 // the shift is undefined. Don't try to analyze it, because the 6976 // resolution chosen here may differ from the resolution chosen in 6977 // other parts of the compiler. 6978 if (CI->getValue().uge(BitWidth)) 6979 break; 6980 6981 if (CI->isZero()) 6982 return getSCEV(BO->LHS); // shift by zero --> noop 6983 6984 uint64_t AShrAmt = CI->getZExtValue(); 6985 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6986 6987 Operator *L = dyn_cast<Operator>(BO->LHS); 6988 if (L && L->getOpcode() == Instruction::Shl) { 6989 // X = Shl A, n 6990 // Y = AShr X, m 6991 // Both n and m are constant. 6992 6993 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6994 if (L->getOperand(1) == BO->RHS) 6995 // For a two-shift sext-inreg, i.e. n = m, 6996 // use sext(trunc(x)) as the SCEV expression. 6997 return getSignExtendExpr( 6998 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6999 7000 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7001 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7002 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7003 if (ShlAmt > AShrAmt) { 7004 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7005 // expression. We already checked that ShlAmt < BitWidth, so 7006 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7007 // ShlAmt - AShrAmt < Amt. 7008 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7009 ShlAmt - AShrAmt); 7010 return getSignExtendExpr( 7011 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7012 getConstant(Mul)), OuterTy); 7013 } 7014 } 7015 } 7016 break; 7017 } 7018 } 7019 } 7020 7021 switch (U->getOpcode()) { 7022 case Instruction::Trunc: 7023 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7024 7025 case Instruction::ZExt: 7026 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7027 7028 case Instruction::SExt: 7029 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7030 // The NSW flag of a subtract does not always survive the conversion to 7031 // A + (-1)*B. By pushing sign extension onto its operands we are much 7032 // more likely to preserve NSW and allow later AddRec optimisations. 7033 // 7034 // NOTE: This is effectively duplicating this logic from getSignExtend: 7035 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7036 // but by that point the NSW information has potentially been lost. 7037 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7038 Type *Ty = U->getType(); 7039 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7040 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7041 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7042 } 7043 } 7044 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7045 7046 case Instruction::BitCast: 7047 // BitCasts are no-op casts so we just eliminate the cast. 7048 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7049 return getSCEV(U->getOperand(0)); 7050 break; 7051 7052 case Instruction::PtrToInt: { 7053 // Pointer to integer cast is straight-forward, so do model it. 7054 const SCEV *Op = getSCEV(U->getOperand(0)); 7055 Type *DstIntTy = U->getType(); 7056 // But only if effective SCEV (integer) type is wide enough to represent 7057 // all possible pointer values. 7058 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7059 if (isa<SCEVCouldNotCompute>(IntOp)) 7060 return getUnknown(V); 7061 return IntOp; 7062 } 7063 case Instruction::IntToPtr: 7064 // Just don't deal with inttoptr casts. 7065 return getUnknown(V); 7066 7067 case Instruction::SDiv: 7068 // If both operands are non-negative, this is just an udiv. 7069 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7070 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7071 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7072 break; 7073 7074 case Instruction::SRem: 7075 // If both operands are non-negative, this is just an urem. 7076 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7077 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7078 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7079 break; 7080 7081 case Instruction::GetElementPtr: 7082 return createNodeForGEP(cast<GEPOperator>(U)); 7083 7084 case Instruction::PHI: 7085 return createNodeForPHI(cast<PHINode>(U)); 7086 7087 case Instruction::Select: 7088 // U can also be a select constant expr, which let fall through. Since 7089 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7090 // constant expressions cannot have instructions as operands, we'd have 7091 // returned getUnknown for a select constant expressions anyway. 7092 if (isa<Instruction>(U)) 7093 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7094 U->getOperand(1), U->getOperand(2)); 7095 break; 7096 7097 case Instruction::Call: 7098 case Instruction::Invoke: 7099 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7100 return getSCEV(RV); 7101 7102 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7103 switch (II->getIntrinsicID()) { 7104 case Intrinsic::abs: 7105 return getAbsExpr( 7106 getSCEV(II->getArgOperand(0)), 7107 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7108 case Intrinsic::umax: 7109 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7110 getSCEV(II->getArgOperand(1))); 7111 case Intrinsic::umin: 7112 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7113 getSCEV(II->getArgOperand(1))); 7114 case Intrinsic::smax: 7115 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7116 getSCEV(II->getArgOperand(1))); 7117 case Intrinsic::smin: 7118 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7119 getSCEV(II->getArgOperand(1))); 7120 case Intrinsic::usub_sat: { 7121 const SCEV *X = getSCEV(II->getArgOperand(0)); 7122 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7123 const SCEV *ClampedY = getUMinExpr(X, Y); 7124 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7125 } 7126 case Intrinsic::uadd_sat: { 7127 const SCEV *X = getSCEV(II->getArgOperand(0)); 7128 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7129 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7130 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7131 } 7132 case Intrinsic::start_loop_iterations: 7133 // A start_loop_iterations is just equivalent to the first operand for 7134 // SCEV purposes. 7135 return getSCEV(II->getArgOperand(0)); 7136 default: 7137 break; 7138 } 7139 } 7140 break; 7141 } 7142 7143 return getUnknown(V); 7144 } 7145 7146 //===----------------------------------------------------------------------===// 7147 // Iteration Count Computation Code 7148 // 7149 7150 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7151 // Get the trip count from the BE count by adding 1. Overflow, results 7152 // in zero which means "unknown". 7153 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7154 } 7155 7156 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7157 if (!ExitCount) 7158 return 0; 7159 7160 ConstantInt *ExitConst = ExitCount->getValue(); 7161 7162 // Guard against huge trip counts. 7163 if (ExitConst->getValue().getActiveBits() > 32) 7164 return 0; 7165 7166 // In case of integer overflow, this returns 0, which is correct. 7167 return ((unsigned)ExitConst->getZExtValue()) + 1; 7168 } 7169 7170 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7171 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7172 return getConstantTripCount(ExitCount); 7173 } 7174 7175 unsigned 7176 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7177 const BasicBlock *ExitingBlock) { 7178 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7179 assert(L->isLoopExiting(ExitingBlock) && 7180 "Exiting block must actually branch out of the loop!"); 7181 const SCEVConstant *ExitCount = 7182 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7183 return getConstantTripCount(ExitCount); 7184 } 7185 7186 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7187 const auto *MaxExitCount = 7188 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7189 return getConstantTripCount(MaxExitCount); 7190 } 7191 7192 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7193 SmallVector<BasicBlock *, 8> ExitingBlocks; 7194 L->getExitingBlocks(ExitingBlocks); 7195 7196 Optional<unsigned> Res = None; 7197 for (auto *ExitingBB : ExitingBlocks) { 7198 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7199 if (!Res) 7200 Res = Multiple; 7201 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7202 } 7203 return Res.getValueOr(1); 7204 } 7205 7206 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7207 const SCEV *ExitCount) { 7208 if (ExitCount == getCouldNotCompute()) 7209 return 1; 7210 7211 // Get the trip count 7212 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7213 7214 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7215 if (!TC) 7216 // Attempt to factor more general cases. Returns the greatest power of 7217 // two divisor. If overflow happens, the trip count expression is still 7218 // divisible by the greatest power of 2 divisor returned. 7219 return 1U << std::min((uint32_t)31, 7220 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7221 7222 ConstantInt *Result = TC->getValue(); 7223 7224 // Guard against huge trip counts (this requires checking 7225 // for zero to handle the case where the trip count == -1 and the 7226 // addition wraps). 7227 if (!Result || Result->getValue().getActiveBits() > 32 || 7228 Result->getValue().getActiveBits() == 0) 7229 return 1; 7230 7231 return (unsigned)Result->getZExtValue(); 7232 } 7233 7234 /// Returns the largest constant divisor of the trip count of this loop as a 7235 /// normal unsigned value, if possible. This means that the actual trip count is 7236 /// always a multiple of the returned value (don't forget the trip count could 7237 /// very well be zero as well!). 7238 /// 7239 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7240 /// multiple of a constant (which is also the case if the trip count is simply 7241 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7242 /// if the trip count is very large (>= 2^32). 7243 /// 7244 /// As explained in the comments for getSmallConstantTripCount, this assumes 7245 /// that control exits the loop via ExitingBlock. 7246 unsigned 7247 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7248 const BasicBlock *ExitingBlock) { 7249 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7250 assert(L->isLoopExiting(ExitingBlock) && 7251 "Exiting block must actually branch out of the loop!"); 7252 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7253 return getSmallConstantTripMultiple(L, ExitCount); 7254 } 7255 7256 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7257 const BasicBlock *ExitingBlock, 7258 ExitCountKind Kind) { 7259 switch (Kind) { 7260 case Exact: 7261 case SymbolicMaximum: 7262 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7263 case ConstantMaximum: 7264 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7265 }; 7266 llvm_unreachable("Invalid ExitCountKind!"); 7267 } 7268 7269 const SCEV * 7270 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7271 SCEVUnionPredicate &Preds) { 7272 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7273 } 7274 7275 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7276 ExitCountKind Kind) { 7277 switch (Kind) { 7278 case Exact: 7279 return getBackedgeTakenInfo(L).getExact(L, this); 7280 case ConstantMaximum: 7281 return getBackedgeTakenInfo(L).getConstantMax(this); 7282 case SymbolicMaximum: 7283 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7284 }; 7285 llvm_unreachable("Invalid ExitCountKind!"); 7286 } 7287 7288 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7289 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7290 } 7291 7292 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7293 static void 7294 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7295 BasicBlock *Header = L->getHeader(); 7296 7297 // Push all Loop-header PHIs onto the Worklist stack. 7298 for (PHINode &PN : Header->phis()) 7299 Worklist.push_back(&PN); 7300 } 7301 7302 const ScalarEvolution::BackedgeTakenInfo & 7303 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7304 auto &BTI = getBackedgeTakenInfo(L); 7305 if (BTI.hasFullInfo()) 7306 return BTI; 7307 7308 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7309 7310 if (!Pair.second) 7311 return Pair.first->second; 7312 7313 BackedgeTakenInfo Result = 7314 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7315 7316 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7317 } 7318 7319 ScalarEvolution::BackedgeTakenInfo & 7320 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7321 // Initially insert an invalid entry for this loop. If the insertion 7322 // succeeds, proceed to actually compute a backedge-taken count and 7323 // update the value. The temporary CouldNotCompute value tells SCEV 7324 // code elsewhere that it shouldn't attempt to request a new 7325 // backedge-taken count, which could result in infinite recursion. 7326 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7327 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7328 if (!Pair.second) 7329 return Pair.first->second; 7330 7331 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7332 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7333 // must be cleared in this scope. 7334 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7335 7336 // In product build, there are no usage of statistic. 7337 (void)NumTripCountsComputed; 7338 (void)NumTripCountsNotComputed; 7339 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7340 const SCEV *BEExact = Result.getExact(L, this); 7341 if (BEExact != getCouldNotCompute()) { 7342 assert(isLoopInvariant(BEExact, L) && 7343 isLoopInvariant(Result.getConstantMax(this), L) && 7344 "Computed backedge-taken count isn't loop invariant for loop!"); 7345 ++NumTripCountsComputed; 7346 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7347 isa<PHINode>(L->getHeader()->begin())) { 7348 // Only count loops that have phi nodes as not being computable. 7349 ++NumTripCountsNotComputed; 7350 } 7351 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7352 7353 // Now that we know more about the trip count for this loop, forget any 7354 // existing SCEV values for PHI nodes in this loop since they are only 7355 // conservative estimates made without the benefit of trip count 7356 // information. This is similar to the code in forgetLoop, except that 7357 // it handles SCEVUnknown PHI nodes specially. 7358 if (Result.hasAnyInfo()) { 7359 SmallVector<Instruction *, 16> Worklist; 7360 PushLoopPHIs(L, Worklist); 7361 7362 SmallPtrSet<Instruction *, 8> Discovered; 7363 while (!Worklist.empty()) { 7364 Instruction *I = Worklist.pop_back_val(); 7365 7366 ValueExprMapType::iterator It = 7367 ValueExprMap.find_as(static_cast<Value *>(I)); 7368 if (It != ValueExprMap.end()) { 7369 const SCEV *Old = It->second; 7370 7371 // SCEVUnknown for a PHI either means that it has an unrecognized 7372 // structure, or it's a PHI that's in the progress of being computed 7373 // by createNodeForPHI. In the former case, additional loop trip 7374 // count information isn't going to change anything. In the later 7375 // case, createNodeForPHI will perform the necessary updates on its 7376 // own when it gets to that point. 7377 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7378 eraseValueFromMap(It->first); 7379 forgetMemoizedResults(Old); 7380 } 7381 if (PHINode *PN = dyn_cast<PHINode>(I)) 7382 ConstantEvolutionLoopExitValue.erase(PN); 7383 } 7384 7385 // Since we don't need to invalidate anything for correctness and we're 7386 // only invalidating to make SCEV's results more precise, we get to stop 7387 // early to avoid invalidating too much. This is especially important in 7388 // cases like: 7389 // 7390 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7391 // loop0: 7392 // %pn0 = phi 7393 // ... 7394 // loop1: 7395 // %pn1 = phi 7396 // ... 7397 // 7398 // where both loop0 and loop1's backedge taken count uses the SCEV 7399 // expression for %v. If we don't have the early stop below then in cases 7400 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7401 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7402 // count for loop1, effectively nullifying SCEV's trip count cache. 7403 for (auto *U : I->users()) 7404 if (auto *I = dyn_cast<Instruction>(U)) { 7405 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7406 if (LoopForUser && L->contains(LoopForUser) && 7407 Discovered.insert(I).second) 7408 Worklist.push_back(I); 7409 } 7410 } 7411 } 7412 7413 // Re-lookup the insert position, since the call to 7414 // computeBackedgeTakenCount above could result in a 7415 // recusive call to getBackedgeTakenInfo (on a different 7416 // loop), which would invalidate the iterator computed 7417 // earlier. 7418 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7419 } 7420 7421 void ScalarEvolution::forgetAllLoops() { 7422 // This method is intended to forget all info about loops. It should 7423 // invalidate caches as if the following happened: 7424 // - The trip counts of all loops have changed arbitrarily 7425 // - Every llvm::Value has been updated in place to produce a different 7426 // result. 7427 BackedgeTakenCounts.clear(); 7428 PredicatedBackedgeTakenCounts.clear(); 7429 LoopPropertiesCache.clear(); 7430 ConstantEvolutionLoopExitValue.clear(); 7431 ValueExprMap.clear(); 7432 ValuesAtScopes.clear(); 7433 LoopDispositions.clear(); 7434 BlockDispositions.clear(); 7435 UnsignedRanges.clear(); 7436 SignedRanges.clear(); 7437 ExprValueMap.clear(); 7438 HasRecMap.clear(); 7439 MinTrailingZerosCache.clear(); 7440 PredicatedSCEVRewrites.clear(); 7441 } 7442 7443 void ScalarEvolution::forgetLoop(const Loop *L) { 7444 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7445 SmallVector<Instruction *, 32> Worklist; 7446 SmallPtrSet<Instruction *, 16> Visited; 7447 7448 // Iterate over all the loops and sub-loops to drop SCEV information. 7449 while (!LoopWorklist.empty()) { 7450 auto *CurrL = LoopWorklist.pop_back_val(); 7451 7452 // Drop any stored trip count value. 7453 BackedgeTakenCounts.erase(CurrL); 7454 PredicatedBackedgeTakenCounts.erase(CurrL); 7455 7456 // Drop information about predicated SCEV rewrites for this loop. 7457 for (auto I = PredicatedSCEVRewrites.begin(); 7458 I != PredicatedSCEVRewrites.end();) { 7459 std::pair<const SCEV *, const Loop *> Entry = I->first; 7460 if (Entry.second == CurrL) 7461 PredicatedSCEVRewrites.erase(I++); 7462 else 7463 ++I; 7464 } 7465 7466 auto LoopUsersItr = LoopUsers.find(CurrL); 7467 if (LoopUsersItr != LoopUsers.end()) { 7468 for (auto *S : LoopUsersItr->second) 7469 forgetMemoizedResults(S); 7470 LoopUsers.erase(LoopUsersItr); 7471 } 7472 7473 // Drop information about expressions based on loop-header PHIs. 7474 PushLoopPHIs(CurrL, Worklist); 7475 7476 while (!Worklist.empty()) { 7477 Instruction *I = Worklist.pop_back_val(); 7478 if (!Visited.insert(I).second) 7479 continue; 7480 7481 ValueExprMapType::iterator It = 7482 ValueExprMap.find_as(static_cast<Value *>(I)); 7483 if (It != ValueExprMap.end()) { 7484 eraseValueFromMap(It->first); 7485 forgetMemoizedResults(It->second); 7486 if (PHINode *PN = dyn_cast<PHINode>(I)) 7487 ConstantEvolutionLoopExitValue.erase(PN); 7488 } 7489 7490 PushDefUseChildren(I, Worklist); 7491 } 7492 7493 LoopPropertiesCache.erase(CurrL); 7494 // Forget all contained loops too, to avoid dangling entries in the 7495 // ValuesAtScopes map. 7496 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7497 } 7498 } 7499 7500 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7501 while (Loop *Parent = L->getParentLoop()) 7502 L = Parent; 7503 forgetLoop(L); 7504 } 7505 7506 void ScalarEvolution::forgetValue(Value *V) { 7507 Instruction *I = dyn_cast<Instruction>(V); 7508 if (!I) return; 7509 7510 // Drop information about expressions based on loop-header PHIs. 7511 SmallVector<Instruction *, 16> Worklist; 7512 Worklist.push_back(I); 7513 7514 SmallPtrSet<Instruction *, 8> Visited; 7515 while (!Worklist.empty()) { 7516 I = Worklist.pop_back_val(); 7517 if (!Visited.insert(I).second) 7518 continue; 7519 7520 ValueExprMapType::iterator It = 7521 ValueExprMap.find_as(static_cast<Value *>(I)); 7522 if (It != ValueExprMap.end()) { 7523 eraseValueFromMap(It->first); 7524 forgetMemoizedResults(It->second); 7525 if (PHINode *PN = dyn_cast<PHINode>(I)) 7526 ConstantEvolutionLoopExitValue.erase(PN); 7527 } 7528 7529 PushDefUseChildren(I, Worklist); 7530 } 7531 } 7532 7533 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7534 LoopDispositions.clear(); 7535 } 7536 7537 /// Get the exact loop backedge taken count considering all loop exits. A 7538 /// computable result can only be returned for loops with all exiting blocks 7539 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7540 /// is never skipped. This is a valid assumption as long as the loop exits via 7541 /// that test. For precise results, it is the caller's responsibility to specify 7542 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7543 const SCEV * 7544 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7545 SCEVUnionPredicate *Preds) const { 7546 // If any exits were not computable, the loop is not computable. 7547 if (!isComplete() || ExitNotTaken.empty()) 7548 return SE->getCouldNotCompute(); 7549 7550 const BasicBlock *Latch = L->getLoopLatch(); 7551 // All exiting blocks we have collected must dominate the only backedge. 7552 if (!Latch) 7553 return SE->getCouldNotCompute(); 7554 7555 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7556 // count is simply a minimum out of all these calculated exit counts. 7557 SmallVector<const SCEV *, 2> Ops; 7558 for (auto &ENT : ExitNotTaken) { 7559 const SCEV *BECount = ENT.ExactNotTaken; 7560 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7561 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7562 "We should only have known counts for exiting blocks that dominate " 7563 "latch!"); 7564 7565 Ops.push_back(BECount); 7566 7567 if (Preds && !ENT.hasAlwaysTruePredicate()) 7568 Preds->add(ENT.Predicate.get()); 7569 7570 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7571 "Predicate should be always true!"); 7572 } 7573 7574 return SE->getUMinFromMismatchedTypes(Ops); 7575 } 7576 7577 /// Get the exact not taken count for this loop exit. 7578 const SCEV * 7579 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7580 ScalarEvolution *SE) const { 7581 for (auto &ENT : ExitNotTaken) 7582 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7583 return ENT.ExactNotTaken; 7584 7585 return SE->getCouldNotCompute(); 7586 } 7587 7588 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7589 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7590 for (auto &ENT : ExitNotTaken) 7591 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7592 return ENT.MaxNotTaken; 7593 7594 return SE->getCouldNotCompute(); 7595 } 7596 7597 /// getConstantMax - Get the constant max backedge taken count for the loop. 7598 const SCEV * 7599 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7600 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7601 return !ENT.hasAlwaysTruePredicate(); 7602 }; 7603 7604 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7605 return SE->getCouldNotCompute(); 7606 7607 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7608 isa<SCEVConstant>(getConstantMax())) && 7609 "No point in having a non-constant max backedge taken count!"); 7610 return getConstantMax(); 7611 } 7612 7613 const SCEV * 7614 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7615 ScalarEvolution *SE) { 7616 if (!SymbolicMax) 7617 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7618 return SymbolicMax; 7619 } 7620 7621 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7622 ScalarEvolution *SE) const { 7623 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7624 return !ENT.hasAlwaysTruePredicate(); 7625 }; 7626 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7627 } 7628 7629 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7630 return Operands.contains(S); 7631 } 7632 7633 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7634 : ExitLimit(E, E, false, None) { 7635 } 7636 7637 ScalarEvolution::ExitLimit::ExitLimit( 7638 const SCEV *E, const SCEV *M, bool MaxOrZero, 7639 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7640 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7641 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7642 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7643 "Exact is not allowed to be less precise than Max"); 7644 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7645 isa<SCEVConstant>(MaxNotTaken)) && 7646 "No point in having a non-constant max backedge taken count!"); 7647 for (auto *PredSet : PredSetList) 7648 for (auto *P : *PredSet) 7649 addPredicate(P); 7650 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7651 "Backedge count should be int"); 7652 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7653 "Max backedge count should be int"); 7654 } 7655 7656 ScalarEvolution::ExitLimit::ExitLimit( 7657 const SCEV *E, const SCEV *M, bool MaxOrZero, 7658 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7659 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7660 } 7661 7662 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7663 bool MaxOrZero) 7664 : ExitLimit(E, M, MaxOrZero, None) { 7665 } 7666 7667 class SCEVRecordOperands { 7668 SmallPtrSetImpl<const SCEV *> &Operands; 7669 7670 public: 7671 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7672 : Operands(Operands) {} 7673 bool follow(const SCEV *S) { 7674 Operands.insert(S); 7675 return true; 7676 } 7677 bool isDone() { return false; } 7678 }; 7679 7680 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7681 /// computable exit into a persistent ExitNotTakenInfo array. 7682 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7683 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7684 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7685 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7686 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7687 7688 ExitNotTaken.reserve(ExitCounts.size()); 7689 std::transform( 7690 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7691 [&](const EdgeExitInfo &EEI) { 7692 BasicBlock *ExitBB = EEI.first; 7693 const ExitLimit &EL = EEI.second; 7694 if (EL.Predicates.empty()) 7695 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7696 nullptr); 7697 7698 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7699 for (auto *Pred : EL.Predicates) 7700 Predicate->add(Pred); 7701 7702 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7703 std::move(Predicate)); 7704 }); 7705 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7706 isa<SCEVConstant>(ConstantMax)) && 7707 "No point in having a non-constant max backedge taken count!"); 7708 7709 SCEVRecordOperands RecordOperands(Operands); 7710 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7711 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7712 ST.visitAll(ConstantMax); 7713 for (auto &ENT : ExitNotTaken) 7714 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7715 ST.visitAll(ENT.ExactNotTaken); 7716 } 7717 7718 /// Compute the number of times the backedge of the specified loop will execute. 7719 ScalarEvolution::BackedgeTakenInfo 7720 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7721 bool AllowPredicates) { 7722 SmallVector<BasicBlock *, 8> ExitingBlocks; 7723 L->getExitingBlocks(ExitingBlocks); 7724 7725 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7726 7727 SmallVector<EdgeExitInfo, 4> ExitCounts; 7728 bool CouldComputeBECount = true; 7729 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7730 const SCEV *MustExitMaxBECount = nullptr; 7731 const SCEV *MayExitMaxBECount = nullptr; 7732 bool MustExitMaxOrZero = false; 7733 7734 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7735 // and compute maxBECount. 7736 // Do a union of all the predicates here. 7737 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7738 BasicBlock *ExitBB = ExitingBlocks[i]; 7739 7740 // We canonicalize untaken exits to br (constant), ignore them so that 7741 // proving an exit untaken doesn't negatively impact our ability to reason 7742 // about the loop as whole. 7743 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7744 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7745 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7746 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7747 continue; 7748 } 7749 7750 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7751 7752 assert((AllowPredicates || EL.Predicates.empty()) && 7753 "Predicated exit limit when predicates are not allowed!"); 7754 7755 // 1. For each exit that can be computed, add an entry to ExitCounts. 7756 // CouldComputeBECount is true only if all exits can be computed. 7757 if (EL.ExactNotTaken == getCouldNotCompute()) 7758 // We couldn't compute an exact value for this exit, so 7759 // we won't be able to compute an exact value for the loop. 7760 CouldComputeBECount = false; 7761 else 7762 ExitCounts.emplace_back(ExitBB, EL); 7763 7764 // 2. Derive the loop's MaxBECount from each exit's max number of 7765 // non-exiting iterations. Partition the loop exits into two kinds: 7766 // LoopMustExits and LoopMayExits. 7767 // 7768 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7769 // is a LoopMayExit. If any computable LoopMustExit is found, then 7770 // MaxBECount is the minimum EL.MaxNotTaken of computable 7771 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7772 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7773 // computable EL.MaxNotTaken. 7774 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7775 DT.dominates(ExitBB, Latch)) { 7776 if (!MustExitMaxBECount) { 7777 MustExitMaxBECount = EL.MaxNotTaken; 7778 MustExitMaxOrZero = EL.MaxOrZero; 7779 } else { 7780 MustExitMaxBECount = 7781 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7782 } 7783 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7784 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7785 MayExitMaxBECount = EL.MaxNotTaken; 7786 else { 7787 MayExitMaxBECount = 7788 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7789 } 7790 } 7791 } 7792 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7793 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7794 // The loop backedge will be taken the maximum or zero times if there's 7795 // a single exit that must be taken the maximum or zero times. 7796 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7797 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7798 MaxBECount, MaxOrZero); 7799 } 7800 7801 ScalarEvolution::ExitLimit 7802 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7803 bool AllowPredicates) { 7804 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7805 // If our exiting block does not dominate the latch, then its connection with 7806 // loop's exit limit may be far from trivial. 7807 const BasicBlock *Latch = L->getLoopLatch(); 7808 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7809 return getCouldNotCompute(); 7810 7811 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7812 Instruction *Term = ExitingBlock->getTerminator(); 7813 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7814 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7815 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7816 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7817 "It should have one successor in loop and one exit block!"); 7818 // Proceed to the next level to examine the exit condition expression. 7819 return computeExitLimitFromCond( 7820 L, BI->getCondition(), ExitIfTrue, 7821 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7822 } 7823 7824 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7825 // For switch, make sure that there is a single exit from the loop. 7826 BasicBlock *Exit = nullptr; 7827 for (auto *SBB : successors(ExitingBlock)) 7828 if (!L->contains(SBB)) { 7829 if (Exit) // Multiple exit successors. 7830 return getCouldNotCompute(); 7831 Exit = SBB; 7832 } 7833 assert(Exit && "Exiting block must have at least one exit"); 7834 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7835 /*ControlsExit=*/IsOnlyExit); 7836 } 7837 7838 return getCouldNotCompute(); 7839 } 7840 7841 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7842 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7843 bool ControlsExit, bool AllowPredicates) { 7844 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7845 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7846 ControlsExit, AllowPredicates); 7847 } 7848 7849 Optional<ScalarEvolution::ExitLimit> 7850 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7851 bool ExitIfTrue, bool ControlsExit, 7852 bool AllowPredicates) { 7853 (void)this->L; 7854 (void)this->ExitIfTrue; 7855 (void)this->AllowPredicates; 7856 7857 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7858 this->AllowPredicates == AllowPredicates && 7859 "Variance in assumed invariant key components!"); 7860 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7861 if (Itr == TripCountMap.end()) 7862 return None; 7863 return Itr->second; 7864 } 7865 7866 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7867 bool ExitIfTrue, 7868 bool ControlsExit, 7869 bool AllowPredicates, 7870 const ExitLimit &EL) { 7871 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7872 this->AllowPredicates == AllowPredicates && 7873 "Variance in assumed invariant key components!"); 7874 7875 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7876 assert(InsertResult.second && "Expected successful insertion!"); 7877 (void)InsertResult; 7878 (void)ExitIfTrue; 7879 } 7880 7881 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7882 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7883 bool ControlsExit, bool AllowPredicates) { 7884 7885 if (auto MaybeEL = 7886 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7887 return *MaybeEL; 7888 7889 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7890 ControlsExit, AllowPredicates); 7891 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7892 return EL; 7893 } 7894 7895 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7896 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7897 bool ControlsExit, bool AllowPredicates) { 7898 // Handle BinOp conditions (And, Or). 7899 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7900 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7901 return *LimitFromBinOp; 7902 7903 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7904 // Proceed to the next level to examine the icmp. 7905 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7906 ExitLimit EL = 7907 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7908 if (EL.hasFullInfo() || !AllowPredicates) 7909 return EL; 7910 7911 // Try again, but use SCEV predicates this time. 7912 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7913 /*AllowPredicates=*/true); 7914 } 7915 7916 // Check for a constant condition. These are normally stripped out by 7917 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7918 // preserve the CFG and is temporarily leaving constant conditions 7919 // in place. 7920 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7921 if (ExitIfTrue == !CI->getZExtValue()) 7922 // The backedge is always taken. 7923 return getCouldNotCompute(); 7924 else 7925 // The backedge is never taken. 7926 return getZero(CI->getType()); 7927 } 7928 7929 // If it's not an integer or pointer comparison then compute it the hard way. 7930 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7931 } 7932 7933 Optional<ScalarEvolution::ExitLimit> 7934 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7935 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7936 bool ControlsExit, bool AllowPredicates) { 7937 // Check if the controlling expression for this loop is an And or Or. 7938 Value *Op0, *Op1; 7939 bool IsAnd = false; 7940 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7941 IsAnd = true; 7942 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7943 IsAnd = false; 7944 else 7945 return None; 7946 7947 // EitherMayExit is true in these two cases: 7948 // br (and Op0 Op1), loop, exit 7949 // br (or Op0 Op1), exit, loop 7950 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7951 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7952 ControlsExit && !EitherMayExit, 7953 AllowPredicates); 7954 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7955 ControlsExit && !EitherMayExit, 7956 AllowPredicates); 7957 7958 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7959 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7960 if (isa<ConstantInt>(Op1)) 7961 return Op1 == NeutralElement ? EL0 : EL1; 7962 if (isa<ConstantInt>(Op0)) 7963 return Op0 == NeutralElement ? EL1 : EL0; 7964 7965 const SCEV *BECount = getCouldNotCompute(); 7966 const SCEV *MaxBECount = getCouldNotCompute(); 7967 if (EitherMayExit) { 7968 // Both conditions must be same for the loop to continue executing. 7969 // Choose the less conservative count. 7970 // If ExitCond is a short-circuit form (select), using 7971 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7972 // To see the detailed examples, please see 7973 // test/Analysis/ScalarEvolution/exit-count-select.ll 7974 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7975 if (!PoisonSafe) 7976 // Even if ExitCond is select, we can safely derive BECount using both 7977 // EL0 and EL1 in these cases: 7978 // (1) EL0.ExactNotTaken is non-zero 7979 // (2) EL1.ExactNotTaken is non-poison 7980 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7981 // it cannot be umin(0, ..)) 7982 // The PoisonSafe assignment below is simplified and the assertion after 7983 // BECount calculation fully guarantees the condition (3). 7984 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7985 isa<SCEVConstant>(EL1.ExactNotTaken); 7986 if (EL0.ExactNotTaken != getCouldNotCompute() && 7987 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7988 BECount = 7989 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7990 7991 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7992 // it should have been simplified to zero (see the condition (3) above) 7993 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7994 BECount->isZero()); 7995 } 7996 if (EL0.MaxNotTaken == getCouldNotCompute()) 7997 MaxBECount = EL1.MaxNotTaken; 7998 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7999 MaxBECount = EL0.MaxNotTaken; 8000 else 8001 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8002 } else { 8003 // Both conditions must be same at the same time for the loop to exit. 8004 // For now, be conservative. 8005 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8006 BECount = EL0.ExactNotTaken; 8007 } 8008 8009 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8010 // to be more aggressive when computing BECount than when computing 8011 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8012 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8013 // to not. 8014 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8015 !isa<SCEVCouldNotCompute>(BECount)) 8016 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8017 8018 return ExitLimit(BECount, MaxBECount, false, 8019 { &EL0.Predicates, &EL1.Predicates }); 8020 } 8021 8022 ScalarEvolution::ExitLimit 8023 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8024 ICmpInst *ExitCond, 8025 bool ExitIfTrue, 8026 bool ControlsExit, 8027 bool AllowPredicates) { 8028 // If the condition was exit on true, convert the condition to exit on false 8029 ICmpInst::Predicate Pred; 8030 if (!ExitIfTrue) 8031 Pred = ExitCond->getPredicate(); 8032 else 8033 Pred = ExitCond->getInversePredicate(); 8034 const ICmpInst::Predicate OriginalPred = Pred; 8035 8036 // Handle common loops like: for (X = "string"; *X; ++X) 8037 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 8038 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 8039 ExitLimit ItCnt = 8040 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 8041 if (ItCnt.hasAnyInfo()) 8042 return ItCnt; 8043 } 8044 8045 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8046 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8047 8048 // Try to evaluate any dependencies out of the loop. 8049 LHS = getSCEVAtScope(LHS, L); 8050 RHS = getSCEVAtScope(RHS, L); 8051 8052 // At this point, we would like to compute how many iterations of the 8053 // loop the predicate will return true for these inputs. 8054 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8055 // If there is a loop-invariant, force it into the RHS. 8056 std::swap(LHS, RHS); 8057 Pred = ICmpInst::getSwappedPredicate(Pred); 8058 } 8059 8060 // Simplify the operands before analyzing them. 8061 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8062 8063 // If we have a comparison of a chrec against a constant, try to use value 8064 // ranges to answer this query. 8065 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8066 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8067 if (AddRec->getLoop() == L) { 8068 // Form the constant range. 8069 ConstantRange CompRange = 8070 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8071 8072 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8073 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8074 } 8075 8076 switch (Pred) { 8077 case ICmpInst::ICMP_NE: { // while (X != Y) 8078 // Convert to: while (X-Y != 0) 8079 if (LHS->getType()->isPointerTy()) { 8080 LHS = getLosslessPtrToIntExpr(LHS); 8081 if (isa<SCEVCouldNotCompute>(LHS)) 8082 return LHS; 8083 } 8084 if (RHS->getType()->isPointerTy()) { 8085 RHS = getLosslessPtrToIntExpr(RHS); 8086 if (isa<SCEVCouldNotCompute>(RHS)) 8087 return RHS; 8088 } 8089 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8090 AllowPredicates); 8091 if (EL.hasAnyInfo()) return EL; 8092 break; 8093 } 8094 case ICmpInst::ICMP_EQ: { // while (X == Y) 8095 // Convert to: while (X-Y == 0) 8096 if (LHS->getType()->isPointerTy()) { 8097 LHS = getLosslessPtrToIntExpr(LHS); 8098 if (isa<SCEVCouldNotCompute>(LHS)) 8099 return LHS; 8100 } 8101 if (RHS->getType()->isPointerTy()) { 8102 RHS = getLosslessPtrToIntExpr(RHS); 8103 if (isa<SCEVCouldNotCompute>(RHS)) 8104 return RHS; 8105 } 8106 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8107 if (EL.hasAnyInfo()) return EL; 8108 break; 8109 } 8110 case ICmpInst::ICMP_SLT: 8111 case ICmpInst::ICMP_ULT: { // while (X < Y) 8112 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8113 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8114 AllowPredicates); 8115 if (EL.hasAnyInfo()) return EL; 8116 break; 8117 } 8118 case ICmpInst::ICMP_SGT: 8119 case ICmpInst::ICMP_UGT: { // while (X > Y) 8120 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8121 ExitLimit EL = 8122 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8123 AllowPredicates); 8124 if (EL.hasAnyInfo()) return EL; 8125 break; 8126 } 8127 default: 8128 break; 8129 } 8130 8131 auto *ExhaustiveCount = 8132 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8133 8134 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8135 return ExhaustiveCount; 8136 8137 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8138 ExitCond->getOperand(1), L, OriginalPred); 8139 } 8140 8141 ScalarEvolution::ExitLimit 8142 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8143 SwitchInst *Switch, 8144 BasicBlock *ExitingBlock, 8145 bool ControlsExit) { 8146 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8147 8148 // Give up if the exit is the default dest of a switch. 8149 if (Switch->getDefaultDest() == ExitingBlock) 8150 return getCouldNotCompute(); 8151 8152 assert(L->contains(Switch->getDefaultDest()) && 8153 "Default case must not exit the loop!"); 8154 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8155 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8156 8157 // while (X != Y) --> while (X-Y != 0) 8158 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8159 if (EL.hasAnyInfo()) 8160 return EL; 8161 8162 return getCouldNotCompute(); 8163 } 8164 8165 static ConstantInt * 8166 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8167 ScalarEvolution &SE) { 8168 const SCEV *InVal = SE.getConstant(C); 8169 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8170 assert(isa<SCEVConstant>(Val) && 8171 "Evaluation of SCEV at constant didn't fold correctly?"); 8172 return cast<SCEVConstant>(Val)->getValue(); 8173 } 8174 8175 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8176 /// compute the backedge execution count. 8177 ScalarEvolution::ExitLimit 8178 ScalarEvolution::computeLoadConstantCompareExitLimit( 8179 LoadInst *LI, 8180 Constant *RHS, 8181 const Loop *L, 8182 ICmpInst::Predicate predicate) { 8183 if (LI->isVolatile()) return getCouldNotCompute(); 8184 8185 // Check to see if the loaded pointer is a getelementptr of a global. 8186 // TODO: Use SCEV instead of manually grubbing with GEPs. 8187 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8188 if (!GEP) return getCouldNotCompute(); 8189 8190 // Make sure that it is really a constant global we are gepping, with an 8191 // initializer, and make sure the first IDX is really 0. 8192 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8193 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8194 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8195 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8196 return getCouldNotCompute(); 8197 8198 // Okay, we allow one non-constant index into the GEP instruction. 8199 Value *VarIdx = nullptr; 8200 std::vector<Constant*> Indexes; 8201 unsigned VarIdxNum = 0; 8202 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8203 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8204 Indexes.push_back(CI); 8205 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8206 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8207 VarIdx = GEP->getOperand(i); 8208 VarIdxNum = i-2; 8209 Indexes.push_back(nullptr); 8210 } 8211 8212 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8213 if (!VarIdx) 8214 return getCouldNotCompute(); 8215 8216 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8217 // Check to see if X is a loop variant variable value now. 8218 const SCEV *Idx = getSCEV(VarIdx); 8219 Idx = getSCEVAtScope(Idx, L); 8220 8221 // We can only recognize very limited forms of loop index expressions, in 8222 // particular, only affine AddRec's like {C1,+,C2}<L>. 8223 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8224 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8225 isLoopInvariant(IdxExpr, L) || 8226 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8227 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8228 return getCouldNotCompute(); 8229 8230 unsigned MaxSteps = MaxBruteForceIterations; 8231 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8232 ConstantInt *ItCst = ConstantInt::get( 8233 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8234 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8235 8236 // Form the GEP offset. 8237 Indexes[VarIdxNum] = Val; 8238 8239 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8240 Indexes); 8241 if (!Result) break; // Cannot compute! 8242 8243 // Evaluate the condition for this iteration. 8244 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8245 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8246 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8247 ++NumArrayLenItCounts; 8248 return getConstant(ItCst); // Found terminating iteration! 8249 } 8250 } 8251 return getCouldNotCompute(); 8252 } 8253 8254 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8255 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8256 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8257 if (!RHS) 8258 return getCouldNotCompute(); 8259 8260 const BasicBlock *Latch = L->getLoopLatch(); 8261 if (!Latch) 8262 return getCouldNotCompute(); 8263 8264 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8265 if (!Predecessor) 8266 return getCouldNotCompute(); 8267 8268 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8269 // Return LHS in OutLHS and shift_opt in OutOpCode. 8270 auto MatchPositiveShift = 8271 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8272 8273 using namespace PatternMatch; 8274 8275 ConstantInt *ShiftAmt; 8276 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8277 OutOpCode = Instruction::LShr; 8278 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8279 OutOpCode = Instruction::AShr; 8280 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8281 OutOpCode = Instruction::Shl; 8282 else 8283 return false; 8284 8285 return ShiftAmt->getValue().isStrictlyPositive(); 8286 }; 8287 8288 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8289 // 8290 // loop: 8291 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8292 // %iv.shifted = lshr i32 %iv, <positive constant> 8293 // 8294 // Return true on a successful match. Return the corresponding PHI node (%iv 8295 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8296 auto MatchShiftRecurrence = 8297 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8298 Optional<Instruction::BinaryOps> PostShiftOpCode; 8299 8300 { 8301 Instruction::BinaryOps OpC; 8302 Value *V; 8303 8304 // If we encounter a shift instruction, "peel off" the shift operation, 8305 // and remember that we did so. Later when we inspect %iv's backedge 8306 // value, we will make sure that the backedge value uses the same 8307 // operation. 8308 // 8309 // Note: the peeled shift operation does not have to be the same 8310 // instruction as the one feeding into the PHI's backedge value. We only 8311 // really care about it being the same *kind* of shift instruction -- 8312 // that's all that is required for our later inferences to hold. 8313 if (MatchPositiveShift(LHS, V, OpC)) { 8314 PostShiftOpCode = OpC; 8315 LHS = V; 8316 } 8317 } 8318 8319 PNOut = dyn_cast<PHINode>(LHS); 8320 if (!PNOut || PNOut->getParent() != L->getHeader()) 8321 return false; 8322 8323 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8324 Value *OpLHS; 8325 8326 return 8327 // The backedge value for the PHI node must be a shift by a positive 8328 // amount 8329 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8330 8331 // of the PHI node itself 8332 OpLHS == PNOut && 8333 8334 // and the kind of shift should be match the kind of shift we peeled 8335 // off, if any. 8336 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8337 }; 8338 8339 PHINode *PN; 8340 Instruction::BinaryOps OpCode; 8341 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8342 return getCouldNotCompute(); 8343 8344 const DataLayout &DL = getDataLayout(); 8345 8346 // The key rationale for this optimization is that for some kinds of shift 8347 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8348 // within a finite number of iterations. If the condition guarding the 8349 // backedge (in the sense that the backedge is taken if the condition is true) 8350 // is false for the value the shift recurrence stabilizes to, then we know 8351 // that the backedge is taken only a finite number of times. 8352 8353 ConstantInt *StableValue = nullptr; 8354 switch (OpCode) { 8355 default: 8356 llvm_unreachable("Impossible case!"); 8357 8358 case Instruction::AShr: { 8359 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8360 // bitwidth(K) iterations. 8361 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8362 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8363 Predecessor->getTerminator(), &DT); 8364 auto *Ty = cast<IntegerType>(RHS->getType()); 8365 if (Known.isNonNegative()) 8366 StableValue = ConstantInt::get(Ty, 0); 8367 else if (Known.isNegative()) 8368 StableValue = ConstantInt::get(Ty, -1, true); 8369 else 8370 return getCouldNotCompute(); 8371 8372 break; 8373 } 8374 case Instruction::LShr: 8375 case Instruction::Shl: 8376 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8377 // stabilize to 0 in at most bitwidth(K) iterations. 8378 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8379 break; 8380 } 8381 8382 auto *Result = 8383 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8384 assert(Result->getType()->isIntegerTy(1) && 8385 "Otherwise cannot be an operand to a branch instruction"); 8386 8387 if (Result->isZeroValue()) { 8388 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8389 const SCEV *UpperBound = 8390 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8391 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8392 } 8393 8394 return getCouldNotCompute(); 8395 } 8396 8397 /// Return true if we can constant fold an instruction of the specified type, 8398 /// assuming that all operands were constants. 8399 static bool CanConstantFold(const Instruction *I) { 8400 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8401 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8402 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8403 return true; 8404 8405 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8406 if (const Function *F = CI->getCalledFunction()) 8407 return canConstantFoldCallTo(CI, F); 8408 return false; 8409 } 8410 8411 /// Determine whether this instruction can constant evolve within this loop 8412 /// assuming its operands can all constant evolve. 8413 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8414 // An instruction outside of the loop can't be derived from a loop PHI. 8415 if (!L->contains(I)) return false; 8416 8417 if (isa<PHINode>(I)) { 8418 // We don't currently keep track of the control flow needed to evaluate 8419 // PHIs, so we cannot handle PHIs inside of loops. 8420 return L->getHeader() == I->getParent(); 8421 } 8422 8423 // If we won't be able to constant fold this expression even if the operands 8424 // are constants, bail early. 8425 return CanConstantFold(I); 8426 } 8427 8428 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8429 /// recursing through each instruction operand until reaching a loop header phi. 8430 static PHINode * 8431 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8432 DenseMap<Instruction *, PHINode *> &PHIMap, 8433 unsigned Depth) { 8434 if (Depth > MaxConstantEvolvingDepth) 8435 return nullptr; 8436 8437 // Otherwise, we can evaluate this instruction if all of its operands are 8438 // constant or derived from a PHI node themselves. 8439 PHINode *PHI = nullptr; 8440 for (Value *Op : UseInst->operands()) { 8441 if (isa<Constant>(Op)) continue; 8442 8443 Instruction *OpInst = dyn_cast<Instruction>(Op); 8444 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8445 8446 PHINode *P = dyn_cast<PHINode>(OpInst); 8447 if (!P) 8448 // If this operand is already visited, reuse the prior result. 8449 // We may have P != PHI if this is the deepest point at which the 8450 // inconsistent paths meet. 8451 P = PHIMap.lookup(OpInst); 8452 if (!P) { 8453 // Recurse and memoize the results, whether a phi is found or not. 8454 // This recursive call invalidates pointers into PHIMap. 8455 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8456 PHIMap[OpInst] = P; 8457 } 8458 if (!P) 8459 return nullptr; // Not evolving from PHI 8460 if (PHI && PHI != P) 8461 return nullptr; // Evolving from multiple different PHIs. 8462 PHI = P; 8463 } 8464 // This is a expression evolving from a constant PHI! 8465 return PHI; 8466 } 8467 8468 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8469 /// in the loop that V is derived from. We allow arbitrary operations along the 8470 /// way, but the operands of an operation must either be constants or a value 8471 /// derived from a constant PHI. If this expression does not fit with these 8472 /// constraints, return null. 8473 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8474 Instruction *I = dyn_cast<Instruction>(V); 8475 if (!I || !canConstantEvolve(I, L)) return nullptr; 8476 8477 if (PHINode *PN = dyn_cast<PHINode>(I)) 8478 return PN; 8479 8480 // Record non-constant instructions contained by the loop. 8481 DenseMap<Instruction *, PHINode *> PHIMap; 8482 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8483 } 8484 8485 /// EvaluateExpression - Given an expression that passes the 8486 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8487 /// in the loop has the value PHIVal. If we can't fold this expression for some 8488 /// reason, return null. 8489 static Constant *EvaluateExpression(Value *V, const Loop *L, 8490 DenseMap<Instruction *, Constant *> &Vals, 8491 const DataLayout &DL, 8492 const TargetLibraryInfo *TLI) { 8493 // Convenient constant check, but redundant for recursive calls. 8494 if (Constant *C = dyn_cast<Constant>(V)) return C; 8495 Instruction *I = dyn_cast<Instruction>(V); 8496 if (!I) return nullptr; 8497 8498 if (Constant *C = Vals.lookup(I)) return C; 8499 8500 // An instruction inside the loop depends on a value outside the loop that we 8501 // weren't given a mapping for, or a value such as a call inside the loop. 8502 if (!canConstantEvolve(I, L)) return nullptr; 8503 8504 // An unmapped PHI can be due to a branch or another loop inside this loop, 8505 // or due to this not being the initial iteration through a loop where we 8506 // couldn't compute the evolution of this particular PHI last time. 8507 if (isa<PHINode>(I)) return nullptr; 8508 8509 std::vector<Constant*> Operands(I->getNumOperands()); 8510 8511 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8512 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8513 if (!Operand) { 8514 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8515 if (!Operands[i]) return nullptr; 8516 continue; 8517 } 8518 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8519 Vals[Operand] = C; 8520 if (!C) return nullptr; 8521 Operands[i] = C; 8522 } 8523 8524 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8525 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8526 Operands[1], DL, TLI); 8527 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8528 if (!LI->isVolatile()) 8529 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8530 } 8531 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8532 } 8533 8534 8535 // If every incoming value to PN except the one for BB is a specific Constant, 8536 // return that, else return nullptr. 8537 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8538 Constant *IncomingVal = nullptr; 8539 8540 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8541 if (PN->getIncomingBlock(i) == BB) 8542 continue; 8543 8544 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8545 if (!CurrentVal) 8546 return nullptr; 8547 8548 if (IncomingVal != CurrentVal) { 8549 if (IncomingVal) 8550 return nullptr; 8551 IncomingVal = CurrentVal; 8552 } 8553 } 8554 8555 return IncomingVal; 8556 } 8557 8558 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8559 /// in the header of its containing loop, we know the loop executes a 8560 /// constant number of times, and the PHI node is just a recurrence 8561 /// involving constants, fold it. 8562 Constant * 8563 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8564 const APInt &BEs, 8565 const Loop *L) { 8566 auto I = ConstantEvolutionLoopExitValue.find(PN); 8567 if (I != ConstantEvolutionLoopExitValue.end()) 8568 return I->second; 8569 8570 if (BEs.ugt(MaxBruteForceIterations)) 8571 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8572 8573 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8574 8575 DenseMap<Instruction *, Constant *> CurrentIterVals; 8576 BasicBlock *Header = L->getHeader(); 8577 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8578 8579 BasicBlock *Latch = L->getLoopLatch(); 8580 if (!Latch) 8581 return nullptr; 8582 8583 for (PHINode &PHI : Header->phis()) { 8584 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8585 CurrentIterVals[&PHI] = StartCST; 8586 } 8587 if (!CurrentIterVals.count(PN)) 8588 return RetVal = nullptr; 8589 8590 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8591 8592 // Execute the loop symbolically to determine the exit value. 8593 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8594 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8595 8596 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8597 unsigned IterationNum = 0; 8598 const DataLayout &DL = getDataLayout(); 8599 for (; ; ++IterationNum) { 8600 if (IterationNum == NumIterations) 8601 return RetVal = CurrentIterVals[PN]; // Got exit value! 8602 8603 // Compute the value of the PHIs for the next iteration. 8604 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8605 DenseMap<Instruction *, Constant *> NextIterVals; 8606 Constant *NextPHI = 8607 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8608 if (!NextPHI) 8609 return nullptr; // Couldn't evaluate! 8610 NextIterVals[PN] = NextPHI; 8611 8612 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8613 8614 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8615 // cease to be able to evaluate one of them or if they stop evolving, 8616 // because that doesn't necessarily prevent us from computing PN. 8617 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8618 for (const auto &I : CurrentIterVals) { 8619 PHINode *PHI = dyn_cast<PHINode>(I.first); 8620 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8621 PHIsToCompute.emplace_back(PHI, I.second); 8622 } 8623 // We use two distinct loops because EvaluateExpression may invalidate any 8624 // iterators into CurrentIterVals. 8625 for (const auto &I : PHIsToCompute) { 8626 PHINode *PHI = I.first; 8627 Constant *&NextPHI = NextIterVals[PHI]; 8628 if (!NextPHI) { // Not already computed. 8629 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8630 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8631 } 8632 if (NextPHI != I.second) 8633 StoppedEvolving = false; 8634 } 8635 8636 // If all entries in CurrentIterVals == NextIterVals then we can stop 8637 // iterating, the loop can't continue to change. 8638 if (StoppedEvolving) 8639 return RetVal = CurrentIterVals[PN]; 8640 8641 CurrentIterVals.swap(NextIterVals); 8642 } 8643 } 8644 8645 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8646 Value *Cond, 8647 bool ExitWhen) { 8648 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8649 if (!PN) return getCouldNotCompute(); 8650 8651 // If the loop is canonicalized, the PHI will have exactly two entries. 8652 // That's the only form we support here. 8653 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8654 8655 DenseMap<Instruction *, Constant *> CurrentIterVals; 8656 BasicBlock *Header = L->getHeader(); 8657 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8658 8659 BasicBlock *Latch = L->getLoopLatch(); 8660 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8661 8662 for (PHINode &PHI : Header->phis()) { 8663 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8664 CurrentIterVals[&PHI] = StartCST; 8665 } 8666 if (!CurrentIterVals.count(PN)) 8667 return getCouldNotCompute(); 8668 8669 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8670 // the loop symbolically to determine when the condition gets a value of 8671 // "ExitWhen". 8672 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8673 const DataLayout &DL = getDataLayout(); 8674 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8675 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8676 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8677 8678 // Couldn't symbolically evaluate. 8679 if (!CondVal) return getCouldNotCompute(); 8680 8681 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8682 ++NumBruteForceTripCountsComputed; 8683 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8684 } 8685 8686 // Update all the PHI nodes for the next iteration. 8687 DenseMap<Instruction *, Constant *> NextIterVals; 8688 8689 // Create a list of which PHIs we need to compute. We want to do this before 8690 // calling EvaluateExpression on them because that may invalidate iterators 8691 // into CurrentIterVals. 8692 SmallVector<PHINode *, 8> PHIsToCompute; 8693 for (const auto &I : CurrentIterVals) { 8694 PHINode *PHI = dyn_cast<PHINode>(I.first); 8695 if (!PHI || PHI->getParent() != Header) continue; 8696 PHIsToCompute.push_back(PHI); 8697 } 8698 for (PHINode *PHI : PHIsToCompute) { 8699 Constant *&NextPHI = NextIterVals[PHI]; 8700 if (NextPHI) continue; // Already computed! 8701 8702 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8703 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8704 } 8705 CurrentIterVals.swap(NextIterVals); 8706 } 8707 8708 // Too many iterations were needed to evaluate. 8709 return getCouldNotCompute(); 8710 } 8711 8712 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8713 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8714 ValuesAtScopes[V]; 8715 // Check to see if we've folded this expression at this loop before. 8716 for (auto &LS : Values) 8717 if (LS.first == L) 8718 return LS.second ? LS.second : V; 8719 8720 Values.emplace_back(L, nullptr); 8721 8722 // Otherwise compute it. 8723 const SCEV *C = computeSCEVAtScope(V, L); 8724 for (auto &LS : reverse(ValuesAtScopes[V])) 8725 if (LS.first == L) { 8726 LS.second = C; 8727 break; 8728 } 8729 return C; 8730 } 8731 8732 /// This builds up a Constant using the ConstantExpr interface. That way, we 8733 /// will return Constants for objects which aren't represented by a 8734 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8735 /// Returns NULL if the SCEV isn't representable as a Constant. 8736 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8737 switch (V->getSCEVType()) { 8738 case scCouldNotCompute: 8739 case scAddRecExpr: 8740 return nullptr; 8741 case scConstant: 8742 return cast<SCEVConstant>(V)->getValue(); 8743 case scUnknown: 8744 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8745 case scSignExtend: { 8746 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8747 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8748 return ConstantExpr::getSExt(CastOp, SS->getType()); 8749 return nullptr; 8750 } 8751 case scZeroExtend: { 8752 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8753 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8754 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8755 return nullptr; 8756 } 8757 case scPtrToInt: { 8758 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8759 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8760 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8761 8762 return nullptr; 8763 } 8764 case scTruncate: { 8765 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8766 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8767 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8768 return nullptr; 8769 } 8770 case scAddExpr: { 8771 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8772 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8773 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8774 unsigned AS = PTy->getAddressSpace(); 8775 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8776 C = ConstantExpr::getBitCast(C, DestPtrTy); 8777 } 8778 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8779 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8780 if (!C2) 8781 return nullptr; 8782 8783 // First pointer! 8784 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8785 unsigned AS = C2->getType()->getPointerAddressSpace(); 8786 std::swap(C, C2); 8787 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8788 // The offsets have been converted to bytes. We can add bytes to an 8789 // i8* by GEP with the byte count in the first index. 8790 C = ConstantExpr::getBitCast(C, DestPtrTy); 8791 } 8792 8793 // Don't bother trying to sum two pointers. We probably can't 8794 // statically compute a load that results from it anyway. 8795 if (C2->getType()->isPointerTy()) 8796 return nullptr; 8797 8798 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8799 if (PTy->getElementType()->isStructTy()) 8800 C2 = ConstantExpr::getIntegerCast( 8801 C2, Type::getInt32Ty(C->getContext()), true); 8802 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8803 } else 8804 C = ConstantExpr::getAdd(C, C2); 8805 } 8806 return C; 8807 } 8808 return nullptr; 8809 } 8810 case scMulExpr: { 8811 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8812 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8813 // Don't bother with pointers at all. 8814 if (C->getType()->isPointerTy()) 8815 return nullptr; 8816 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8817 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8818 if (!C2 || C2->getType()->isPointerTy()) 8819 return nullptr; 8820 C = ConstantExpr::getMul(C, C2); 8821 } 8822 return C; 8823 } 8824 return nullptr; 8825 } 8826 case scUDivExpr: { 8827 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8828 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8829 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8830 if (LHS->getType() == RHS->getType()) 8831 return ConstantExpr::getUDiv(LHS, RHS); 8832 return nullptr; 8833 } 8834 case scSMaxExpr: 8835 case scUMaxExpr: 8836 case scSMinExpr: 8837 case scUMinExpr: 8838 return nullptr; // TODO: smax, umax, smin, umax. 8839 } 8840 llvm_unreachable("Unknown SCEV kind!"); 8841 } 8842 8843 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8844 if (isa<SCEVConstant>(V)) return V; 8845 8846 // If this instruction is evolved from a constant-evolving PHI, compute the 8847 // exit value from the loop without using SCEVs. 8848 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8849 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8850 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8851 const Loop *CurrLoop = this->LI[I->getParent()]; 8852 // Looking for loop exit value. 8853 if (CurrLoop && CurrLoop->getParentLoop() == L && 8854 PN->getParent() == CurrLoop->getHeader()) { 8855 // Okay, there is no closed form solution for the PHI node. Check 8856 // to see if the loop that contains it has a known backedge-taken 8857 // count. If so, we may be able to force computation of the exit 8858 // value. 8859 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8860 // This trivial case can show up in some degenerate cases where 8861 // the incoming IR has not yet been fully simplified. 8862 if (BackedgeTakenCount->isZero()) { 8863 Value *InitValue = nullptr; 8864 bool MultipleInitValues = false; 8865 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8866 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8867 if (!InitValue) 8868 InitValue = PN->getIncomingValue(i); 8869 else if (InitValue != PN->getIncomingValue(i)) { 8870 MultipleInitValues = true; 8871 break; 8872 } 8873 } 8874 } 8875 if (!MultipleInitValues && InitValue) 8876 return getSCEV(InitValue); 8877 } 8878 // Do we have a loop invariant value flowing around the backedge 8879 // for a loop which must execute the backedge? 8880 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8881 isKnownPositive(BackedgeTakenCount) && 8882 PN->getNumIncomingValues() == 2) { 8883 8884 unsigned InLoopPred = 8885 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8886 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8887 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8888 return getSCEV(BackedgeVal); 8889 } 8890 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8891 // Okay, we know how many times the containing loop executes. If 8892 // this is a constant evolving PHI node, get the final value at 8893 // the specified iteration number. 8894 Constant *RV = getConstantEvolutionLoopExitValue( 8895 PN, BTCC->getAPInt(), CurrLoop); 8896 if (RV) return getSCEV(RV); 8897 } 8898 } 8899 8900 // If there is a single-input Phi, evaluate it at our scope. If we can 8901 // prove that this replacement does not break LCSSA form, use new value. 8902 if (PN->getNumOperands() == 1) { 8903 const SCEV *Input = getSCEV(PN->getOperand(0)); 8904 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8905 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8906 // for the simplest case just support constants. 8907 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8908 } 8909 } 8910 8911 // Okay, this is an expression that we cannot symbolically evaluate 8912 // into a SCEV. Check to see if it's possible to symbolically evaluate 8913 // the arguments into constants, and if so, try to constant propagate the 8914 // result. This is particularly useful for computing loop exit values. 8915 if (CanConstantFold(I)) { 8916 SmallVector<Constant *, 4> Operands; 8917 bool MadeImprovement = false; 8918 for (Value *Op : I->operands()) { 8919 if (Constant *C = dyn_cast<Constant>(Op)) { 8920 Operands.push_back(C); 8921 continue; 8922 } 8923 8924 // If any of the operands is non-constant and if they are 8925 // non-integer and non-pointer, don't even try to analyze them 8926 // with scev techniques. 8927 if (!isSCEVable(Op->getType())) 8928 return V; 8929 8930 const SCEV *OrigV = getSCEV(Op); 8931 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8932 MadeImprovement |= OrigV != OpV; 8933 8934 Constant *C = BuildConstantFromSCEV(OpV); 8935 if (!C) return V; 8936 if (C->getType() != Op->getType()) 8937 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8938 Op->getType(), 8939 false), 8940 C, Op->getType()); 8941 Operands.push_back(C); 8942 } 8943 8944 // Check to see if getSCEVAtScope actually made an improvement. 8945 if (MadeImprovement) { 8946 Constant *C = nullptr; 8947 const DataLayout &DL = getDataLayout(); 8948 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8949 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8950 Operands[1], DL, &TLI); 8951 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8952 if (!Load->isVolatile()) 8953 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8954 DL); 8955 } else 8956 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8957 if (!C) return V; 8958 return getSCEV(C); 8959 } 8960 } 8961 } 8962 8963 // This is some other type of SCEVUnknown, just return it. 8964 return V; 8965 } 8966 8967 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8968 // Avoid performing the look-up in the common case where the specified 8969 // expression has no loop-variant portions. 8970 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8971 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8972 if (OpAtScope != Comm->getOperand(i)) { 8973 // Okay, at least one of these operands is loop variant but might be 8974 // foldable. Build a new instance of the folded commutative expression. 8975 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8976 Comm->op_begin()+i); 8977 NewOps.push_back(OpAtScope); 8978 8979 for (++i; i != e; ++i) { 8980 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8981 NewOps.push_back(OpAtScope); 8982 } 8983 if (isa<SCEVAddExpr>(Comm)) 8984 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8985 if (isa<SCEVMulExpr>(Comm)) 8986 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8987 if (isa<SCEVMinMaxExpr>(Comm)) 8988 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8989 llvm_unreachable("Unknown commutative SCEV type!"); 8990 } 8991 } 8992 // If we got here, all operands are loop invariant. 8993 return Comm; 8994 } 8995 8996 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8997 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8998 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8999 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9000 return Div; // must be loop invariant 9001 return getUDivExpr(LHS, RHS); 9002 } 9003 9004 // If this is a loop recurrence for a loop that does not contain L, then we 9005 // are dealing with the final value computed by the loop. 9006 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9007 // First, attempt to evaluate each operand. 9008 // Avoid performing the look-up in the common case where the specified 9009 // expression has no loop-variant portions. 9010 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9011 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9012 if (OpAtScope == AddRec->getOperand(i)) 9013 continue; 9014 9015 // Okay, at least one of these operands is loop variant but might be 9016 // foldable. Build a new instance of the folded commutative expression. 9017 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9018 AddRec->op_begin()+i); 9019 NewOps.push_back(OpAtScope); 9020 for (++i; i != e; ++i) 9021 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9022 9023 const SCEV *FoldedRec = 9024 getAddRecExpr(NewOps, AddRec->getLoop(), 9025 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9026 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9027 // The addrec may be folded to a nonrecurrence, for example, if the 9028 // induction variable is multiplied by zero after constant folding. Go 9029 // ahead and return the folded value. 9030 if (!AddRec) 9031 return FoldedRec; 9032 break; 9033 } 9034 9035 // If the scope is outside the addrec's loop, evaluate it by using the 9036 // loop exit value of the addrec. 9037 if (!AddRec->getLoop()->contains(L)) { 9038 // To evaluate this recurrence, we need to know how many times the AddRec 9039 // loop iterates. Compute this now. 9040 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9041 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9042 9043 // Then, evaluate the AddRec. 9044 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9045 } 9046 9047 return AddRec; 9048 } 9049 9050 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9051 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9052 if (Op == Cast->getOperand()) 9053 return Cast; // must be loop invariant 9054 return getZeroExtendExpr(Op, Cast->getType()); 9055 } 9056 9057 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9058 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9059 if (Op == Cast->getOperand()) 9060 return Cast; // must be loop invariant 9061 return getSignExtendExpr(Op, Cast->getType()); 9062 } 9063 9064 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9065 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9066 if (Op == Cast->getOperand()) 9067 return Cast; // must be loop invariant 9068 return getTruncateExpr(Op, Cast->getType()); 9069 } 9070 9071 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9072 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9073 if (Op == Cast->getOperand()) 9074 return Cast; // must be loop invariant 9075 return getPtrToIntExpr(Op, Cast->getType()); 9076 } 9077 9078 llvm_unreachable("Unknown SCEV type!"); 9079 } 9080 9081 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9082 return getSCEVAtScope(getSCEV(V), L); 9083 } 9084 9085 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9086 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9087 return stripInjectiveFunctions(ZExt->getOperand()); 9088 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9089 return stripInjectiveFunctions(SExt->getOperand()); 9090 return S; 9091 } 9092 9093 /// Finds the minimum unsigned root of the following equation: 9094 /// 9095 /// A * X = B (mod N) 9096 /// 9097 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9098 /// A and B isn't important. 9099 /// 9100 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9101 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9102 ScalarEvolution &SE) { 9103 uint32_t BW = A.getBitWidth(); 9104 assert(BW == SE.getTypeSizeInBits(B->getType())); 9105 assert(A != 0 && "A must be non-zero."); 9106 9107 // 1. D = gcd(A, N) 9108 // 9109 // The gcd of A and N may have only one prime factor: 2. The number of 9110 // trailing zeros in A is its multiplicity 9111 uint32_t Mult2 = A.countTrailingZeros(); 9112 // D = 2^Mult2 9113 9114 // 2. Check if B is divisible by D. 9115 // 9116 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9117 // is not less than multiplicity of this prime factor for D. 9118 if (SE.GetMinTrailingZeros(B) < Mult2) 9119 return SE.getCouldNotCompute(); 9120 9121 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9122 // modulo (N / D). 9123 // 9124 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9125 // (N / D) in general. The inverse itself always fits into BW bits, though, 9126 // so we immediately truncate it. 9127 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9128 APInt Mod(BW + 1, 0); 9129 Mod.setBit(BW - Mult2); // Mod = N / D 9130 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9131 9132 // 4. Compute the minimum unsigned root of the equation: 9133 // I * (B / D) mod (N / D) 9134 // To simplify the computation, we factor out the divide by D: 9135 // (I * B mod N) / D 9136 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9137 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9138 } 9139 9140 /// For a given quadratic addrec, generate coefficients of the corresponding 9141 /// quadratic equation, multiplied by a common value to ensure that they are 9142 /// integers. 9143 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9144 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9145 /// were multiplied by, and BitWidth is the bit width of the original addrec 9146 /// coefficients. 9147 /// This function returns None if the addrec coefficients are not compile- 9148 /// time constants. 9149 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9150 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9151 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9152 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9153 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9154 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9155 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9156 << *AddRec << '\n'); 9157 9158 // We currently can only solve this if the coefficients are constants. 9159 if (!LC || !MC || !NC) { 9160 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9161 return None; 9162 } 9163 9164 APInt L = LC->getAPInt(); 9165 APInt M = MC->getAPInt(); 9166 APInt N = NC->getAPInt(); 9167 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9168 9169 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9170 unsigned NewWidth = BitWidth + 1; 9171 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9172 << BitWidth << '\n'); 9173 // The sign-extension (as opposed to a zero-extension) here matches the 9174 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9175 N = N.sext(NewWidth); 9176 M = M.sext(NewWidth); 9177 L = L.sext(NewWidth); 9178 9179 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9180 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9181 // L+M, L+2M+N, L+3M+3N, ... 9182 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9183 // 9184 // The equation Acc = 0 is then 9185 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9186 // In a quadratic form it becomes: 9187 // N n^2 + (2M-N) n + 2L = 0. 9188 9189 APInt A = N; 9190 APInt B = 2 * M - A; 9191 APInt C = 2 * L; 9192 APInt T = APInt(NewWidth, 2); 9193 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9194 << "x + " << C << ", coeff bw: " << NewWidth 9195 << ", multiplied by " << T << '\n'); 9196 return std::make_tuple(A, B, C, T, BitWidth); 9197 } 9198 9199 /// Helper function to compare optional APInts: 9200 /// (a) if X and Y both exist, return min(X, Y), 9201 /// (b) if neither X nor Y exist, return None, 9202 /// (c) if exactly one of X and Y exists, return that value. 9203 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9204 if (X.hasValue() && Y.hasValue()) { 9205 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9206 APInt XW = X->sextOrSelf(W); 9207 APInt YW = Y->sextOrSelf(W); 9208 return XW.slt(YW) ? *X : *Y; 9209 } 9210 if (!X.hasValue() && !Y.hasValue()) 9211 return None; 9212 return X.hasValue() ? *X : *Y; 9213 } 9214 9215 /// Helper function to truncate an optional APInt to a given BitWidth. 9216 /// When solving addrec-related equations, it is preferable to return a value 9217 /// that has the same bit width as the original addrec's coefficients. If the 9218 /// solution fits in the original bit width, truncate it (except for i1). 9219 /// Returning a value of a different bit width may inhibit some optimizations. 9220 /// 9221 /// In general, a solution to a quadratic equation generated from an addrec 9222 /// may require BW+1 bits, where BW is the bit width of the addrec's 9223 /// coefficients. The reason is that the coefficients of the quadratic 9224 /// equation are BW+1 bits wide (to avoid truncation when converting from 9225 /// the addrec to the equation). 9226 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9227 if (!X.hasValue()) 9228 return None; 9229 unsigned W = X->getBitWidth(); 9230 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9231 return X->trunc(BitWidth); 9232 return X; 9233 } 9234 9235 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9236 /// iterations. The values L, M, N are assumed to be signed, and they 9237 /// should all have the same bit widths. 9238 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9239 /// where BW is the bit width of the addrec's coefficients. 9240 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9241 /// returned as such, otherwise the bit width of the returned value may 9242 /// be greater than BW. 9243 /// 9244 /// This function returns None if 9245 /// (a) the addrec coefficients are not constant, or 9246 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9247 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9248 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9249 static Optional<APInt> 9250 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9251 APInt A, B, C, M; 9252 unsigned BitWidth; 9253 auto T = GetQuadraticEquation(AddRec); 9254 if (!T.hasValue()) 9255 return None; 9256 9257 std::tie(A, B, C, M, BitWidth) = *T; 9258 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9259 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9260 if (!X.hasValue()) 9261 return None; 9262 9263 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9264 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9265 if (!V->isZero()) 9266 return None; 9267 9268 return TruncIfPossible(X, BitWidth); 9269 } 9270 9271 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9272 /// iterations. The values M, N are assumed to be signed, and they 9273 /// should all have the same bit widths. 9274 /// Find the least n such that c(n) does not belong to the given range, 9275 /// while c(n-1) does. 9276 /// 9277 /// This function returns None if 9278 /// (a) the addrec coefficients are not constant, or 9279 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9280 /// bounds of the range. 9281 static Optional<APInt> 9282 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9283 const ConstantRange &Range, ScalarEvolution &SE) { 9284 assert(AddRec->getOperand(0)->isZero() && 9285 "Starting value of addrec should be 0"); 9286 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9287 << Range << ", addrec " << *AddRec << '\n'); 9288 // This case is handled in getNumIterationsInRange. Here we can assume that 9289 // we start in the range. 9290 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9291 "Addrec's initial value should be in range"); 9292 9293 APInt A, B, C, M; 9294 unsigned BitWidth; 9295 auto T = GetQuadraticEquation(AddRec); 9296 if (!T.hasValue()) 9297 return None; 9298 9299 // Be careful about the return value: there can be two reasons for not 9300 // returning an actual number. First, if no solutions to the equations 9301 // were found, and second, if the solutions don't leave the given range. 9302 // The first case means that the actual solution is "unknown", the second 9303 // means that it's known, but not valid. If the solution is unknown, we 9304 // cannot make any conclusions. 9305 // Return a pair: the optional solution and a flag indicating if the 9306 // solution was found. 9307 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9308 // Solve for signed overflow and unsigned overflow, pick the lower 9309 // solution. 9310 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9311 << Bound << " (before multiplying by " << M << ")\n"); 9312 Bound *= M; // The quadratic equation multiplier. 9313 9314 Optional<APInt> SO = None; 9315 if (BitWidth > 1) { 9316 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9317 "signed overflow\n"); 9318 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9319 } 9320 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9321 "unsigned overflow\n"); 9322 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9323 BitWidth+1); 9324 9325 auto LeavesRange = [&] (const APInt &X) { 9326 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9327 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9328 if (Range.contains(V0->getValue())) 9329 return false; 9330 // X should be at least 1, so X-1 is non-negative. 9331 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9332 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9333 if (Range.contains(V1->getValue())) 9334 return true; 9335 return false; 9336 }; 9337 9338 // If SolveQuadraticEquationWrap returns None, it means that there can 9339 // be a solution, but the function failed to find it. We cannot treat it 9340 // as "no solution". 9341 if (!SO.hasValue() || !UO.hasValue()) 9342 return { None, false }; 9343 9344 // Check the smaller value first to see if it leaves the range. 9345 // At this point, both SO and UO must have values. 9346 Optional<APInt> Min = MinOptional(SO, UO); 9347 if (LeavesRange(*Min)) 9348 return { Min, true }; 9349 Optional<APInt> Max = Min == SO ? UO : SO; 9350 if (LeavesRange(*Max)) 9351 return { Max, true }; 9352 9353 // Solutions were found, but were eliminated, hence the "true". 9354 return { None, true }; 9355 }; 9356 9357 std::tie(A, B, C, M, BitWidth) = *T; 9358 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9359 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9360 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9361 auto SL = SolveForBoundary(Lower); 9362 auto SU = SolveForBoundary(Upper); 9363 // If any of the solutions was unknown, no meaninigful conclusions can 9364 // be made. 9365 if (!SL.second || !SU.second) 9366 return None; 9367 9368 // Claim: The correct solution is not some value between Min and Max. 9369 // 9370 // Justification: Assuming that Min and Max are different values, one of 9371 // them is when the first signed overflow happens, the other is when the 9372 // first unsigned overflow happens. Crossing the range boundary is only 9373 // possible via an overflow (treating 0 as a special case of it, modeling 9374 // an overflow as crossing k*2^W for some k). 9375 // 9376 // The interesting case here is when Min was eliminated as an invalid 9377 // solution, but Max was not. The argument is that if there was another 9378 // overflow between Min and Max, it would also have been eliminated if 9379 // it was considered. 9380 // 9381 // For a given boundary, it is possible to have two overflows of the same 9382 // type (signed/unsigned) without having the other type in between: this 9383 // can happen when the vertex of the parabola is between the iterations 9384 // corresponding to the overflows. This is only possible when the two 9385 // overflows cross k*2^W for the same k. In such case, if the second one 9386 // left the range (and was the first one to do so), the first overflow 9387 // would have to enter the range, which would mean that either we had left 9388 // the range before or that we started outside of it. Both of these cases 9389 // are contradictions. 9390 // 9391 // Claim: In the case where SolveForBoundary returns None, the correct 9392 // solution is not some value between the Max for this boundary and the 9393 // Min of the other boundary. 9394 // 9395 // Justification: Assume that we had such Max_A and Min_B corresponding 9396 // to range boundaries A and B and such that Max_A < Min_B. If there was 9397 // a solution between Max_A and Min_B, it would have to be caused by an 9398 // overflow corresponding to either A or B. It cannot correspond to B, 9399 // since Min_B is the first occurrence of such an overflow. If it 9400 // corresponded to A, it would have to be either a signed or an unsigned 9401 // overflow that is larger than both eliminated overflows for A. But 9402 // between the eliminated overflows and this overflow, the values would 9403 // cover the entire value space, thus crossing the other boundary, which 9404 // is a contradiction. 9405 9406 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9407 } 9408 9409 ScalarEvolution::ExitLimit 9410 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9411 bool AllowPredicates) { 9412 9413 // This is only used for loops with a "x != y" exit test. The exit condition 9414 // is now expressed as a single expression, V = x-y. So the exit test is 9415 // effectively V != 0. We know and take advantage of the fact that this 9416 // expression only being used in a comparison by zero context. 9417 9418 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9419 // If the value is a constant 9420 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9421 // If the value is already zero, the branch will execute zero times. 9422 if (C->getValue()->isZero()) return C; 9423 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9424 } 9425 9426 const SCEVAddRecExpr *AddRec = 9427 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9428 9429 if (!AddRec && AllowPredicates) 9430 // Try to make this an AddRec using runtime tests, in the first X 9431 // iterations of this loop, where X is the SCEV expression found by the 9432 // algorithm below. 9433 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9434 9435 if (!AddRec || AddRec->getLoop() != L) 9436 return getCouldNotCompute(); 9437 9438 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9439 // the quadratic equation to solve it. 9440 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9441 // We can only use this value if the chrec ends up with an exact zero 9442 // value at this index. When solving for "X*X != 5", for example, we 9443 // should not accept a root of 2. 9444 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9445 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9446 return ExitLimit(R, R, false, Predicates); 9447 } 9448 return getCouldNotCompute(); 9449 } 9450 9451 // Otherwise we can only handle this if it is affine. 9452 if (!AddRec->isAffine()) 9453 return getCouldNotCompute(); 9454 9455 // If this is an affine expression, the execution count of this branch is 9456 // the minimum unsigned root of the following equation: 9457 // 9458 // Start + Step*N = 0 (mod 2^BW) 9459 // 9460 // equivalent to: 9461 // 9462 // Step*N = -Start (mod 2^BW) 9463 // 9464 // where BW is the common bit width of Start and Step. 9465 9466 // Get the initial value for the loop. 9467 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9468 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9469 9470 // For now we handle only constant steps. 9471 // 9472 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9473 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9474 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9475 // We have not yet seen any such cases. 9476 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9477 if (!StepC || StepC->getValue()->isZero()) 9478 return getCouldNotCompute(); 9479 9480 // For positive steps (counting up until unsigned overflow): 9481 // N = -Start/Step (as unsigned) 9482 // For negative steps (counting down to zero): 9483 // N = Start/-Step 9484 // First compute the unsigned distance from zero in the direction of Step. 9485 bool CountDown = StepC->getAPInt().isNegative(); 9486 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9487 9488 // Handle unitary steps, which cannot wraparound. 9489 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9490 // N = Distance (as unsigned) 9491 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9492 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9493 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9494 if (MaxBECountBase.ult(MaxBECount)) 9495 MaxBECount = MaxBECountBase; 9496 9497 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9498 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9499 // case, and see if we can improve the bound. 9500 // 9501 // Explicitly handling this here is necessary because getUnsignedRange 9502 // isn't context-sensitive; it doesn't know that we only care about the 9503 // range inside the loop. 9504 const SCEV *Zero = getZero(Distance->getType()); 9505 const SCEV *One = getOne(Distance->getType()); 9506 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9507 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9508 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9509 // as "unsigned_max(Distance + 1) - 1". 9510 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9511 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9512 } 9513 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9514 } 9515 9516 // If the condition controls loop exit (the loop exits only if the expression 9517 // is true) and the addition is no-wrap we can use unsigned divide to 9518 // compute the backedge count. In this case, the step may not divide the 9519 // distance, but we don't care because if the condition is "missed" the loop 9520 // will have undefined behavior due to wrapping. 9521 if (ControlsExit && AddRec->hasNoSelfWrap() && 9522 loopHasNoAbnormalExits(AddRec->getLoop())) { 9523 const SCEV *Exact = 9524 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9525 const SCEV *Max = getCouldNotCompute(); 9526 if (Exact != getCouldNotCompute()) { 9527 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9528 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9529 if (BaseMaxInt.ult(MaxInt)) 9530 Max = getConstant(BaseMaxInt); 9531 else 9532 Max = getConstant(MaxInt); 9533 } 9534 return ExitLimit(Exact, Max, false, Predicates); 9535 } 9536 9537 // Solve the general equation. 9538 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9539 getNegativeSCEV(Start), *this); 9540 const SCEV *M = E == getCouldNotCompute() 9541 ? E 9542 : getConstant(getUnsignedRangeMax(E)); 9543 return ExitLimit(E, M, false, Predicates); 9544 } 9545 9546 ScalarEvolution::ExitLimit 9547 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9548 // Loops that look like: while (X == 0) are very strange indeed. We don't 9549 // handle them yet except for the trivial case. This could be expanded in the 9550 // future as needed. 9551 9552 // If the value is a constant, check to see if it is known to be non-zero 9553 // already. If so, the backedge will execute zero times. 9554 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9555 if (!C->getValue()->isZero()) 9556 return getZero(C->getType()); 9557 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9558 } 9559 9560 // We could implement others, but I really doubt anyone writes loops like 9561 // this, and if they did, they would already be constant folded. 9562 return getCouldNotCompute(); 9563 } 9564 9565 std::pair<const BasicBlock *, const BasicBlock *> 9566 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9567 const { 9568 // If the block has a unique predecessor, then there is no path from the 9569 // predecessor to the block that does not go through the direct edge 9570 // from the predecessor to the block. 9571 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9572 return {Pred, BB}; 9573 9574 // A loop's header is defined to be a block that dominates the loop. 9575 // If the header has a unique predecessor outside the loop, it must be 9576 // a block that has exactly one successor that can reach the loop. 9577 if (const Loop *L = LI.getLoopFor(BB)) 9578 return {L->getLoopPredecessor(), L->getHeader()}; 9579 9580 return {nullptr, nullptr}; 9581 } 9582 9583 /// SCEV structural equivalence is usually sufficient for testing whether two 9584 /// expressions are equal, however for the purposes of looking for a condition 9585 /// guarding a loop, it can be useful to be a little more general, since a 9586 /// front-end may have replicated the controlling expression. 9587 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9588 // Quick check to see if they are the same SCEV. 9589 if (A == B) return true; 9590 9591 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9592 // Not all instructions that are "identical" compute the same value. For 9593 // instance, two distinct alloca instructions allocating the same type are 9594 // identical and do not read memory; but compute distinct values. 9595 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9596 }; 9597 9598 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9599 // two different instructions with the same value. Check for this case. 9600 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9601 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9602 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9603 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9604 if (ComputesEqualValues(AI, BI)) 9605 return true; 9606 9607 // Otherwise assume they may have a different value. 9608 return false; 9609 } 9610 9611 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9612 const SCEV *&LHS, const SCEV *&RHS, 9613 unsigned Depth) { 9614 bool Changed = false; 9615 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9616 // '0 != 0'. 9617 auto TrivialCase = [&](bool TriviallyTrue) { 9618 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9619 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9620 return true; 9621 }; 9622 // If we hit the max recursion limit bail out. 9623 if (Depth >= 3) 9624 return false; 9625 9626 // Canonicalize a constant to the right side. 9627 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9628 // Check for both operands constant. 9629 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9630 if (ConstantExpr::getICmp(Pred, 9631 LHSC->getValue(), 9632 RHSC->getValue())->isNullValue()) 9633 return TrivialCase(false); 9634 else 9635 return TrivialCase(true); 9636 } 9637 // Otherwise swap the operands to put the constant on the right. 9638 std::swap(LHS, RHS); 9639 Pred = ICmpInst::getSwappedPredicate(Pred); 9640 Changed = true; 9641 } 9642 9643 // If we're comparing an addrec with a value which is loop-invariant in the 9644 // addrec's loop, put the addrec on the left. Also make a dominance check, 9645 // as both operands could be addrecs loop-invariant in each other's loop. 9646 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9647 const Loop *L = AR->getLoop(); 9648 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9649 std::swap(LHS, RHS); 9650 Pred = ICmpInst::getSwappedPredicate(Pred); 9651 Changed = true; 9652 } 9653 } 9654 9655 // If there's a constant operand, canonicalize comparisons with boundary 9656 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9657 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9658 const APInt &RA = RC->getAPInt(); 9659 9660 bool SimplifiedByConstantRange = false; 9661 9662 if (!ICmpInst::isEquality(Pred)) { 9663 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9664 if (ExactCR.isFullSet()) 9665 return TrivialCase(true); 9666 else if (ExactCR.isEmptySet()) 9667 return TrivialCase(false); 9668 9669 APInt NewRHS; 9670 CmpInst::Predicate NewPred; 9671 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9672 ICmpInst::isEquality(NewPred)) { 9673 // We were able to convert an inequality to an equality. 9674 Pred = NewPred; 9675 RHS = getConstant(NewRHS); 9676 Changed = SimplifiedByConstantRange = true; 9677 } 9678 } 9679 9680 if (!SimplifiedByConstantRange) { 9681 switch (Pred) { 9682 default: 9683 break; 9684 case ICmpInst::ICMP_EQ: 9685 case ICmpInst::ICMP_NE: 9686 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9687 if (!RA) 9688 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9689 if (const SCEVMulExpr *ME = 9690 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9691 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9692 ME->getOperand(0)->isAllOnesValue()) { 9693 RHS = AE->getOperand(1); 9694 LHS = ME->getOperand(1); 9695 Changed = true; 9696 } 9697 break; 9698 9699 9700 // The "Should have been caught earlier!" messages refer to the fact 9701 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9702 // should have fired on the corresponding cases, and canonicalized the 9703 // check to trivial case. 9704 9705 case ICmpInst::ICMP_UGE: 9706 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9707 Pred = ICmpInst::ICMP_UGT; 9708 RHS = getConstant(RA - 1); 9709 Changed = true; 9710 break; 9711 case ICmpInst::ICMP_ULE: 9712 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9713 Pred = ICmpInst::ICMP_ULT; 9714 RHS = getConstant(RA + 1); 9715 Changed = true; 9716 break; 9717 case ICmpInst::ICMP_SGE: 9718 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9719 Pred = ICmpInst::ICMP_SGT; 9720 RHS = getConstant(RA - 1); 9721 Changed = true; 9722 break; 9723 case ICmpInst::ICMP_SLE: 9724 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9725 Pred = ICmpInst::ICMP_SLT; 9726 RHS = getConstant(RA + 1); 9727 Changed = true; 9728 break; 9729 } 9730 } 9731 } 9732 9733 // Check for obvious equality. 9734 if (HasSameValue(LHS, RHS)) { 9735 if (ICmpInst::isTrueWhenEqual(Pred)) 9736 return TrivialCase(true); 9737 if (ICmpInst::isFalseWhenEqual(Pred)) 9738 return TrivialCase(false); 9739 } 9740 9741 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9742 // adding or subtracting 1 from one of the operands. 9743 switch (Pred) { 9744 case ICmpInst::ICMP_SLE: 9745 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9746 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9747 SCEV::FlagNSW); 9748 Pred = ICmpInst::ICMP_SLT; 9749 Changed = true; 9750 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9751 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9752 SCEV::FlagNSW); 9753 Pred = ICmpInst::ICMP_SLT; 9754 Changed = true; 9755 } 9756 break; 9757 case ICmpInst::ICMP_SGE: 9758 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9759 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9760 SCEV::FlagNSW); 9761 Pred = ICmpInst::ICMP_SGT; 9762 Changed = true; 9763 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9764 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9765 SCEV::FlagNSW); 9766 Pred = ICmpInst::ICMP_SGT; 9767 Changed = true; 9768 } 9769 break; 9770 case ICmpInst::ICMP_ULE: 9771 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9772 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9773 SCEV::FlagNUW); 9774 Pred = ICmpInst::ICMP_ULT; 9775 Changed = true; 9776 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9777 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9778 Pred = ICmpInst::ICMP_ULT; 9779 Changed = true; 9780 } 9781 break; 9782 case ICmpInst::ICMP_UGE: 9783 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9784 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9785 Pred = ICmpInst::ICMP_UGT; 9786 Changed = true; 9787 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9788 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9789 SCEV::FlagNUW); 9790 Pred = ICmpInst::ICMP_UGT; 9791 Changed = true; 9792 } 9793 break; 9794 default: 9795 break; 9796 } 9797 9798 // TODO: More simplifications are possible here. 9799 9800 // Recursively simplify until we either hit a recursion limit or nothing 9801 // changes. 9802 if (Changed) 9803 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9804 9805 return Changed; 9806 } 9807 9808 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9809 return getSignedRangeMax(S).isNegative(); 9810 } 9811 9812 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9813 return getSignedRangeMin(S).isStrictlyPositive(); 9814 } 9815 9816 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9817 return !getSignedRangeMin(S).isNegative(); 9818 } 9819 9820 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9821 return !getSignedRangeMax(S).isStrictlyPositive(); 9822 } 9823 9824 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9825 return isKnownNegative(S) || isKnownPositive(S); 9826 } 9827 9828 std::pair<const SCEV *, const SCEV *> 9829 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9830 // Compute SCEV on entry of loop L. 9831 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9832 if (Start == getCouldNotCompute()) 9833 return { Start, Start }; 9834 // Compute post increment SCEV for loop L. 9835 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9836 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9837 return { Start, PostInc }; 9838 } 9839 9840 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9841 const SCEV *LHS, const SCEV *RHS) { 9842 // First collect all loops. 9843 SmallPtrSet<const Loop *, 8> LoopsUsed; 9844 getUsedLoops(LHS, LoopsUsed); 9845 getUsedLoops(RHS, LoopsUsed); 9846 9847 if (LoopsUsed.empty()) 9848 return false; 9849 9850 // Domination relationship must be a linear order on collected loops. 9851 #ifndef NDEBUG 9852 for (auto *L1 : LoopsUsed) 9853 for (auto *L2 : LoopsUsed) 9854 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9855 DT.dominates(L2->getHeader(), L1->getHeader())) && 9856 "Domination relationship is not a linear order"); 9857 #endif 9858 9859 const Loop *MDL = 9860 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9861 [&](const Loop *L1, const Loop *L2) { 9862 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9863 }); 9864 9865 // Get init and post increment value for LHS. 9866 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9867 // if LHS contains unknown non-invariant SCEV then bail out. 9868 if (SplitLHS.first == getCouldNotCompute()) 9869 return false; 9870 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9871 // Get init and post increment value for RHS. 9872 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9873 // if RHS contains unknown non-invariant SCEV then bail out. 9874 if (SplitRHS.first == getCouldNotCompute()) 9875 return false; 9876 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9877 // It is possible that init SCEV contains an invariant load but it does 9878 // not dominate MDL and is not available at MDL loop entry, so we should 9879 // check it here. 9880 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9881 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9882 return false; 9883 9884 // It seems backedge guard check is faster than entry one so in some cases 9885 // it can speed up whole estimation by short circuit 9886 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9887 SplitRHS.second) && 9888 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9889 } 9890 9891 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9892 const SCEV *LHS, const SCEV *RHS) { 9893 // Canonicalize the inputs first. 9894 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9895 9896 if (isKnownViaInduction(Pred, LHS, RHS)) 9897 return true; 9898 9899 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9900 return true; 9901 9902 // Otherwise see what can be done with some simple reasoning. 9903 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9904 } 9905 9906 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9907 const SCEV *LHS, 9908 const SCEV *RHS) { 9909 if (isKnownPredicate(Pred, LHS, RHS)) 9910 return true; 9911 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9912 return false; 9913 return None; 9914 } 9915 9916 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9917 const SCEV *LHS, const SCEV *RHS, 9918 const Instruction *Context) { 9919 // TODO: Analyze guards and assumes from Context's block. 9920 return isKnownPredicate(Pred, LHS, RHS) || 9921 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9922 } 9923 9924 Optional<bool> 9925 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9926 const SCEV *RHS, 9927 const Instruction *Context) { 9928 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9929 if (KnownWithoutContext) 9930 return KnownWithoutContext; 9931 9932 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9933 return true; 9934 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9935 ICmpInst::getInversePredicate(Pred), 9936 LHS, RHS)) 9937 return false; 9938 return None; 9939 } 9940 9941 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9942 const SCEVAddRecExpr *LHS, 9943 const SCEV *RHS) { 9944 const Loop *L = LHS->getLoop(); 9945 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9946 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9947 } 9948 9949 Optional<ScalarEvolution::MonotonicPredicateType> 9950 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9951 ICmpInst::Predicate Pred) { 9952 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9953 9954 #ifndef NDEBUG 9955 // Verify an invariant: inverting the predicate should turn a monotonically 9956 // increasing change to a monotonically decreasing one, and vice versa. 9957 if (Result) { 9958 auto ResultSwapped = 9959 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9960 9961 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9962 assert(ResultSwapped.getValue() != Result.getValue() && 9963 "monotonicity should flip as we flip the predicate"); 9964 } 9965 #endif 9966 9967 return Result; 9968 } 9969 9970 Optional<ScalarEvolution::MonotonicPredicateType> 9971 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9972 ICmpInst::Predicate Pred) { 9973 // A zero step value for LHS means the induction variable is essentially a 9974 // loop invariant value. We don't really depend on the predicate actually 9975 // flipping from false to true (for increasing predicates, and the other way 9976 // around for decreasing predicates), all we care about is that *if* the 9977 // predicate changes then it only changes from false to true. 9978 // 9979 // A zero step value in itself is not very useful, but there may be places 9980 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9981 // as general as possible. 9982 9983 // Only handle LE/LT/GE/GT predicates. 9984 if (!ICmpInst::isRelational(Pred)) 9985 return None; 9986 9987 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9988 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9989 "Should be greater or less!"); 9990 9991 // Check that AR does not wrap. 9992 if (ICmpInst::isUnsigned(Pred)) { 9993 if (!LHS->hasNoUnsignedWrap()) 9994 return None; 9995 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9996 } else { 9997 assert(ICmpInst::isSigned(Pred) && 9998 "Relational predicate is either signed or unsigned!"); 9999 if (!LHS->hasNoSignedWrap()) 10000 return None; 10001 10002 const SCEV *Step = LHS->getStepRecurrence(*this); 10003 10004 if (isKnownNonNegative(Step)) 10005 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10006 10007 if (isKnownNonPositive(Step)) 10008 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10009 10010 return None; 10011 } 10012 } 10013 10014 Optional<ScalarEvolution::LoopInvariantPredicate> 10015 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10016 const SCEV *LHS, const SCEV *RHS, 10017 const Loop *L) { 10018 10019 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10020 if (!isLoopInvariant(RHS, L)) { 10021 if (!isLoopInvariant(LHS, L)) 10022 return None; 10023 10024 std::swap(LHS, RHS); 10025 Pred = ICmpInst::getSwappedPredicate(Pred); 10026 } 10027 10028 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10029 if (!ArLHS || ArLHS->getLoop() != L) 10030 return None; 10031 10032 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10033 if (!MonotonicType) 10034 return None; 10035 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10036 // true as the loop iterates, and the backedge is control dependent on 10037 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10038 // 10039 // * if the predicate was false in the first iteration then the predicate 10040 // is never evaluated again, since the loop exits without taking the 10041 // backedge. 10042 // * if the predicate was true in the first iteration then it will 10043 // continue to be true for all future iterations since it is 10044 // monotonically increasing. 10045 // 10046 // For both the above possibilities, we can replace the loop varying 10047 // predicate with its value on the first iteration of the loop (which is 10048 // loop invariant). 10049 // 10050 // A similar reasoning applies for a monotonically decreasing predicate, by 10051 // replacing true with false and false with true in the above two bullets. 10052 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10053 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10054 10055 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10056 return None; 10057 10058 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10059 } 10060 10061 Optional<ScalarEvolution::LoopInvariantPredicate> 10062 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10063 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10064 const Instruction *Context, const SCEV *MaxIter) { 10065 // Try to prove the following set of facts: 10066 // - The predicate is monotonic in the iteration space. 10067 // - If the check does not fail on the 1st iteration: 10068 // - No overflow will happen during first MaxIter iterations; 10069 // - It will not fail on the MaxIter'th iteration. 10070 // If the check does fail on the 1st iteration, we leave the loop and no 10071 // other checks matter. 10072 10073 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10074 if (!isLoopInvariant(RHS, L)) { 10075 if (!isLoopInvariant(LHS, L)) 10076 return None; 10077 10078 std::swap(LHS, RHS); 10079 Pred = ICmpInst::getSwappedPredicate(Pred); 10080 } 10081 10082 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10083 if (!AR || AR->getLoop() != L) 10084 return None; 10085 10086 // The predicate must be relational (i.e. <, <=, >=, >). 10087 if (!ICmpInst::isRelational(Pred)) 10088 return None; 10089 10090 // TODO: Support steps other than +/- 1. 10091 const SCEV *Step = AR->getStepRecurrence(*this); 10092 auto *One = getOne(Step->getType()); 10093 auto *MinusOne = getNegativeSCEV(One); 10094 if (Step != One && Step != MinusOne) 10095 return None; 10096 10097 // Type mismatch here means that MaxIter is potentially larger than max 10098 // unsigned value in start type, which mean we cannot prove no wrap for the 10099 // indvar. 10100 if (AR->getType() != MaxIter->getType()) 10101 return None; 10102 10103 // Value of IV on suggested last iteration. 10104 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10105 // Does it still meet the requirement? 10106 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10107 return None; 10108 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10109 // not exceed max unsigned value of this type), this effectively proves 10110 // that there is no wrap during the iteration. To prove that there is no 10111 // signed/unsigned wrap, we need to check that 10112 // Start <= Last for step = 1 or Start >= Last for step = -1. 10113 ICmpInst::Predicate NoOverflowPred = 10114 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10115 if (Step == MinusOne) 10116 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10117 const SCEV *Start = AR->getStart(); 10118 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 10119 return None; 10120 10121 // Everything is fine. 10122 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10123 } 10124 10125 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10126 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10127 if (HasSameValue(LHS, RHS)) 10128 return ICmpInst::isTrueWhenEqual(Pred); 10129 10130 // This code is split out from isKnownPredicate because it is called from 10131 // within isLoopEntryGuardedByCond. 10132 10133 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10134 const ConstantRange &RangeRHS) { 10135 return RangeLHS.icmp(Pred, RangeRHS); 10136 }; 10137 10138 // The check at the top of the function catches the case where the values are 10139 // known to be equal. 10140 if (Pred == CmpInst::ICMP_EQ) 10141 return false; 10142 10143 if (Pred == CmpInst::ICMP_NE) { 10144 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10145 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10146 return true; 10147 auto *Diff = getMinusSCEV(LHS, RHS); 10148 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10149 } 10150 10151 if (CmpInst::isSigned(Pred)) 10152 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10153 10154 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10155 } 10156 10157 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10158 const SCEV *LHS, 10159 const SCEV *RHS) { 10160 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10161 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10162 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10163 // OutC1 and OutC2. 10164 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10165 APInt &OutC1, APInt &OutC2, 10166 SCEV::NoWrapFlags ExpectedFlags) { 10167 const SCEV *XNonConstOp, *XConstOp; 10168 const SCEV *YNonConstOp, *YConstOp; 10169 SCEV::NoWrapFlags XFlagsPresent; 10170 SCEV::NoWrapFlags YFlagsPresent; 10171 10172 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10173 XConstOp = getZero(X->getType()); 10174 XNonConstOp = X; 10175 XFlagsPresent = ExpectedFlags; 10176 } 10177 if (!isa<SCEVConstant>(XConstOp) || 10178 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10179 return false; 10180 10181 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10182 YConstOp = getZero(Y->getType()); 10183 YNonConstOp = Y; 10184 YFlagsPresent = ExpectedFlags; 10185 } 10186 10187 if (!isa<SCEVConstant>(YConstOp) || 10188 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10189 return false; 10190 10191 if (YNonConstOp != XNonConstOp) 10192 return false; 10193 10194 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10195 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10196 10197 return true; 10198 }; 10199 10200 APInt C1; 10201 APInt C2; 10202 10203 switch (Pred) { 10204 default: 10205 break; 10206 10207 case ICmpInst::ICMP_SGE: 10208 std::swap(LHS, RHS); 10209 LLVM_FALLTHROUGH; 10210 case ICmpInst::ICMP_SLE: 10211 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10212 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10213 return true; 10214 10215 break; 10216 10217 case ICmpInst::ICMP_SGT: 10218 std::swap(LHS, RHS); 10219 LLVM_FALLTHROUGH; 10220 case ICmpInst::ICMP_SLT: 10221 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10222 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10223 return true; 10224 10225 break; 10226 10227 case ICmpInst::ICMP_UGE: 10228 std::swap(LHS, RHS); 10229 LLVM_FALLTHROUGH; 10230 case ICmpInst::ICMP_ULE: 10231 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10232 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10233 return true; 10234 10235 break; 10236 10237 case ICmpInst::ICMP_UGT: 10238 std::swap(LHS, RHS); 10239 LLVM_FALLTHROUGH; 10240 case ICmpInst::ICMP_ULT: 10241 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10242 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10243 return true; 10244 break; 10245 } 10246 10247 return false; 10248 } 10249 10250 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10251 const SCEV *LHS, 10252 const SCEV *RHS) { 10253 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10254 return false; 10255 10256 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10257 // the stack can result in exponential time complexity. 10258 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10259 10260 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10261 // 10262 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10263 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10264 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10265 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10266 // use isKnownPredicate later if needed. 10267 return isKnownNonNegative(RHS) && 10268 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10269 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10270 } 10271 10272 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10273 ICmpInst::Predicate Pred, 10274 const SCEV *LHS, const SCEV *RHS) { 10275 // No need to even try if we know the module has no guards. 10276 if (!HasGuards) 10277 return false; 10278 10279 return any_of(*BB, [&](const Instruction &I) { 10280 using namespace llvm::PatternMatch; 10281 10282 Value *Condition; 10283 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10284 m_Value(Condition))) && 10285 isImpliedCond(Pred, LHS, RHS, Condition, false); 10286 }); 10287 } 10288 10289 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10290 /// protected by a conditional between LHS and RHS. This is used to 10291 /// to eliminate casts. 10292 bool 10293 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10294 ICmpInst::Predicate Pred, 10295 const SCEV *LHS, const SCEV *RHS) { 10296 // Interpret a null as meaning no loop, where there is obviously no guard 10297 // (interprocedural conditions notwithstanding). 10298 if (!L) return true; 10299 10300 if (VerifyIR) 10301 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10302 "This cannot be done on broken IR!"); 10303 10304 10305 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10306 return true; 10307 10308 BasicBlock *Latch = L->getLoopLatch(); 10309 if (!Latch) 10310 return false; 10311 10312 BranchInst *LoopContinuePredicate = 10313 dyn_cast<BranchInst>(Latch->getTerminator()); 10314 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10315 isImpliedCond(Pred, LHS, RHS, 10316 LoopContinuePredicate->getCondition(), 10317 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10318 return true; 10319 10320 // We don't want more than one activation of the following loops on the stack 10321 // -- that can lead to O(n!) time complexity. 10322 if (WalkingBEDominatingConds) 10323 return false; 10324 10325 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10326 10327 // See if we can exploit a trip count to prove the predicate. 10328 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10329 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10330 if (LatchBECount != getCouldNotCompute()) { 10331 // We know that Latch branches back to the loop header exactly 10332 // LatchBECount times. This means the backdege condition at Latch is 10333 // equivalent to "{0,+,1} u< LatchBECount". 10334 Type *Ty = LatchBECount->getType(); 10335 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10336 const SCEV *LoopCounter = 10337 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10338 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10339 LatchBECount)) 10340 return true; 10341 } 10342 10343 // Check conditions due to any @llvm.assume intrinsics. 10344 for (auto &AssumeVH : AC.assumptions()) { 10345 if (!AssumeVH) 10346 continue; 10347 auto *CI = cast<CallInst>(AssumeVH); 10348 if (!DT.dominates(CI, Latch->getTerminator())) 10349 continue; 10350 10351 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10352 return true; 10353 } 10354 10355 // If the loop is not reachable from the entry block, we risk running into an 10356 // infinite loop as we walk up into the dom tree. These loops do not matter 10357 // anyway, so we just return a conservative answer when we see them. 10358 if (!DT.isReachableFromEntry(L->getHeader())) 10359 return false; 10360 10361 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10362 return true; 10363 10364 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10365 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10366 assert(DTN && "should reach the loop header before reaching the root!"); 10367 10368 BasicBlock *BB = DTN->getBlock(); 10369 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10370 return true; 10371 10372 BasicBlock *PBB = BB->getSinglePredecessor(); 10373 if (!PBB) 10374 continue; 10375 10376 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10377 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10378 continue; 10379 10380 Value *Condition = ContinuePredicate->getCondition(); 10381 10382 // If we have an edge `E` within the loop body that dominates the only 10383 // latch, the condition guarding `E` also guards the backedge. This 10384 // reasoning works only for loops with a single latch. 10385 10386 BasicBlockEdge DominatingEdge(PBB, BB); 10387 if (DominatingEdge.isSingleEdge()) { 10388 // We're constructively (and conservatively) enumerating edges within the 10389 // loop body that dominate the latch. The dominator tree better agree 10390 // with us on this: 10391 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10392 10393 if (isImpliedCond(Pred, LHS, RHS, Condition, 10394 BB != ContinuePredicate->getSuccessor(0))) 10395 return true; 10396 } 10397 } 10398 10399 return false; 10400 } 10401 10402 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10403 ICmpInst::Predicate Pred, 10404 const SCEV *LHS, 10405 const SCEV *RHS) { 10406 if (VerifyIR) 10407 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10408 "This cannot be done on broken IR!"); 10409 10410 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10411 // the facts (a >= b && a != b) separately. A typical situation is when the 10412 // non-strict comparison is known from ranges and non-equality is known from 10413 // dominating predicates. If we are proving strict comparison, we always try 10414 // to prove non-equality and non-strict comparison separately. 10415 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10416 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10417 bool ProvedNonStrictComparison = false; 10418 bool ProvedNonEquality = false; 10419 10420 auto SplitAndProve = 10421 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10422 if (!ProvedNonStrictComparison) 10423 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10424 if (!ProvedNonEquality) 10425 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10426 if (ProvedNonStrictComparison && ProvedNonEquality) 10427 return true; 10428 return false; 10429 }; 10430 10431 if (ProvingStrictComparison) { 10432 auto ProofFn = [&](ICmpInst::Predicate P) { 10433 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10434 }; 10435 if (SplitAndProve(ProofFn)) 10436 return true; 10437 } 10438 10439 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10440 auto ProveViaGuard = [&](const BasicBlock *Block) { 10441 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10442 return true; 10443 if (ProvingStrictComparison) { 10444 auto ProofFn = [&](ICmpInst::Predicate P) { 10445 return isImpliedViaGuard(Block, P, LHS, RHS); 10446 }; 10447 if (SplitAndProve(ProofFn)) 10448 return true; 10449 } 10450 return false; 10451 }; 10452 10453 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10454 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10455 const Instruction *Context = &BB->front(); 10456 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10457 return true; 10458 if (ProvingStrictComparison) { 10459 auto ProofFn = [&](ICmpInst::Predicate P) { 10460 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10461 }; 10462 if (SplitAndProve(ProofFn)) 10463 return true; 10464 } 10465 return false; 10466 }; 10467 10468 // Starting at the block's predecessor, climb up the predecessor chain, as long 10469 // as there are predecessors that can be found that have unique successors 10470 // leading to the original block. 10471 const Loop *ContainingLoop = LI.getLoopFor(BB); 10472 const BasicBlock *PredBB; 10473 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10474 PredBB = ContainingLoop->getLoopPredecessor(); 10475 else 10476 PredBB = BB->getSinglePredecessor(); 10477 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10478 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10479 if (ProveViaGuard(Pair.first)) 10480 return true; 10481 10482 const BranchInst *LoopEntryPredicate = 10483 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10484 if (!LoopEntryPredicate || 10485 LoopEntryPredicate->isUnconditional()) 10486 continue; 10487 10488 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10489 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10490 return true; 10491 } 10492 10493 // Check conditions due to any @llvm.assume intrinsics. 10494 for (auto &AssumeVH : AC.assumptions()) { 10495 if (!AssumeVH) 10496 continue; 10497 auto *CI = cast<CallInst>(AssumeVH); 10498 if (!DT.dominates(CI, BB)) 10499 continue; 10500 10501 if (ProveViaCond(CI->getArgOperand(0), false)) 10502 return true; 10503 } 10504 10505 return false; 10506 } 10507 10508 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10509 ICmpInst::Predicate Pred, 10510 const SCEV *LHS, 10511 const SCEV *RHS) { 10512 // Interpret a null as meaning no loop, where there is obviously no guard 10513 // (interprocedural conditions notwithstanding). 10514 if (!L) 10515 return false; 10516 10517 // Both LHS and RHS must be available at loop entry. 10518 assert(isAvailableAtLoopEntry(LHS, L) && 10519 "LHS is not available at Loop Entry"); 10520 assert(isAvailableAtLoopEntry(RHS, L) && 10521 "RHS is not available at Loop Entry"); 10522 10523 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10524 return true; 10525 10526 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10527 } 10528 10529 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10530 const SCEV *RHS, 10531 const Value *FoundCondValue, bool Inverse, 10532 const Instruction *Context) { 10533 // False conditions implies anything. Do not bother analyzing it further. 10534 if (FoundCondValue == 10535 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10536 return true; 10537 10538 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10539 return false; 10540 10541 auto ClearOnExit = 10542 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10543 10544 // Recursively handle And and Or conditions. 10545 const Value *Op0, *Op1; 10546 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10547 if (!Inverse) 10548 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10549 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10550 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10551 if (Inverse) 10552 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10553 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10554 } 10555 10556 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10557 if (!ICI) return false; 10558 10559 // Now that we found a conditional branch that dominates the loop or controls 10560 // the loop latch. Check to see if it is the comparison we are looking for. 10561 ICmpInst::Predicate FoundPred; 10562 if (Inverse) 10563 FoundPred = ICI->getInversePredicate(); 10564 else 10565 FoundPred = ICI->getPredicate(); 10566 10567 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10568 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10569 10570 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10571 } 10572 10573 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10574 const SCEV *RHS, 10575 ICmpInst::Predicate FoundPred, 10576 const SCEV *FoundLHS, const SCEV *FoundRHS, 10577 const Instruction *Context) { 10578 // Balance the types. 10579 if (getTypeSizeInBits(LHS->getType()) < 10580 getTypeSizeInBits(FoundLHS->getType())) { 10581 // For unsigned and equality predicates, try to prove that both found 10582 // operands fit into narrow unsigned range. If so, try to prove facts in 10583 // narrow types. 10584 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10585 auto *NarrowType = LHS->getType(); 10586 auto *WideType = FoundLHS->getType(); 10587 auto BitWidth = getTypeSizeInBits(NarrowType); 10588 const SCEV *MaxValue = getZeroExtendExpr( 10589 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10590 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10591 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10592 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10593 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10594 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10595 TruncFoundRHS, Context)) 10596 return true; 10597 } 10598 } 10599 10600 if (LHS->getType()->isPointerTy()) 10601 return false; 10602 if (CmpInst::isSigned(Pred)) { 10603 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10604 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10605 } else { 10606 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10607 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10608 } 10609 } else if (getTypeSizeInBits(LHS->getType()) > 10610 getTypeSizeInBits(FoundLHS->getType())) { 10611 if (FoundLHS->getType()->isPointerTy()) 10612 return false; 10613 if (CmpInst::isSigned(FoundPred)) { 10614 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10615 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10616 } else { 10617 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10618 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10619 } 10620 } 10621 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10622 FoundRHS, Context); 10623 } 10624 10625 bool ScalarEvolution::isImpliedCondBalancedTypes( 10626 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10627 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10628 const Instruction *Context) { 10629 assert(getTypeSizeInBits(LHS->getType()) == 10630 getTypeSizeInBits(FoundLHS->getType()) && 10631 "Types should be balanced!"); 10632 // Canonicalize the query to match the way instcombine will have 10633 // canonicalized the comparison. 10634 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10635 if (LHS == RHS) 10636 return CmpInst::isTrueWhenEqual(Pred); 10637 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10638 if (FoundLHS == FoundRHS) 10639 return CmpInst::isFalseWhenEqual(FoundPred); 10640 10641 // Check to see if we can make the LHS or RHS match. 10642 if (LHS == FoundRHS || RHS == FoundLHS) { 10643 if (isa<SCEVConstant>(RHS)) { 10644 std::swap(FoundLHS, FoundRHS); 10645 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10646 } else { 10647 std::swap(LHS, RHS); 10648 Pred = ICmpInst::getSwappedPredicate(Pred); 10649 } 10650 } 10651 10652 // Check whether the found predicate is the same as the desired predicate. 10653 if (FoundPred == Pred) 10654 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10655 10656 // Check whether swapping the found predicate makes it the same as the 10657 // desired predicate. 10658 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10659 // We can write the implication 10660 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10661 // using one of the following ways: 10662 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10663 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10664 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10665 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10666 // Forms 1. and 2. require swapping the operands of one condition. Don't 10667 // do this if it would break canonical constant/addrec ordering. 10668 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10669 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10670 Context); 10671 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10672 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10673 10674 // Don't try to getNotSCEV pointers. 10675 if (LHS->getType()->isPointerTy() || FoundLHS->getType()->isPointerTy()) 10676 return false; 10677 10678 // There's no clear preference between forms 3. and 4., try both. 10679 return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10680 FoundLHS, FoundRHS, Context) || 10681 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10682 getNotSCEV(FoundRHS), Context); 10683 } 10684 10685 // Unsigned comparison is the same as signed comparison when both the operands 10686 // are non-negative. 10687 if (CmpInst::isUnsigned(FoundPred) && 10688 CmpInst::getSignedPredicate(FoundPred) == Pred && 10689 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10690 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10691 10692 // Check if we can make progress by sharpening ranges. 10693 if (FoundPred == ICmpInst::ICMP_NE && 10694 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10695 10696 const SCEVConstant *C = nullptr; 10697 const SCEV *V = nullptr; 10698 10699 if (isa<SCEVConstant>(FoundLHS)) { 10700 C = cast<SCEVConstant>(FoundLHS); 10701 V = FoundRHS; 10702 } else { 10703 C = cast<SCEVConstant>(FoundRHS); 10704 V = FoundLHS; 10705 } 10706 10707 // The guarding predicate tells us that C != V. If the known range 10708 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10709 // range we consider has to correspond to same signedness as the 10710 // predicate we're interested in folding. 10711 10712 APInt Min = ICmpInst::isSigned(Pred) ? 10713 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10714 10715 if (Min == C->getAPInt()) { 10716 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10717 // This is true even if (Min + 1) wraps around -- in case of 10718 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10719 10720 APInt SharperMin = Min + 1; 10721 10722 switch (Pred) { 10723 case ICmpInst::ICMP_SGE: 10724 case ICmpInst::ICMP_UGE: 10725 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10726 // RHS, we're done. 10727 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10728 Context)) 10729 return true; 10730 LLVM_FALLTHROUGH; 10731 10732 case ICmpInst::ICMP_SGT: 10733 case ICmpInst::ICMP_UGT: 10734 // We know from the range information that (V `Pred` Min || 10735 // V == Min). We know from the guarding condition that !(V 10736 // == Min). This gives us 10737 // 10738 // V `Pred` Min || V == Min && !(V == Min) 10739 // => V `Pred` Min 10740 // 10741 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10742 10743 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10744 Context)) 10745 return true; 10746 break; 10747 10748 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10749 case ICmpInst::ICMP_SLE: 10750 case ICmpInst::ICMP_ULE: 10751 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10752 LHS, V, getConstant(SharperMin), Context)) 10753 return true; 10754 LLVM_FALLTHROUGH; 10755 10756 case ICmpInst::ICMP_SLT: 10757 case ICmpInst::ICMP_ULT: 10758 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10759 LHS, V, getConstant(Min), Context)) 10760 return true; 10761 break; 10762 10763 default: 10764 // No change 10765 break; 10766 } 10767 } 10768 } 10769 10770 // Check whether the actual condition is beyond sufficient. 10771 if (FoundPred == ICmpInst::ICMP_EQ) 10772 if (ICmpInst::isTrueWhenEqual(Pred)) 10773 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10774 return true; 10775 if (Pred == ICmpInst::ICMP_NE) 10776 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10777 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10778 Context)) 10779 return true; 10780 10781 // Otherwise assume the worst. 10782 return false; 10783 } 10784 10785 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10786 const SCEV *&L, const SCEV *&R, 10787 SCEV::NoWrapFlags &Flags) { 10788 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10789 if (!AE || AE->getNumOperands() != 2) 10790 return false; 10791 10792 L = AE->getOperand(0); 10793 R = AE->getOperand(1); 10794 Flags = AE->getNoWrapFlags(); 10795 return true; 10796 } 10797 10798 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10799 const SCEV *Less) { 10800 // We avoid subtracting expressions here because this function is usually 10801 // fairly deep in the call stack (i.e. is called many times). 10802 10803 // X - X = 0. 10804 if (More == Less) 10805 return APInt(getTypeSizeInBits(More->getType()), 0); 10806 10807 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10808 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10809 const auto *MAR = cast<SCEVAddRecExpr>(More); 10810 10811 if (LAR->getLoop() != MAR->getLoop()) 10812 return None; 10813 10814 // We look at affine expressions only; not for correctness but to keep 10815 // getStepRecurrence cheap. 10816 if (!LAR->isAffine() || !MAR->isAffine()) 10817 return None; 10818 10819 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10820 return None; 10821 10822 Less = LAR->getStart(); 10823 More = MAR->getStart(); 10824 10825 // fall through 10826 } 10827 10828 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10829 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10830 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10831 return M - L; 10832 } 10833 10834 SCEV::NoWrapFlags Flags; 10835 const SCEV *LLess = nullptr, *RLess = nullptr; 10836 const SCEV *LMore = nullptr, *RMore = nullptr; 10837 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10838 // Compare (X + C1) vs X. 10839 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10840 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10841 if (RLess == More) 10842 return -(C1->getAPInt()); 10843 10844 // Compare X vs (X + C2). 10845 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10846 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10847 if (RMore == Less) 10848 return C2->getAPInt(); 10849 10850 // Compare (X + C1) vs (X + C2). 10851 if (C1 && C2 && RLess == RMore) 10852 return C2->getAPInt() - C1->getAPInt(); 10853 10854 return None; 10855 } 10856 10857 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10858 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10859 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10860 // Try to recognize the following pattern: 10861 // 10862 // FoundRHS = ... 10863 // ... 10864 // loop: 10865 // FoundLHS = {Start,+,W} 10866 // context_bb: // Basic block from the same loop 10867 // known(Pred, FoundLHS, FoundRHS) 10868 // 10869 // If some predicate is known in the context of a loop, it is also known on 10870 // each iteration of this loop, including the first iteration. Therefore, in 10871 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10872 // prove the original pred using this fact. 10873 if (!Context) 10874 return false; 10875 const BasicBlock *ContextBB = Context->getParent(); 10876 // Make sure AR varies in the context block. 10877 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10878 const Loop *L = AR->getLoop(); 10879 // Make sure that context belongs to the loop and executes on 1st iteration 10880 // (if it ever executes at all). 10881 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10882 return false; 10883 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10884 return false; 10885 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10886 } 10887 10888 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10889 const Loop *L = AR->getLoop(); 10890 // Make sure that context belongs to the loop and executes on 1st iteration 10891 // (if it ever executes at all). 10892 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10893 return false; 10894 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10895 return false; 10896 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10897 } 10898 10899 return false; 10900 } 10901 10902 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10903 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10904 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10905 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10906 return false; 10907 10908 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10909 if (!AddRecLHS) 10910 return false; 10911 10912 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10913 if (!AddRecFoundLHS) 10914 return false; 10915 10916 // We'd like to let SCEV reason about control dependencies, so we constrain 10917 // both the inequalities to be about add recurrences on the same loop. This 10918 // way we can use isLoopEntryGuardedByCond later. 10919 10920 const Loop *L = AddRecFoundLHS->getLoop(); 10921 if (L != AddRecLHS->getLoop()) 10922 return false; 10923 10924 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10925 // 10926 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10927 // ... (2) 10928 // 10929 // Informal proof for (2), assuming (1) [*]: 10930 // 10931 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10932 // 10933 // Then 10934 // 10935 // FoundLHS s< FoundRHS s< INT_MIN - C 10936 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10937 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10938 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10939 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10940 // <=> FoundLHS + C s< FoundRHS + C 10941 // 10942 // [*]: (1) can be proved by ruling out overflow. 10943 // 10944 // [**]: This can be proved by analyzing all the four possibilities: 10945 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10946 // (A s>= 0, B s>= 0). 10947 // 10948 // Note: 10949 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10950 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10951 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10952 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10953 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10954 // C)". 10955 10956 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10957 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10958 if (!LDiff || !RDiff || *LDiff != *RDiff) 10959 return false; 10960 10961 if (LDiff->isMinValue()) 10962 return true; 10963 10964 APInt FoundRHSLimit; 10965 10966 if (Pred == CmpInst::ICMP_ULT) { 10967 FoundRHSLimit = -(*RDiff); 10968 } else { 10969 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10970 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10971 } 10972 10973 // Try to prove (1) or (2), as needed. 10974 return isAvailableAtLoopEntry(FoundRHS, L) && 10975 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10976 getConstant(FoundRHSLimit)); 10977 } 10978 10979 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10980 const SCEV *LHS, const SCEV *RHS, 10981 const SCEV *FoundLHS, 10982 const SCEV *FoundRHS, unsigned Depth) { 10983 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10984 10985 auto ClearOnExit = make_scope_exit([&]() { 10986 if (LPhi) { 10987 bool Erased = PendingMerges.erase(LPhi); 10988 assert(Erased && "Failed to erase LPhi!"); 10989 (void)Erased; 10990 } 10991 if (RPhi) { 10992 bool Erased = PendingMerges.erase(RPhi); 10993 assert(Erased && "Failed to erase RPhi!"); 10994 (void)Erased; 10995 } 10996 }); 10997 10998 // Find respective Phis and check that they are not being pending. 10999 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11000 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11001 if (!PendingMerges.insert(Phi).second) 11002 return false; 11003 LPhi = Phi; 11004 } 11005 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11006 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11007 // If we detect a loop of Phi nodes being processed by this method, for 11008 // example: 11009 // 11010 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11011 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11012 // 11013 // we don't want to deal with a case that complex, so return conservative 11014 // answer false. 11015 if (!PendingMerges.insert(Phi).second) 11016 return false; 11017 RPhi = Phi; 11018 } 11019 11020 // If none of LHS, RHS is a Phi, nothing to do here. 11021 if (!LPhi && !RPhi) 11022 return false; 11023 11024 // If there is a SCEVUnknown Phi we are interested in, make it left. 11025 if (!LPhi) { 11026 std::swap(LHS, RHS); 11027 std::swap(FoundLHS, FoundRHS); 11028 std::swap(LPhi, RPhi); 11029 Pred = ICmpInst::getSwappedPredicate(Pred); 11030 } 11031 11032 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11033 const BasicBlock *LBB = LPhi->getParent(); 11034 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11035 11036 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11037 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11038 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11039 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11040 }; 11041 11042 if (RPhi && RPhi->getParent() == LBB) { 11043 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11044 // If we compare two Phis from the same block, and for each entry block 11045 // the predicate is true for incoming values from this block, then the 11046 // predicate is also true for the Phis. 11047 for (const BasicBlock *IncBB : predecessors(LBB)) { 11048 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11049 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11050 if (!ProvedEasily(L, R)) 11051 return false; 11052 } 11053 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11054 // Case two: RHS is also a Phi from the same basic block, and it is an 11055 // AddRec. It means that there is a loop which has both AddRec and Unknown 11056 // PHIs, for it we can compare incoming values of AddRec from above the loop 11057 // and latch with their respective incoming values of LPhi. 11058 // TODO: Generalize to handle loops with many inputs in a header. 11059 if (LPhi->getNumIncomingValues() != 2) return false; 11060 11061 auto *RLoop = RAR->getLoop(); 11062 auto *Predecessor = RLoop->getLoopPredecessor(); 11063 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11064 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11065 if (!ProvedEasily(L1, RAR->getStart())) 11066 return false; 11067 auto *Latch = RLoop->getLoopLatch(); 11068 assert(Latch && "Loop with AddRec with no latch?"); 11069 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11070 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11071 return false; 11072 } else { 11073 // In all other cases go over inputs of LHS and compare each of them to RHS, 11074 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11075 // At this point RHS is either a non-Phi, or it is a Phi from some block 11076 // different from LBB. 11077 for (const BasicBlock *IncBB : predecessors(LBB)) { 11078 // Check that RHS is available in this block. 11079 if (!dominates(RHS, IncBB)) 11080 return false; 11081 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11082 // Make sure L does not refer to a value from a potentially previous 11083 // iteration of a loop. 11084 if (!properlyDominates(L, IncBB)) 11085 return false; 11086 if (!ProvedEasily(L, RHS)) 11087 return false; 11088 } 11089 } 11090 return true; 11091 } 11092 11093 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11094 const SCEV *LHS, const SCEV *RHS, 11095 const SCEV *FoundLHS, 11096 const SCEV *FoundRHS, 11097 const Instruction *Context) { 11098 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11099 return true; 11100 11101 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11102 return true; 11103 11104 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11105 Context)) 11106 return true; 11107 11108 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11109 FoundLHS, FoundRHS); 11110 } 11111 11112 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11113 template <typename MinMaxExprType> 11114 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11115 const SCEV *Candidate) { 11116 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11117 if (!MinMaxExpr) 11118 return false; 11119 11120 return is_contained(MinMaxExpr->operands(), Candidate); 11121 } 11122 11123 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11124 ICmpInst::Predicate Pred, 11125 const SCEV *LHS, const SCEV *RHS) { 11126 // If both sides are affine addrecs for the same loop, with equal 11127 // steps, and we know the recurrences don't wrap, then we only 11128 // need to check the predicate on the starting values. 11129 11130 if (!ICmpInst::isRelational(Pred)) 11131 return false; 11132 11133 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11134 if (!LAR) 11135 return false; 11136 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11137 if (!RAR) 11138 return false; 11139 if (LAR->getLoop() != RAR->getLoop()) 11140 return false; 11141 if (!LAR->isAffine() || !RAR->isAffine()) 11142 return false; 11143 11144 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11145 return false; 11146 11147 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11148 SCEV::FlagNSW : SCEV::FlagNUW; 11149 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11150 return false; 11151 11152 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11153 } 11154 11155 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11156 /// expression? 11157 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11158 ICmpInst::Predicate Pred, 11159 const SCEV *LHS, const SCEV *RHS) { 11160 switch (Pred) { 11161 default: 11162 return false; 11163 11164 case ICmpInst::ICMP_SGE: 11165 std::swap(LHS, RHS); 11166 LLVM_FALLTHROUGH; 11167 case ICmpInst::ICMP_SLE: 11168 return 11169 // min(A, ...) <= A 11170 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11171 // A <= max(A, ...) 11172 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11173 11174 case ICmpInst::ICMP_UGE: 11175 std::swap(LHS, RHS); 11176 LLVM_FALLTHROUGH; 11177 case ICmpInst::ICMP_ULE: 11178 return 11179 // min(A, ...) <= A 11180 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11181 // A <= max(A, ...) 11182 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11183 } 11184 11185 llvm_unreachable("covered switch fell through?!"); 11186 } 11187 11188 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11189 const SCEV *LHS, const SCEV *RHS, 11190 const SCEV *FoundLHS, 11191 const SCEV *FoundRHS, 11192 unsigned Depth) { 11193 assert(getTypeSizeInBits(LHS->getType()) == 11194 getTypeSizeInBits(RHS->getType()) && 11195 "LHS and RHS have different sizes?"); 11196 assert(getTypeSizeInBits(FoundLHS->getType()) == 11197 getTypeSizeInBits(FoundRHS->getType()) && 11198 "FoundLHS and FoundRHS have different sizes?"); 11199 // We want to avoid hurting the compile time with analysis of too big trees. 11200 if (Depth > MaxSCEVOperationsImplicationDepth) 11201 return false; 11202 11203 // We only want to work with GT comparison so far. 11204 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11205 Pred = CmpInst::getSwappedPredicate(Pred); 11206 std::swap(LHS, RHS); 11207 std::swap(FoundLHS, FoundRHS); 11208 } 11209 11210 // For unsigned, try to reduce it to corresponding signed comparison. 11211 if (Pred == ICmpInst::ICMP_UGT) 11212 // We can replace unsigned predicate with its signed counterpart if all 11213 // involved values are non-negative. 11214 // TODO: We could have better support for unsigned. 11215 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11216 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11217 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11218 // use this fact to prove that LHS and RHS are non-negative. 11219 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11220 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11221 FoundRHS) && 11222 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11223 FoundRHS)) 11224 Pred = ICmpInst::ICMP_SGT; 11225 } 11226 11227 if (Pred != ICmpInst::ICMP_SGT) 11228 return false; 11229 11230 auto GetOpFromSExt = [&](const SCEV *S) { 11231 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11232 return Ext->getOperand(); 11233 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11234 // the constant in some cases. 11235 return S; 11236 }; 11237 11238 // Acquire values from extensions. 11239 auto *OrigLHS = LHS; 11240 auto *OrigFoundLHS = FoundLHS; 11241 LHS = GetOpFromSExt(LHS); 11242 FoundLHS = GetOpFromSExt(FoundLHS); 11243 11244 // Is the SGT predicate can be proved trivially or using the found context. 11245 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11246 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11247 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11248 FoundRHS, Depth + 1); 11249 }; 11250 11251 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11252 // We want to avoid creation of any new non-constant SCEV. Since we are 11253 // going to compare the operands to RHS, we should be certain that we don't 11254 // need any size extensions for this. So let's decline all cases when the 11255 // sizes of types of LHS and RHS do not match. 11256 // TODO: Maybe try to get RHS from sext to catch more cases? 11257 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11258 return false; 11259 11260 // Should not overflow. 11261 if (!LHSAddExpr->hasNoSignedWrap()) 11262 return false; 11263 11264 auto *LL = LHSAddExpr->getOperand(0); 11265 auto *LR = LHSAddExpr->getOperand(1); 11266 auto *MinusOne = getMinusOne(RHS->getType()); 11267 11268 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11269 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11270 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11271 }; 11272 // Try to prove the following rule: 11273 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11274 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11275 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11276 return true; 11277 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11278 Value *LL, *LR; 11279 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11280 11281 using namespace llvm::PatternMatch; 11282 11283 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11284 // Rules for division. 11285 // We are going to perform some comparisons with Denominator and its 11286 // derivative expressions. In general case, creating a SCEV for it may 11287 // lead to a complex analysis of the entire graph, and in particular it 11288 // can request trip count recalculation for the same loop. This would 11289 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11290 // this, we only want to create SCEVs that are constants in this section. 11291 // So we bail if Denominator is not a constant. 11292 if (!isa<ConstantInt>(LR)) 11293 return false; 11294 11295 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11296 11297 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11298 // then a SCEV for the numerator already exists and matches with FoundLHS. 11299 auto *Numerator = getExistingSCEV(LL); 11300 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11301 return false; 11302 11303 // Make sure that the numerator matches with FoundLHS and the denominator 11304 // is positive. 11305 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11306 return false; 11307 11308 auto *DTy = Denominator->getType(); 11309 auto *FRHSTy = FoundRHS->getType(); 11310 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11311 // One of types is a pointer and another one is not. We cannot extend 11312 // them properly to a wider type, so let us just reject this case. 11313 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11314 // to avoid this check. 11315 return false; 11316 11317 // Given that: 11318 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11319 auto *WTy = getWiderType(DTy, FRHSTy); 11320 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11321 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11322 11323 // Try to prove the following rule: 11324 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11325 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11326 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11327 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11328 if (isKnownNonPositive(RHS) && 11329 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11330 return true; 11331 11332 // Try to prove the following rule: 11333 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11334 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11335 // If we divide it by Denominator > 2, then: 11336 // 1. If FoundLHS is negative, then the result is 0. 11337 // 2. If FoundLHS is non-negative, then the result is non-negative. 11338 // Anyways, the result is non-negative. 11339 auto *MinusOne = getMinusOne(WTy); 11340 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11341 if (isKnownNegative(RHS) && 11342 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11343 return true; 11344 } 11345 } 11346 11347 // If our expression contained SCEVUnknown Phis, and we split it down and now 11348 // need to prove something for them, try to prove the predicate for every 11349 // possible incoming values of those Phis. 11350 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11351 return true; 11352 11353 return false; 11354 } 11355 11356 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11357 const SCEV *LHS, const SCEV *RHS) { 11358 // zext x u<= sext x, sext x s<= zext x 11359 switch (Pred) { 11360 case ICmpInst::ICMP_SGE: 11361 std::swap(LHS, RHS); 11362 LLVM_FALLTHROUGH; 11363 case ICmpInst::ICMP_SLE: { 11364 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11365 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11366 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11367 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11368 return true; 11369 break; 11370 } 11371 case ICmpInst::ICMP_UGE: 11372 std::swap(LHS, RHS); 11373 LLVM_FALLTHROUGH; 11374 case ICmpInst::ICMP_ULE: { 11375 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11376 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11377 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11378 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11379 return true; 11380 break; 11381 } 11382 default: 11383 break; 11384 }; 11385 return false; 11386 } 11387 11388 bool 11389 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11390 const SCEV *LHS, const SCEV *RHS) { 11391 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11392 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11393 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11394 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11395 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11396 } 11397 11398 bool 11399 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11400 const SCEV *LHS, const SCEV *RHS, 11401 const SCEV *FoundLHS, 11402 const SCEV *FoundRHS) { 11403 switch (Pred) { 11404 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11405 case ICmpInst::ICMP_EQ: 11406 case ICmpInst::ICMP_NE: 11407 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11408 return true; 11409 break; 11410 case ICmpInst::ICMP_SLT: 11411 case ICmpInst::ICMP_SLE: 11412 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11413 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11414 return true; 11415 break; 11416 case ICmpInst::ICMP_SGT: 11417 case ICmpInst::ICMP_SGE: 11418 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11419 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11420 return true; 11421 break; 11422 case ICmpInst::ICMP_ULT: 11423 case ICmpInst::ICMP_ULE: 11424 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11425 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11426 return true; 11427 break; 11428 case ICmpInst::ICMP_UGT: 11429 case ICmpInst::ICMP_UGE: 11430 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11431 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11432 return true; 11433 break; 11434 } 11435 11436 // Maybe it can be proved via operations? 11437 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11438 return true; 11439 11440 return false; 11441 } 11442 11443 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11444 const SCEV *LHS, 11445 const SCEV *RHS, 11446 const SCEV *FoundLHS, 11447 const SCEV *FoundRHS) { 11448 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11449 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11450 // reduce the compile time impact of this optimization. 11451 return false; 11452 11453 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11454 if (!Addend) 11455 return false; 11456 11457 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11458 11459 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11460 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11461 ConstantRange FoundLHSRange = 11462 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11463 11464 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11465 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11466 11467 // We can also compute the range of values for `LHS` that satisfy the 11468 // consequent, "`LHS` `Pred` `RHS`": 11469 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11470 // The antecedent implies the consequent if every value of `LHS` that 11471 // satisfies the antecedent also satisfies the consequent. 11472 return LHSRange.icmp(Pred, ConstRHS); 11473 } 11474 11475 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11476 bool IsSigned) { 11477 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11478 11479 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11480 const SCEV *One = getOne(Stride->getType()); 11481 11482 if (IsSigned) { 11483 APInt MaxRHS = getSignedRangeMax(RHS); 11484 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11485 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11486 11487 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11488 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11489 } 11490 11491 APInt MaxRHS = getUnsignedRangeMax(RHS); 11492 APInt MaxValue = APInt::getMaxValue(BitWidth); 11493 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11494 11495 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11496 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11497 } 11498 11499 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11500 bool IsSigned) { 11501 11502 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11503 const SCEV *One = getOne(Stride->getType()); 11504 11505 if (IsSigned) { 11506 APInt MinRHS = getSignedRangeMin(RHS); 11507 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11508 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11509 11510 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11511 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11512 } 11513 11514 APInt MinRHS = getUnsignedRangeMin(RHS); 11515 APInt MinValue = APInt::getMinValue(BitWidth); 11516 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11517 11518 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11519 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11520 } 11521 11522 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11523 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11524 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11525 // expression fixes the case of N=0. 11526 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11527 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11528 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11529 } 11530 11531 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, 11532 const SCEV *Step) { 11533 const SCEV *One = getOne(Step->getType()); 11534 Delta = getAddExpr(Delta, getMinusSCEV(Step, One)); 11535 return getUDivExpr(Delta, Step); 11536 } 11537 11538 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11539 const SCEV *Stride, 11540 const SCEV *End, 11541 unsigned BitWidth, 11542 bool IsSigned) { 11543 11544 assert(!isKnownNonPositive(Stride) && 11545 "Stride is expected strictly positive!"); 11546 // Calculate the maximum backedge count based on the range of values 11547 // permitted by Start, End, and Stride. 11548 const SCEV *MaxBECount; 11549 APInt MinStart = 11550 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11551 11552 APInt StrideForMaxBECount = 11553 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11554 11555 // We already know that the stride is positive, so we paper over conservatism 11556 // in our range computation by forcing StrideForMaxBECount to be at least one. 11557 // In theory this is unnecessary, but we expect MaxBECount to be a 11558 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11559 // is nothing to constant fold it to). 11560 APInt One(BitWidth, 1, IsSigned); 11561 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11562 11563 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11564 : APInt::getMaxValue(BitWidth); 11565 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11566 11567 // Although End can be a MAX expression we estimate MaxEnd considering only 11568 // the case End = RHS of the loop termination condition. This is safe because 11569 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11570 // taken count. 11571 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11572 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11573 11574 MaxBECount = getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11575 getConstant(StrideForMaxBECount) /* Step */); 11576 11577 return MaxBECount; 11578 } 11579 11580 ScalarEvolution::ExitLimit 11581 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11582 const Loop *L, bool IsSigned, 11583 bool ControlsExit, bool AllowPredicates) { 11584 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11585 11586 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11587 bool PredicatedIV = false; 11588 11589 if (!IV && AllowPredicates) { 11590 // Try to make this an AddRec using runtime tests, in the first X 11591 // iterations of this loop, where X is the SCEV expression found by the 11592 // algorithm below. 11593 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11594 PredicatedIV = true; 11595 } 11596 11597 // Avoid weird loops 11598 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11599 return getCouldNotCompute(); 11600 11601 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11602 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11603 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11604 11605 const SCEV *Stride = IV->getStepRecurrence(*this); 11606 11607 bool PositiveStride = isKnownPositive(Stride); 11608 11609 // Avoid negative or zero stride values. 11610 if (!PositiveStride) { 11611 // We can compute the correct backedge taken count for loops with unknown 11612 // strides if we can prove that the loop is not an infinite loop with side 11613 // effects. Here's the loop structure we are trying to handle - 11614 // 11615 // i = start 11616 // do { 11617 // A[i] = i; 11618 // i += s; 11619 // } while (i < end); 11620 // 11621 // The backedge taken count for such loops is evaluated as - 11622 // (max(end, start + stride) - start - 1) /u stride 11623 // 11624 // The additional preconditions that we need to check to prove correctness 11625 // of the above formula is as follows - 11626 // 11627 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11628 // NoWrap flag). 11629 // b) loop is single exit with no side effects. 11630 // 11631 // 11632 // Precondition a) implies that if the stride is negative, this is a single 11633 // trip loop. The backedge taken count formula reduces to zero in this case. 11634 // 11635 // Precondition b) implies that the unknown stride cannot be zero otherwise 11636 // we have UB. 11637 // 11638 // The positive stride case is the same as isKnownPositive(Stride) returning 11639 // true (original behavior of the function). 11640 // 11641 // We want to make sure that the stride is truly unknown as there are edge 11642 // cases where ScalarEvolution propagates no wrap flags to the 11643 // post-increment/decrement IV even though the increment/decrement operation 11644 // itself is wrapping. The computed backedge taken count may be wrong in 11645 // such cases. This is prevented by checking that the stride is not known to 11646 // be either positive or non-positive. For example, no wrap flags are 11647 // propagated to the post-increment IV of this loop with a trip count of 2 - 11648 // 11649 // unsigned char i; 11650 // for(i=127; i<128; i+=129) 11651 // A[i] = i; 11652 // 11653 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11654 !loopIsFiniteByAssumption(L)) 11655 return getCouldNotCompute(); 11656 } else if (!Stride->isOne() && !NoWrap) { 11657 auto isUBOnWrap = [&]() { 11658 // Can we prove this loop *must* be UB if overflow of IV occurs? 11659 // Reasoning goes as follows: 11660 // * Suppose the IV did self wrap. 11661 // * If Stride evenly divides the iteration space, then once wrap 11662 // occurs, the loop must revisit the same values. 11663 // * We know that RHS is invariant, and that none of those values 11664 // caused this exit to be taken previously. Thus, this exit is 11665 // dynamically dead. 11666 // * If this is the sole exit, then a dead exit implies the loop 11667 // must be infinite if there are no abnormal exits. 11668 // * If the loop were infinite, then it must either not be mustprogress 11669 // or have side effects. Otherwise, it must be UB. 11670 // * It can't (by assumption), be UB so we have contradicted our 11671 // premise and can conclude the IV did not in fact self-wrap. 11672 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11673 // follows trivially from the fact that every (un)signed-wrapped, but 11674 // not self-wrapped value must be LT than the last value before 11675 // (un)signed wrap. Since we know that last value didn't exit, nor 11676 // will any smaller one. 11677 11678 if (!isLoopInvariant(RHS, L)) 11679 return false; 11680 11681 auto *StrideC = dyn_cast<SCEVConstant>(Stride); 11682 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11683 return false; 11684 11685 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11686 return false; 11687 11688 return loopIsFiniteByAssumption(L); 11689 }; 11690 11691 // Avoid proven overflow cases: this will ensure that the backedge taken 11692 // count will not generate any unsigned overflow. Relaxed no-overflow 11693 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11694 // undefined behaviors like the case of C language. 11695 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11696 return getCouldNotCompute(); 11697 } 11698 11699 const SCEV *Start = IV->getStart(); 11700 11701 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11702 // Use integer-typed versions for actual computation. 11703 const SCEV *OrigStart = Start; 11704 const SCEV *OrigRHS = RHS; 11705 if (Start->getType()->isPointerTy()) { 11706 Start = getLosslessPtrToIntExpr(Start); 11707 if (isa<SCEVCouldNotCompute>(Start)) 11708 return Start; 11709 } 11710 if (RHS->getType()->isPointerTy()) { 11711 RHS = getLosslessPtrToIntExpr(RHS); 11712 if (isa<SCEVCouldNotCompute>(RHS)) 11713 return RHS; 11714 } 11715 11716 const SCEV *End = RHS; 11717 // When the RHS is not invariant, we do not know the end bound of the loop and 11718 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11719 // calculate the MaxBECount, given the start, stride and max value for the end 11720 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11721 // checked above). 11722 if (!isLoopInvariant(RHS, L)) { 11723 const SCEV *MaxBECount = computeMaxBECountForLT( 11724 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11725 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11726 false /*MaxOrZero*/, Predicates); 11727 } 11728 // If the backedge is taken at least once, then it will be taken 11729 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11730 // is the LHS value of the less-than comparison the first time it is evaluated 11731 // and End is the RHS. 11732 const SCEV *BECountIfBackedgeTaken = 11733 computeBECount(getMinusSCEV(End, Start), Stride); 11734 // If the loop entry is guarded by the result of the backedge test of the 11735 // first loop iteration, then we know the backedge will be taken at least 11736 // once and so the backedge taken count is as above. If not then we use the 11737 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11738 // as if the backedge is taken at least once max(End,Start) is End and so the 11739 // result is as above, and if not max(End,Start) is Start so we get a backedge 11740 // count of zero. 11741 const SCEV *BECount; 11742 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(OrigStart, Stride), OrigRHS)) 11743 BECount = BECountIfBackedgeTaken; 11744 else { 11745 // If we know that RHS >= Start in the context of loop, then we know that 11746 // max(RHS, Start) = RHS at this point. 11747 if (isLoopEntryGuardedByCond( 11748 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, OrigRHS, OrigStart)) 11749 End = RHS; 11750 else 11751 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11752 BECount = computeBECount(getMinusSCEV(End, Start), Stride); 11753 } 11754 11755 const SCEV *MaxBECount; 11756 bool MaxOrZero = false; 11757 if (isa<SCEVConstant>(BECount)) 11758 MaxBECount = BECount; 11759 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11760 // If we know exactly how many times the backedge will be taken if it's 11761 // taken at least once, then the backedge count will either be that or 11762 // zero. 11763 MaxBECount = BECountIfBackedgeTaken; 11764 MaxOrZero = true; 11765 } else { 11766 MaxBECount = computeMaxBECountForLT( 11767 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11768 } 11769 11770 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11771 !isa<SCEVCouldNotCompute>(BECount)) 11772 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11773 11774 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11775 } 11776 11777 ScalarEvolution::ExitLimit 11778 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11779 const Loop *L, bool IsSigned, 11780 bool ControlsExit, bool AllowPredicates) { 11781 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11782 // We handle only IV > Invariant 11783 if (!isLoopInvariant(RHS, L)) 11784 return getCouldNotCompute(); 11785 11786 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11787 if (!IV && AllowPredicates) 11788 // Try to make this an AddRec using runtime tests, in the first X 11789 // iterations of this loop, where X is the SCEV expression found by the 11790 // algorithm below. 11791 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11792 11793 // Avoid weird loops 11794 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11795 return getCouldNotCompute(); 11796 11797 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11798 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11799 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11800 11801 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11802 11803 // Avoid negative or zero stride values 11804 if (!isKnownPositive(Stride)) 11805 return getCouldNotCompute(); 11806 11807 // Avoid proven overflow cases: this will ensure that the backedge taken count 11808 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11809 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11810 // behaviors like the case of C language. 11811 if (!Stride->isOne() && !NoWrap) 11812 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 11813 return getCouldNotCompute(); 11814 11815 const SCEV *Start = IV->getStart(); 11816 const SCEV *End = RHS; 11817 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11818 // If we know that Start >= RHS in the context of loop, then we know that 11819 // min(RHS, Start) = RHS at this point. 11820 if (isLoopEntryGuardedByCond( 11821 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11822 End = RHS; 11823 else 11824 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11825 } 11826 11827 if (Start->getType()->isPointerTy()) { 11828 Start = getLosslessPtrToIntExpr(Start); 11829 if (isa<SCEVCouldNotCompute>(Start)) 11830 return Start; 11831 } 11832 if (End->getType()->isPointerTy()) { 11833 End = getLosslessPtrToIntExpr(End); 11834 if (isa<SCEVCouldNotCompute>(End)) 11835 return End; 11836 } 11837 11838 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride); 11839 11840 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11841 : getUnsignedRangeMax(Start); 11842 11843 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11844 : getUnsignedRangeMin(Stride); 11845 11846 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11847 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11848 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11849 11850 // Although End can be a MIN expression we estimate MinEnd considering only 11851 // the case End = RHS. This is safe because in the other case (Start - End) 11852 // is zero, leading to a zero maximum backedge taken count. 11853 APInt MinEnd = 11854 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11855 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11856 11857 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11858 ? BECount 11859 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 11860 getConstant(MinStride)); 11861 11862 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11863 MaxBECount = BECount; 11864 11865 return ExitLimit(BECount, MaxBECount, false, Predicates); 11866 } 11867 11868 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11869 ScalarEvolution &SE) const { 11870 if (Range.isFullSet()) // Infinite loop. 11871 return SE.getCouldNotCompute(); 11872 11873 // If the start is a non-zero constant, shift the range to simplify things. 11874 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11875 if (!SC->getValue()->isZero()) { 11876 SmallVector<const SCEV *, 4> Operands(operands()); 11877 Operands[0] = SE.getZero(SC->getType()); 11878 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11879 getNoWrapFlags(FlagNW)); 11880 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11881 return ShiftedAddRec->getNumIterationsInRange( 11882 Range.subtract(SC->getAPInt()), SE); 11883 // This is strange and shouldn't happen. 11884 return SE.getCouldNotCompute(); 11885 } 11886 11887 // The only time we can solve this is when we have all constant indices. 11888 // Otherwise, we cannot determine the overflow conditions. 11889 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11890 return SE.getCouldNotCompute(); 11891 11892 // Okay at this point we know that all elements of the chrec are constants and 11893 // that the start element is zero. 11894 11895 // First check to see if the range contains zero. If not, the first 11896 // iteration exits. 11897 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11898 if (!Range.contains(APInt(BitWidth, 0))) 11899 return SE.getZero(getType()); 11900 11901 if (isAffine()) { 11902 // If this is an affine expression then we have this situation: 11903 // Solve {0,+,A} in Range === Ax in Range 11904 11905 // We know that zero is in the range. If A is positive then we know that 11906 // the upper value of the range must be the first possible exit value. 11907 // If A is negative then the lower of the range is the last possible loop 11908 // value. Also note that we already checked for a full range. 11909 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11910 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11911 11912 // The exit value should be (End+A)/A. 11913 APInt ExitVal = (End + A).udiv(A); 11914 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11915 11916 // Evaluate at the exit value. If we really did fall out of the valid 11917 // range, then we computed our trip count, otherwise wrap around or other 11918 // things must have happened. 11919 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11920 if (Range.contains(Val->getValue())) 11921 return SE.getCouldNotCompute(); // Something strange happened 11922 11923 // Ensure that the previous value is in the range. This is a sanity check. 11924 assert(Range.contains( 11925 EvaluateConstantChrecAtConstant(this, 11926 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11927 "Linear scev computation is off in a bad way!"); 11928 return SE.getConstant(ExitValue); 11929 } 11930 11931 if (isQuadratic()) { 11932 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11933 return SE.getConstant(S.getValue()); 11934 } 11935 11936 return SE.getCouldNotCompute(); 11937 } 11938 11939 const SCEVAddRecExpr * 11940 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11941 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11942 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11943 // but in this case we cannot guarantee that the value returned will be an 11944 // AddRec because SCEV does not have a fixed point where it stops 11945 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11946 // may happen if we reach arithmetic depth limit while simplifying. So we 11947 // construct the returned value explicitly. 11948 SmallVector<const SCEV *, 3> Ops; 11949 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11950 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11951 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11952 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11953 // We know that the last operand is not a constant zero (otherwise it would 11954 // have been popped out earlier). This guarantees us that if the result has 11955 // the same last operand, then it will also not be popped out, meaning that 11956 // the returned value will be an AddRec. 11957 const SCEV *Last = getOperand(getNumOperands() - 1); 11958 assert(!Last->isZero() && "Recurrency with zero step?"); 11959 Ops.push_back(Last); 11960 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11961 SCEV::FlagAnyWrap)); 11962 } 11963 11964 // Return true when S contains at least an undef value. 11965 static inline bool containsUndefs(const SCEV *S) { 11966 return SCEVExprContains(S, [](const SCEV *S) { 11967 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11968 return isa<UndefValue>(SU->getValue()); 11969 return false; 11970 }); 11971 } 11972 11973 namespace { 11974 11975 // Collect all steps of SCEV expressions. 11976 struct SCEVCollectStrides { 11977 ScalarEvolution &SE; 11978 SmallVectorImpl<const SCEV *> &Strides; 11979 11980 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11981 : SE(SE), Strides(S) {} 11982 11983 bool follow(const SCEV *S) { 11984 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11985 Strides.push_back(AR->getStepRecurrence(SE)); 11986 return true; 11987 } 11988 11989 bool isDone() const { return false; } 11990 }; 11991 11992 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11993 struct SCEVCollectTerms { 11994 SmallVectorImpl<const SCEV *> &Terms; 11995 11996 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11997 11998 bool follow(const SCEV *S) { 11999 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 12000 isa<SCEVSignExtendExpr>(S)) { 12001 if (!containsUndefs(S)) 12002 Terms.push_back(S); 12003 12004 // Stop recursion: once we collected a term, do not walk its operands. 12005 return false; 12006 } 12007 12008 // Keep looking. 12009 return true; 12010 } 12011 12012 bool isDone() const { return false; } 12013 }; 12014 12015 // Check if a SCEV contains an AddRecExpr. 12016 struct SCEVHasAddRec { 12017 bool &ContainsAddRec; 12018 12019 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 12020 ContainsAddRec = false; 12021 } 12022 12023 bool follow(const SCEV *S) { 12024 if (isa<SCEVAddRecExpr>(S)) { 12025 ContainsAddRec = true; 12026 12027 // Stop recursion: once we collected a term, do not walk its operands. 12028 return false; 12029 } 12030 12031 // Keep looking. 12032 return true; 12033 } 12034 12035 bool isDone() const { return false; } 12036 }; 12037 12038 // Find factors that are multiplied with an expression that (possibly as a 12039 // subexpression) contains an AddRecExpr. In the expression: 12040 // 12041 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 12042 // 12043 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 12044 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 12045 // parameters as they form a product with an induction variable. 12046 // 12047 // This collector expects all array size parameters to be in the same MulExpr. 12048 // It might be necessary to later add support for collecting parameters that are 12049 // spread over different nested MulExpr. 12050 struct SCEVCollectAddRecMultiplies { 12051 SmallVectorImpl<const SCEV *> &Terms; 12052 ScalarEvolution &SE; 12053 12054 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 12055 : Terms(T), SE(SE) {} 12056 12057 bool follow(const SCEV *S) { 12058 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 12059 bool HasAddRec = false; 12060 SmallVector<const SCEV *, 0> Operands; 12061 for (auto Op : Mul->operands()) { 12062 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 12063 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 12064 Operands.push_back(Op); 12065 } else if (Unknown) { 12066 HasAddRec = true; 12067 } else { 12068 bool ContainsAddRec = false; 12069 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 12070 visitAll(Op, ContiansAddRec); 12071 HasAddRec |= ContainsAddRec; 12072 } 12073 } 12074 if (Operands.size() == 0) 12075 return true; 12076 12077 if (!HasAddRec) 12078 return false; 12079 12080 Terms.push_back(SE.getMulExpr(Operands)); 12081 // Stop recursion: once we collected a term, do not walk its operands. 12082 return false; 12083 } 12084 12085 // Keep looking. 12086 return true; 12087 } 12088 12089 bool isDone() const { return false; } 12090 }; 12091 12092 } // end anonymous namespace 12093 12094 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 12095 /// two places: 12096 /// 1) The strides of AddRec expressions. 12097 /// 2) Unknowns that are multiplied with AddRec expressions. 12098 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 12099 SmallVectorImpl<const SCEV *> &Terms) { 12100 SmallVector<const SCEV *, 4> Strides; 12101 SCEVCollectStrides StrideCollector(*this, Strides); 12102 visitAll(Expr, StrideCollector); 12103 12104 LLVM_DEBUG({ 12105 dbgs() << "Strides:\n"; 12106 for (const SCEV *S : Strides) 12107 dbgs() << *S << "\n"; 12108 }); 12109 12110 for (const SCEV *S : Strides) { 12111 SCEVCollectTerms TermCollector(Terms); 12112 visitAll(S, TermCollector); 12113 } 12114 12115 LLVM_DEBUG({ 12116 dbgs() << "Terms:\n"; 12117 for (const SCEV *T : Terms) 12118 dbgs() << *T << "\n"; 12119 }); 12120 12121 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 12122 visitAll(Expr, MulCollector); 12123 } 12124 12125 static bool findArrayDimensionsRec(ScalarEvolution &SE, 12126 SmallVectorImpl<const SCEV *> &Terms, 12127 SmallVectorImpl<const SCEV *> &Sizes) { 12128 int Last = Terms.size() - 1; 12129 const SCEV *Step = Terms[Last]; 12130 12131 // End of recursion. 12132 if (Last == 0) { 12133 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 12134 SmallVector<const SCEV *, 2> Qs; 12135 for (const SCEV *Op : M->operands()) 12136 if (!isa<SCEVConstant>(Op)) 12137 Qs.push_back(Op); 12138 12139 Step = SE.getMulExpr(Qs); 12140 } 12141 12142 Sizes.push_back(Step); 12143 return true; 12144 } 12145 12146 for (const SCEV *&Term : Terms) { 12147 // Normalize the terms before the next call to findArrayDimensionsRec. 12148 const SCEV *Q, *R; 12149 SCEVDivision::divide(SE, Term, Step, &Q, &R); 12150 12151 // Bail out when GCD does not evenly divide one of the terms. 12152 if (!R->isZero()) 12153 return false; 12154 12155 Term = Q; 12156 } 12157 12158 // Remove all SCEVConstants. 12159 erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }); 12160 12161 if (Terms.size() > 0) 12162 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 12163 return false; 12164 12165 Sizes.push_back(Step); 12166 return true; 12167 } 12168 12169 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 12170 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 12171 for (const SCEV *T : Terms) 12172 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 12173 return true; 12174 12175 return false; 12176 } 12177 12178 // Return the number of product terms in S. 12179 static inline int numberOfTerms(const SCEV *S) { 12180 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 12181 return Expr->getNumOperands(); 12182 return 1; 12183 } 12184 12185 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 12186 if (isa<SCEVConstant>(T)) 12187 return nullptr; 12188 12189 if (isa<SCEVUnknown>(T)) 12190 return T; 12191 12192 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 12193 SmallVector<const SCEV *, 2> Factors; 12194 for (const SCEV *Op : M->operands()) 12195 if (!isa<SCEVConstant>(Op)) 12196 Factors.push_back(Op); 12197 12198 return SE.getMulExpr(Factors); 12199 } 12200 12201 return T; 12202 } 12203 12204 /// Return the size of an element read or written by Inst. 12205 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12206 Type *Ty; 12207 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12208 Ty = Store->getValueOperand()->getType(); 12209 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12210 Ty = Load->getType(); 12211 else 12212 return nullptr; 12213 12214 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12215 return getSizeOfExpr(ETy, Ty); 12216 } 12217 12218 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 12219 SmallVectorImpl<const SCEV *> &Sizes, 12220 const SCEV *ElementSize) { 12221 if (Terms.size() < 1 || !ElementSize) 12222 return; 12223 12224 // Early return when Terms do not contain parameters: we do not delinearize 12225 // non parametric SCEVs. 12226 if (!containsParameters(Terms)) 12227 return; 12228 12229 LLVM_DEBUG({ 12230 dbgs() << "Terms:\n"; 12231 for (const SCEV *T : Terms) 12232 dbgs() << *T << "\n"; 12233 }); 12234 12235 // Remove duplicates. 12236 array_pod_sort(Terms.begin(), Terms.end()); 12237 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 12238 12239 // Put larger terms first. 12240 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 12241 return numberOfTerms(LHS) > numberOfTerms(RHS); 12242 }); 12243 12244 // Try to divide all terms by the element size. If term is not divisible by 12245 // element size, proceed with the original term. 12246 for (const SCEV *&Term : Terms) { 12247 const SCEV *Q, *R; 12248 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 12249 if (!Q->isZero()) 12250 Term = Q; 12251 } 12252 12253 SmallVector<const SCEV *, 4> NewTerms; 12254 12255 // Remove constant factors. 12256 for (const SCEV *T : Terms) 12257 if (const SCEV *NewT = removeConstantFactors(*this, T)) 12258 NewTerms.push_back(NewT); 12259 12260 LLVM_DEBUG({ 12261 dbgs() << "Terms after sorting:\n"; 12262 for (const SCEV *T : NewTerms) 12263 dbgs() << *T << "\n"; 12264 }); 12265 12266 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 12267 Sizes.clear(); 12268 return; 12269 } 12270 12271 // The last element to be pushed into Sizes is the size of an element. 12272 Sizes.push_back(ElementSize); 12273 12274 LLVM_DEBUG({ 12275 dbgs() << "Sizes:\n"; 12276 for (const SCEV *S : Sizes) 12277 dbgs() << *S << "\n"; 12278 }); 12279 } 12280 12281 void ScalarEvolution::computeAccessFunctions( 12282 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 12283 SmallVectorImpl<const SCEV *> &Sizes) { 12284 // Early exit in case this SCEV is not an affine multivariate function. 12285 if (Sizes.empty()) 12286 return; 12287 12288 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 12289 if (!AR->isAffine()) 12290 return; 12291 12292 const SCEV *Res = Expr; 12293 int Last = Sizes.size() - 1; 12294 for (int i = Last; i >= 0; i--) { 12295 const SCEV *Q, *R; 12296 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 12297 12298 LLVM_DEBUG({ 12299 dbgs() << "Res: " << *Res << "\n"; 12300 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 12301 dbgs() << "Res divided by Sizes[i]:\n"; 12302 dbgs() << "Quotient: " << *Q << "\n"; 12303 dbgs() << "Remainder: " << *R << "\n"; 12304 }); 12305 12306 Res = Q; 12307 12308 // Do not record the last subscript corresponding to the size of elements in 12309 // the array. 12310 if (i == Last) { 12311 12312 // Bail out if the remainder is too complex. 12313 if (isa<SCEVAddRecExpr>(R)) { 12314 Subscripts.clear(); 12315 Sizes.clear(); 12316 return; 12317 } 12318 12319 continue; 12320 } 12321 12322 // Record the access function for the current subscript. 12323 Subscripts.push_back(R); 12324 } 12325 12326 // Also push in last position the remainder of the last division: it will be 12327 // the access function of the innermost dimension. 12328 Subscripts.push_back(Res); 12329 12330 std::reverse(Subscripts.begin(), Subscripts.end()); 12331 12332 LLVM_DEBUG({ 12333 dbgs() << "Subscripts:\n"; 12334 for (const SCEV *S : Subscripts) 12335 dbgs() << *S << "\n"; 12336 }); 12337 } 12338 12339 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 12340 /// sizes of an array access. Returns the remainder of the delinearization that 12341 /// is the offset start of the array. The SCEV->delinearize algorithm computes 12342 /// the multiples of SCEV coefficients: that is a pattern matching of sub 12343 /// expressions in the stride and base of a SCEV corresponding to the 12344 /// computation of a GCD (greatest common divisor) of base and stride. When 12345 /// SCEV->delinearize fails, it returns the SCEV unchanged. 12346 /// 12347 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 12348 /// 12349 /// void foo(long n, long m, long o, double A[n][m][o]) { 12350 /// 12351 /// for (long i = 0; i < n; i++) 12352 /// for (long j = 0; j < m; j++) 12353 /// for (long k = 0; k < o; k++) 12354 /// A[i][j][k] = 1.0; 12355 /// } 12356 /// 12357 /// the delinearization input is the following AddRec SCEV: 12358 /// 12359 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 12360 /// 12361 /// From this SCEV, we are able to say that the base offset of the access is %A 12362 /// because it appears as an offset that does not divide any of the strides in 12363 /// the loops: 12364 /// 12365 /// CHECK: Base offset: %A 12366 /// 12367 /// and then SCEV->delinearize determines the size of some of the dimensions of 12368 /// the array as these are the multiples by which the strides are happening: 12369 /// 12370 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 12371 /// 12372 /// Note that the outermost dimension remains of UnknownSize because there are 12373 /// no strides that would help identifying the size of the last dimension: when 12374 /// the array has been statically allocated, one could compute the size of that 12375 /// dimension by dividing the overall size of the array by the size of the known 12376 /// dimensions: %m * %o * 8. 12377 /// 12378 /// Finally delinearize provides the access functions for the array reference 12379 /// that does correspond to A[i][j][k] of the above C testcase: 12380 /// 12381 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 12382 /// 12383 /// The testcases are checking the output of a function pass: 12384 /// DelinearizationPass that walks through all loads and stores of a function 12385 /// asking for the SCEV of the memory access with respect to all enclosing 12386 /// loops, calling SCEV->delinearize on that and printing the results. 12387 void ScalarEvolution::delinearize(const SCEV *Expr, 12388 SmallVectorImpl<const SCEV *> &Subscripts, 12389 SmallVectorImpl<const SCEV *> &Sizes, 12390 const SCEV *ElementSize) { 12391 // First step: collect parametric terms. 12392 SmallVector<const SCEV *, 4> Terms; 12393 collectParametricTerms(Expr, Terms); 12394 12395 if (Terms.empty()) 12396 return; 12397 12398 // Second step: find subscript sizes. 12399 findArrayDimensions(Terms, Sizes, ElementSize); 12400 12401 if (Sizes.empty()) 12402 return; 12403 12404 // Third step: compute the access functions for each subscript. 12405 computeAccessFunctions(Expr, Subscripts, Sizes); 12406 12407 if (Subscripts.empty()) 12408 return; 12409 12410 LLVM_DEBUG({ 12411 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 12412 dbgs() << "ArrayDecl[UnknownSize]"; 12413 for (const SCEV *S : Sizes) 12414 dbgs() << "[" << *S << "]"; 12415 12416 dbgs() << "\nArrayRef"; 12417 for (const SCEV *S : Subscripts) 12418 dbgs() << "[" << *S << "]"; 12419 dbgs() << "\n"; 12420 }); 12421 } 12422 12423 bool ScalarEvolution::getIndexExpressionsFromGEP( 12424 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 12425 SmallVectorImpl<int> &Sizes) { 12426 assert(Subscripts.empty() && Sizes.empty() && 12427 "Expected output lists to be empty on entry to this function."); 12428 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 12429 Type *Ty = GEP->getPointerOperandType(); 12430 bool DroppedFirstDim = false; 12431 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 12432 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 12433 if (i == 1) { 12434 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 12435 Ty = PtrTy->getElementType(); 12436 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 12437 Ty = ArrayTy->getElementType(); 12438 } else { 12439 Subscripts.clear(); 12440 Sizes.clear(); 12441 return false; 12442 } 12443 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 12444 if (Const->getValue()->isZero()) { 12445 DroppedFirstDim = true; 12446 continue; 12447 } 12448 Subscripts.push_back(Expr); 12449 continue; 12450 } 12451 12452 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 12453 if (!ArrayTy) { 12454 Subscripts.clear(); 12455 Sizes.clear(); 12456 return false; 12457 } 12458 12459 Subscripts.push_back(Expr); 12460 if (!(DroppedFirstDim && i == 2)) 12461 Sizes.push_back(ArrayTy->getNumElements()); 12462 12463 Ty = ArrayTy->getElementType(); 12464 } 12465 return !Subscripts.empty(); 12466 } 12467 12468 //===----------------------------------------------------------------------===// 12469 // SCEVCallbackVH Class Implementation 12470 //===----------------------------------------------------------------------===// 12471 12472 void ScalarEvolution::SCEVCallbackVH::deleted() { 12473 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12474 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12475 SE->ConstantEvolutionLoopExitValue.erase(PN); 12476 SE->eraseValueFromMap(getValPtr()); 12477 // this now dangles! 12478 } 12479 12480 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12481 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12482 12483 // Forget all the expressions associated with users of the old value, 12484 // so that future queries will recompute the expressions using the new 12485 // value. 12486 Value *Old = getValPtr(); 12487 SmallVector<User *, 16> Worklist(Old->users()); 12488 SmallPtrSet<User *, 8> Visited; 12489 while (!Worklist.empty()) { 12490 User *U = Worklist.pop_back_val(); 12491 // Deleting the Old value will cause this to dangle. Postpone 12492 // that until everything else is done. 12493 if (U == Old) 12494 continue; 12495 if (!Visited.insert(U).second) 12496 continue; 12497 if (PHINode *PN = dyn_cast<PHINode>(U)) 12498 SE->ConstantEvolutionLoopExitValue.erase(PN); 12499 SE->eraseValueFromMap(U); 12500 llvm::append_range(Worklist, U->users()); 12501 } 12502 // Delete the Old value. 12503 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12504 SE->ConstantEvolutionLoopExitValue.erase(PN); 12505 SE->eraseValueFromMap(Old); 12506 // this now dangles! 12507 } 12508 12509 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12510 : CallbackVH(V), SE(se) {} 12511 12512 //===----------------------------------------------------------------------===// 12513 // ScalarEvolution Class Implementation 12514 //===----------------------------------------------------------------------===// 12515 12516 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12517 AssumptionCache &AC, DominatorTree &DT, 12518 LoopInfo &LI) 12519 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12520 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12521 LoopDispositions(64), BlockDispositions(64) { 12522 // To use guards for proving predicates, we need to scan every instruction in 12523 // relevant basic blocks, and not just terminators. Doing this is a waste of 12524 // time if the IR does not actually contain any calls to 12525 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12526 // 12527 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12528 // to _add_ guards to the module when there weren't any before, and wants 12529 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12530 // efficient in lieu of being smart in that rather obscure case. 12531 12532 auto *GuardDecl = F.getParent()->getFunction( 12533 Intrinsic::getName(Intrinsic::experimental_guard)); 12534 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12535 } 12536 12537 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12538 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12539 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12540 ValueExprMap(std::move(Arg.ValueExprMap)), 12541 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12542 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12543 PendingMerges(std::move(Arg.PendingMerges)), 12544 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12545 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12546 PredicatedBackedgeTakenCounts( 12547 std::move(Arg.PredicatedBackedgeTakenCounts)), 12548 ConstantEvolutionLoopExitValue( 12549 std::move(Arg.ConstantEvolutionLoopExitValue)), 12550 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12551 LoopDispositions(std::move(Arg.LoopDispositions)), 12552 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12553 BlockDispositions(std::move(Arg.BlockDispositions)), 12554 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12555 SignedRanges(std::move(Arg.SignedRanges)), 12556 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12557 UniquePreds(std::move(Arg.UniquePreds)), 12558 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12559 LoopUsers(std::move(Arg.LoopUsers)), 12560 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12561 FirstUnknown(Arg.FirstUnknown) { 12562 Arg.FirstUnknown = nullptr; 12563 } 12564 12565 ScalarEvolution::~ScalarEvolution() { 12566 // Iterate through all the SCEVUnknown instances and call their 12567 // destructors, so that they release their references to their values. 12568 for (SCEVUnknown *U = FirstUnknown; U;) { 12569 SCEVUnknown *Tmp = U; 12570 U = U->Next; 12571 Tmp->~SCEVUnknown(); 12572 } 12573 FirstUnknown = nullptr; 12574 12575 ExprValueMap.clear(); 12576 ValueExprMap.clear(); 12577 HasRecMap.clear(); 12578 BackedgeTakenCounts.clear(); 12579 PredicatedBackedgeTakenCounts.clear(); 12580 12581 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12582 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12583 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12584 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12585 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12586 } 12587 12588 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12589 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12590 } 12591 12592 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12593 const Loop *L) { 12594 // Print all inner loops first 12595 for (Loop *I : *L) 12596 PrintLoopInfo(OS, SE, I); 12597 12598 OS << "Loop "; 12599 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12600 OS << ": "; 12601 12602 SmallVector<BasicBlock *, 8> ExitingBlocks; 12603 L->getExitingBlocks(ExitingBlocks); 12604 if (ExitingBlocks.size() != 1) 12605 OS << "<multiple exits> "; 12606 12607 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12608 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12609 else 12610 OS << "Unpredictable backedge-taken count.\n"; 12611 12612 if (ExitingBlocks.size() > 1) 12613 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12614 OS << " exit count for " << ExitingBlock->getName() << ": " 12615 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12616 } 12617 12618 OS << "Loop "; 12619 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12620 OS << ": "; 12621 12622 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12623 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12624 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12625 OS << ", actual taken count either this or zero."; 12626 } else { 12627 OS << "Unpredictable max backedge-taken count. "; 12628 } 12629 12630 OS << "\n" 12631 "Loop "; 12632 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12633 OS << ": "; 12634 12635 SCEVUnionPredicate Pred; 12636 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12637 if (!isa<SCEVCouldNotCompute>(PBT)) { 12638 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12639 OS << " Predicates:\n"; 12640 Pred.print(OS, 4); 12641 } else { 12642 OS << "Unpredictable predicated backedge-taken count. "; 12643 } 12644 OS << "\n"; 12645 12646 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12647 OS << "Loop "; 12648 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12649 OS << ": "; 12650 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12651 } 12652 } 12653 12654 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12655 switch (LD) { 12656 case ScalarEvolution::LoopVariant: 12657 return "Variant"; 12658 case ScalarEvolution::LoopInvariant: 12659 return "Invariant"; 12660 case ScalarEvolution::LoopComputable: 12661 return "Computable"; 12662 } 12663 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12664 } 12665 12666 void ScalarEvolution::print(raw_ostream &OS) const { 12667 // ScalarEvolution's implementation of the print method is to print 12668 // out SCEV values of all instructions that are interesting. Doing 12669 // this potentially causes it to create new SCEV objects though, 12670 // which technically conflicts with the const qualifier. This isn't 12671 // observable from outside the class though, so casting away the 12672 // const isn't dangerous. 12673 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12674 12675 if (ClassifyExpressions) { 12676 OS << "Classifying expressions for: "; 12677 F.printAsOperand(OS, /*PrintType=*/false); 12678 OS << "\n"; 12679 for (Instruction &I : instructions(F)) 12680 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12681 OS << I << '\n'; 12682 OS << " --> "; 12683 const SCEV *SV = SE.getSCEV(&I); 12684 SV->print(OS); 12685 if (!isa<SCEVCouldNotCompute>(SV)) { 12686 OS << " U: "; 12687 SE.getUnsignedRange(SV).print(OS); 12688 OS << " S: "; 12689 SE.getSignedRange(SV).print(OS); 12690 } 12691 12692 const Loop *L = LI.getLoopFor(I.getParent()); 12693 12694 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12695 if (AtUse != SV) { 12696 OS << " --> "; 12697 AtUse->print(OS); 12698 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12699 OS << " U: "; 12700 SE.getUnsignedRange(AtUse).print(OS); 12701 OS << " S: "; 12702 SE.getSignedRange(AtUse).print(OS); 12703 } 12704 } 12705 12706 if (L) { 12707 OS << "\t\t" "Exits: "; 12708 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12709 if (!SE.isLoopInvariant(ExitValue, L)) { 12710 OS << "<<Unknown>>"; 12711 } else { 12712 OS << *ExitValue; 12713 } 12714 12715 bool First = true; 12716 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12717 if (First) { 12718 OS << "\t\t" "LoopDispositions: { "; 12719 First = false; 12720 } else { 12721 OS << ", "; 12722 } 12723 12724 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12725 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12726 } 12727 12728 for (auto *InnerL : depth_first(L)) { 12729 if (InnerL == L) 12730 continue; 12731 if (First) { 12732 OS << "\t\t" "LoopDispositions: { "; 12733 First = false; 12734 } else { 12735 OS << ", "; 12736 } 12737 12738 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12739 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12740 } 12741 12742 OS << " }"; 12743 } 12744 12745 OS << "\n"; 12746 } 12747 } 12748 12749 OS << "Determining loop execution counts for: "; 12750 F.printAsOperand(OS, /*PrintType=*/false); 12751 OS << "\n"; 12752 for (Loop *I : LI) 12753 PrintLoopInfo(OS, &SE, I); 12754 } 12755 12756 ScalarEvolution::LoopDisposition 12757 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12758 auto &Values = LoopDispositions[S]; 12759 for (auto &V : Values) { 12760 if (V.getPointer() == L) 12761 return V.getInt(); 12762 } 12763 Values.emplace_back(L, LoopVariant); 12764 LoopDisposition D = computeLoopDisposition(S, L); 12765 auto &Values2 = LoopDispositions[S]; 12766 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12767 if (V.getPointer() == L) { 12768 V.setInt(D); 12769 break; 12770 } 12771 } 12772 return D; 12773 } 12774 12775 ScalarEvolution::LoopDisposition 12776 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12777 switch (S->getSCEVType()) { 12778 case scConstant: 12779 return LoopInvariant; 12780 case scPtrToInt: 12781 case scTruncate: 12782 case scZeroExtend: 12783 case scSignExtend: 12784 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12785 case scAddRecExpr: { 12786 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12787 12788 // If L is the addrec's loop, it's computable. 12789 if (AR->getLoop() == L) 12790 return LoopComputable; 12791 12792 // Add recurrences are never invariant in the function-body (null loop). 12793 if (!L) 12794 return LoopVariant; 12795 12796 // Everything that is not defined at loop entry is variant. 12797 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12798 return LoopVariant; 12799 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12800 " dominate the contained loop's header?"); 12801 12802 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12803 if (AR->getLoop()->contains(L)) 12804 return LoopInvariant; 12805 12806 // This recurrence is variant w.r.t. L if any of its operands 12807 // are variant. 12808 for (auto *Op : AR->operands()) 12809 if (!isLoopInvariant(Op, L)) 12810 return LoopVariant; 12811 12812 // Otherwise it's loop-invariant. 12813 return LoopInvariant; 12814 } 12815 case scAddExpr: 12816 case scMulExpr: 12817 case scUMaxExpr: 12818 case scSMaxExpr: 12819 case scUMinExpr: 12820 case scSMinExpr: { 12821 bool HasVarying = false; 12822 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12823 LoopDisposition D = getLoopDisposition(Op, L); 12824 if (D == LoopVariant) 12825 return LoopVariant; 12826 if (D == LoopComputable) 12827 HasVarying = true; 12828 } 12829 return HasVarying ? LoopComputable : LoopInvariant; 12830 } 12831 case scUDivExpr: { 12832 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12833 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12834 if (LD == LoopVariant) 12835 return LoopVariant; 12836 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12837 if (RD == LoopVariant) 12838 return LoopVariant; 12839 return (LD == LoopInvariant && RD == LoopInvariant) ? 12840 LoopInvariant : LoopComputable; 12841 } 12842 case scUnknown: 12843 // All non-instruction values are loop invariant. All instructions are loop 12844 // invariant if they are not contained in the specified loop. 12845 // Instructions are never considered invariant in the function body 12846 // (null loop) because they are defined within the "loop". 12847 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12848 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12849 return LoopInvariant; 12850 case scCouldNotCompute: 12851 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12852 } 12853 llvm_unreachable("Unknown SCEV kind!"); 12854 } 12855 12856 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12857 return getLoopDisposition(S, L) == LoopInvariant; 12858 } 12859 12860 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12861 return getLoopDisposition(S, L) == LoopComputable; 12862 } 12863 12864 ScalarEvolution::BlockDisposition 12865 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12866 auto &Values = BlockDispositions[S]; 12867 for (auto &V : Values) { 12868 if (V.getPointer() == BB) 12869 return V.getInt(); 12870 } 12871 Values.emplace_back(BB, DoesNotDominateBlock); 12872 BlockDisposition D = computeBlockDisposition(S, BB); 12873 auto &Values2 = BlockDispositions[S]; 12874 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12875 if (V.getPointer() == BB) { 12876 V.setInt(D); 12877 break; 12878 } 12879 } 12880 return D; 12881 } 12882 12883 ScalarEvolution::BlockDisposition 12884 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12885 switch (S->getSCEVType()) { 12886 case scConstant: 12887 return ProperlyDominatesBlock; 12888 case scPtrToInt: 12889 case scTruncate: 12890 case scZeroExtend: 12891 case scSignExtend: 12892 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12893 case scAddRecExpr: { 12894 // This uses a "dominates" query instead of "properly dominates" query 12895 // to test for proper dominance too, because the instruction which 12896 // produces the addrec's value is a PHI, and a PHI effectively properly 12897 // dominates its entire containing block. 12898 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12899 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12900 return DoesNotDominateBlock; 12901 12902 // Fall through into SCEVNAryExpr handling. 12903 LLVM_FALLTHROUGH; 12904 } 12905 case scAddExpr: 12906 case scMulExpr: 12907 case scUMaxExpr: 12908 case scSMaxExpr: 12909 case scUMinExpr: 12910 case scSMinExpr: { 12911 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12912 bool Proper = true; 12913 for (const SCEV *NAryOp : NAry->operands()) { 12914 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12915 if (D == DoesNotDominateBlock) 12916 return DoesNotDominateBlock; 12917 if (D == DominatesBlock) 12918 Proper = false; 12919 } 12920 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12921 } 12922 case scUDivExpr: { 12923 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12924 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12925 BlockDisposition LD = getBlockDisposition(LHS, BB); 12926 if (LD == DoesNotDominateBlock) 12927 return DoesNotDominateBlock; 12928 BlockDisposition RD = getBlockDisposition(RHS, BB); 12929 if (RD == DoesNotDominateBlock) 12930 return DoesNotDominateBlock; 12931 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12932 ProperlyDominatesBlock : DominatesBlock; 12933 } 12934 case scUnknown: 12935 if (Instruction *I = 12936 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12937 if (I->getParent() == BB) 12938 return DominatesBlock; 12939 if (DT.properlyDominates(I->getParent(), BB)) 12940 return ProperlyDominatesBlock; 12941 return DoesNotDominateBlock; 12942 } 12943 return ProperlyDominatesBlock; 12944 case scCouldNotCompute: 12945 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12946 } 12947 llvm_unreachable("Unknown SCEV kind!"); 12948 } 12949 12950 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12951 return getBlockDisposition(S, BB) >= DominatesBlock; 12952 } 12953 12954 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12955 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12956 } 12957 12958 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12959 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12960 } 12961 12962 void 12963 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12964 ValuesAtScopes.erase(S); 12965 LoopDispositions.erase(S); 12966 BlockDispositions.erase(S); 12967 UnsignedRanges.erase(S); 12968 SignedRanges.erase(S); 12969 ExprValueMap.erase(S); 12970 HasRecMap.erase(S); 12971 MinTrailingZerosCache.erase(S); 12972 12973 for (auto I = PredicatedSCEVRewrites.begin(); 12974 I != PredicatedSCEVRewrites.end();) { 12975 std::pair<const SCEV *, const Loop *> Entry = I->first; 12976 if (Entry.first == S) 12977 PredicatedSCEVRewrites.erase(I++); 12978 else 12979 ++I; 12980 } 12981 12982 auto RemoveSCEVFromBackedgeMap = 12983 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12984 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12985 BackedgeTakenInfo &BEInfo = I->second; 12986 if (BEInfo.hasOperand(S)) 12987 Map.erase(I++); 12988 else 12989 ++I; 12990 } 12991 }; 12992 12993 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12994 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12995 } 12996 12997 void 12998 ScalarEvolution::getUsedLoops(const SCEV *S, 12999 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 13000 struct FindUsedLoops { 13001 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 13002 : LoopsUsed(LoopsUsed) {} 13003 SmallPtrSetImpl<const Loop *> &LoopsUsed; 13004 bool follow(const SCEV *S) { 13005 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 13006 LoopsUsed.insert(AR->getLoop()); 13007 return true; 13008 } 13009 13010 bool isDone() const { return false; } 13011 }; 13012 13013 FindUsedLoops F(LoopsUsed); 13014 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 13015 } 13016 13017 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 13018 SmallPtrSet<const Loop *, 8> LoopsUsed; 13019 getUsedLoops(S, LoopsUsed); 13020 for (auto *L : LoopsUsed) 13021 LoopUsers[L].push_back(S); 13022 } 13023 13024 void ScalarEvolution::verify() const { 13025 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13026 ScalarEvolution SE2(F, TLI, AC, DT, LI); 13027 13028 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 13029 13030 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 13031 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 13032 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 13033 13034 const SCEV *visitConstant(const SCEVConstant *Constant) { 13035 return SE.getConstant(Constant->getAPInt()); 13036 } 13037 13038 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13039 return SE.getUnknown(Expr->getValue()); 13040 } 13041 13042 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 13043 return SE.getCouldNotCompute(); 13044 } 13045 }; 13046 13047 SCEVMapper SCM(SE2); 13048 13049 while (!LoopStack.empty()) { 13050 auto *L = LoopStack.pop_back_val(); 13051 llvm::append_range(LoopStack, *L); 13052 13053 auto *CurBECount = SCM.visit( 13054 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 13055 auto *NewBECount = SE2.getBackedgeTakenCount(L); 13056 13057 if (CurBECount == SE2.getCouldNotCompute() || 13058 NewBECount == SE2.getCouldNotCompute()) { 13059 // NB! This situation is legal, but is very suspicious -- whatever pass 13060 // change the loop to make a trip count go from could not compute to 13061 // computable or vice-versa *should have* invalidated SCEV. However, we 13062 // choose not to assert here (for now) since we don't want false 13063 // positives. 13064 continue; 13065 } 13066 13067 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 13068 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 13069 // not propagate undef aggressively). This means we can (and do) fail 13070 // verification in cases where a transform makes the trip count of a loop 13071 // go from "undef" to "undef+1" (say). The transform is fine, since in 13072 // both cases the loop iterates "undef" times, but SCEV thinks we 13073 // increased the trip count of the loop by 1 incorrectly. 13074 continue; 13075 } 13076 13077 if (SE.getTypeSizeInBits(CurBECount->getType()) > 13078 SE.getTypeSizeInBits(NewBECount->getType())) 13079 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 13080 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 13081 SE.getTypeSizeInBits(NewBECount->getType())) 13082 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 13083 13084 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 13085 13086 // Unless VerifySCEVStrict is set, we only compare constant deltas. 13087 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 13088 dbgs() << "Trip Count for " << *L << " Changed!\n"; 13089 dbgs() << "Old: " << *CurBECount << "\n"; 13090 dbgs() << "New: " << *NewBECount << "\n"; 13091 dbgs() << "Delta: " << *Delta << "\n"; 13092 std::abort(); 13093 } 13094 } 13095 13096 // Collect all valid loops currently in LoopInfo. 13097 SmallPtrSet<Loop *, 32> ValidLoops; 13098 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 13099 while (!Worklist.empty()) { 13100 Loop *L = Worklist.pop_back_val(); 13101 if (ValidLoops.contains(L)) 13102 continue; 13103 ValidLoops.insert(L); 13104 Worklist.append(L->begin(), L->end()); 13105 } 13106 // Check for SCEV expressions referencing invalid/deleted loops. 13107 for (auto &KV : ValueExprMap) { 13108 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 13109 if (!AR) 13110 continue; 13111 assert(ValidLoops.contains(AR->getLoop()) && 13112 "AddRec references invalid loop"); 13113 } 13114 } 13115 13116 bool ScalarEvolution::invalidate( 13117 Function &F, const PreservedAnalyses &PA, 13118 FunctionAnalysisManager::Invalidator &Inv) { 13119 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 13120 // of its dependencies is invalidated. 13121 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 13122 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 13123 Inv.invalidate<AssumptionAnalysis>(F, PA) || 13124 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 13125 Inv.invalidate<LoopAnalysis>(F, PA); 13126 } 13127 13128 AnalysisKey ScalarEvolutionAnalysis::Key; 13129 13130 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 13131 FunctionAnalysisManager &AM) { 13132 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 13133 AM.getResult<AssumptionAnalysis>(F), 13134 AM.getResult<DominatorTreeAnalysis>(F), 13135 AM.getResult<LoopAnalysis>(F)); 13136 } 13137 13138 PreservedAnalyses 13139 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 13140 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 13141 return PreservedAnalyses::all(); 13142 } 13143 13144 PreservedAnalyses 13145 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 13146 // For compatibility with opt's -analyze feature under legacy pass manager 13147 // which was not ported to NPM. This keeps tests using 13148 // update_analyze_test_checks.py working. 13149 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 13150 << F.getName() << "':\n"; 13151 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 13152 return PreservedAnalyses::all(); 13153 } 13154 13155 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 13156 "Scalar Evolution Analysis", false, true) 13157 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 13158 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 13159 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 13160 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 13161 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 13162 "Scalar Evolution Analysis", false, true) 13163 13164 char ScalarEvolutionWrapperPass::ID = 0; 13165 13166 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 13167 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 13168 } 13169 13170 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 13171 SE.reset(new ScalarEvolution( 13172 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 13173 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 13174 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 13175 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 13176 return false; 13177 } 13178 13179 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 13180 13181 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 13182 SE->print(OS); 13183 } 13184 13185 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 13186 if (!VerifySCEV) 13187 return; 13188 13189 SE->verify(); 13190 } 13191 13192 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13193 AU.setPreservesAll(); 13194 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13195 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13196 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13197 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13198 } 13199 13200 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13201 const SCEV *RHS) { 13202 FoldingSetNodeID ID; 13203 assert(LHS->getType() == RHS->getType() && 13204 "Type mismatch between LHS and RHS"); 13205 // Unique this node based on the arguments 13206 ID.AddInteger(SCEVPredicate::P_Equal); 13207 ID.AddPointer(LHS); 13208 ID.AddPointer(RHS); 13209 void *IP = nullptr; 13210 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13211 return S; 13212 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13213 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13214 UniquePreds.InsertNode(Eq, IP); 13215 return Eq; 13216 } 13217 13218 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13219 const SCEVAddRecExpr *AR, 13220 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13221 FoldingSetNodeID ID; 13222 // Unique this node based on the arguments 13223 ID.AddInteger(SCEVPredicate::P_Wrap); 13224 ID.AddPointer(AR); 13225 ID.AddInteger(AddedFlags); 13226 void *IP = nullptr; 13227 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13228 return S; 13229 auto *OF = new (SCEVAllocator) 13230 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13231 UniquePreds.InsertNode(OF, IP); 13232 return OF; 13233 } 13234 13235 namespace { 13236 13237 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13238 public: 13239 13240 /// Rewrites \p S in the context of a loop L and the SCEV predication 13241 /// infrastructure. 13242 /// 13243 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13244 /// equivalences present in \p Pred. 13245 /// 13246 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13247 /// \p NewPreds such that the result will be an AddRecExpr. 13248 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13249 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13250 SCEVUnionPredicate *Pred) { 13251 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13252 return Rewriter.visit(S); 13253 } 13254 13255 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13256 if (Pred) { 13257 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13258 for (auto *Pred : ExprPreds) 13259 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13260 if (IPred->getLHS() == Expr) 13261 return IPred->getRHS(); 13262 } 13263 return convertToAddRecWithPreds(Expr); 13264 } 13265 13266 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13267 const SCEV *Operand = visit(Expr->getOperand()); 13268 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13269 if (AR && AR->getLoop() == L && AR->isAffine()) { 13270 // This couldn't be folded because the operand didn't have the nuw 13271 // flag. Add the nusw flag as an assumption that we could make. 13272 const SCEV *Step = AR->getStepRecurrence(SE); 13273 Type *Ty = Expr->getType(); 13274 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13275 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13276 SE.getSignExtendExpr(Step, Ty), L, 13277 AR->getNoWrapFlags()); 13278 } 13279 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13280 } 13281 13282 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13283 const SCEV *Operand = visit(Expr->getOperand()); 13284 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13285 if (AR && AR->getLoop() == L && AR->isAffine()) { 13286 // This couldn't be folded because the operand didn't have the nsw 13287 // flag. Add the nssw flag as an assumption that we could make. 13288 const SCEV *Step = AR->getStepRecurrence(SE); 13289 Type *Ty = Expr->getType(); 13290 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13291 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13292 SE.getSignExtendExpr(Step, Ty), L, 13293 AR->getNoWrapFlags()); 13294 } 13295 return SE.getSignExtendExpr(Operand, Expr->getType()); 13296 } 13297 13298 private: 13299 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13300 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13301 SCEVUnionPredicate *Pred) 13302 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13303 13304 bool addOverflowAssumption(const SCEVPredicate *P) { 13305 if (!NewPreds) { 13306 // Check if we've already made this assumption. 13307 return Pred && Pred->implies(P); 13308 } 13309 NewPreds->insert(P); 13310 return true; 13311 } 13312 13313 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13314 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13315 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13316 return addOverflowAssumption(A); 13317 } 13318 13319 // If \p Expr represents a PHINode, we try to see if it can be represented 13320 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13321 // to add this predicate as a runtime overflow check, we return the AddRec. 13322 // If \p Expr does not meet these conditions (is not a PHI node, or we 13323 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13324 // return \p Expr. 13325 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13326 if (!isa<PHINode>(Expr->getValue())) 13327 return Expr; 13328 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13329 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13330 if (!PredicatedRewrite) 13331 return Expr; 13332 for (auto *P : PredicatedRewrite->second){ 13333 // Wrap predicates from outer loops are not supported. 13334 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13335 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13336 if (L != AR->getLoop()) 13337 return Expr; 13338 } 13339 if (!addOverflowAssumption(P)) 13340 return Expr; 13341 } 13342 return PredicatedRewrite->first; 13343 } 13344 13345 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13346 SCEVUnionPredicate *Pred; 13347 const Loop *L; 13348 }; 13349 13350 } // end anonymous namespace 13351 13352 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13353 SCEVUnionPredicate &Preds) { 13354 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13355 } 13356 13357 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13358 const SCEV *S, const Loop *L, 13359 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13360 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13361 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13362 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13363 13364 if (!AddRec) 13365 return nullptr; 13366 13367 // Since the transformation was successful, we can now transfer the SCEV 13368 // predicates. 13369 for (auto *P : TransformPreds) 13370 Preds.insert(P); 13371 13372 return AddRec; 13373 } 13374 13375 /// SCEV predicates 13376 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13377 SCEVPredicateKind Kind) 13378 : FastID(ID), Kind(Kind) {} 13379 13380 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13381 const SCEV *LHS, const SCEV *RHS) 13382 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13383 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13384 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13385 } 13386 13387 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13388 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13389 13390 if (!Op) 13391 return false; 13392 13393 return Op->LHS == LHS && Op->RHS == RHS; 13394 } 13395 13396 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13397 13398 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13399 13400 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13401 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13402 } 13403 13404 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13405 const SCEVAddRecExpr *AR, 13406 IncrementWrapFlags Flags) 13407 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13408 13409 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13410 13411 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13412 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13413 13414 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13415 } 13416 13417 bool SCEVWrapPredicate::isAlwaysTrue() const { 13418 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13419 IncrementWrapFlags IFlags = Flags; 13420 13421 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13422 IFlags = clearFlags(IFlags, IncrementNSSW); 13423 13424 return IFlags == IncrementAnyWrap; 13425 } 13426 13427 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13428 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13429 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13430 OS << "<nusw>"; 13431 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13432 OS << "<nssw>"; 13433 OS << "\n"; 13434 } 13435 13436 SCEVWrapPredicate::IncrementWrapFlags 13437 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13438 ScalarEvolution &SE) { 13439 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13440 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13441 13442 // We can safely transfer the NSW flag as NSSW. 13443 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13444 ImpliedFlags = IncrementNSSW; 13445 13446 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13447 // If the increment is positive, the SCEV NUW flag will also imply the 13448 // WrapPredicate NUSW flag. 13449 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13450 if (Step->getValue()->getValue().isNonNegative()) 13451 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13452 } 13453 13454 return ImpliedFlags; 13455 } 13456 13457 /// Union predicates don't get cached so create a dummy set ID for it. 13458 SCEVUnionPredicate::SCEVUnionPredicate() 13459 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13460 13461 bool SCEVUnionPredicate::isAlwaysTrue() const { 13462 return all_of(Preds, 13463 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13464 } 13465 13466 ArrayRef<const SCEVPredicate *> 13467 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13468 auto I = SCEVToPreds.find(Expr); 13469 if (I == SCEVToPreds.end()) 13470 return ArrayRef<const SCEVPredicate *>(); 13471 return I->second; 13472 } 13473 13474 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13475 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13476 return all_of(Set->Preds, 13477 [this](const SCEVPredicate *I) { return this->implies(I); }); 13478 13479 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13480 if (ScevPredsIt == SCEVToPreds.end()) 13481 return false; 13482 auto &SCEVPreds = ScevPredsIt->second; 13483 13484 return any_of(SCEVPreds, 13485 [N](const SCEVPredicate *I) { return I->implies(N); }); 13486 } 13487 13488 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13489 13490 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13491 for (auto Pred : Preds) 13492 Pred->print(OS, Depth); 13493 } 13494 13495 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13496 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13497 for (auto Pred : Set->Preds) 13498 add(Pred); 13499 return; 13500 } 13501 13502 if (implies(N)) 13503 return; 13504 13505 const SCEV *Key = N->getExpr(); 13506 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13507 " associated expression!"); 13508 13509 SCEVToPreds[Key].push_back(N); 13510 Preds.push_back(N); 13511 } 13512 13513 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13514 Loop &L) 13515 : SE(SE), L(L) {} 13516 13517 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13518 const SCEV *Expr = SE.getSCEV(V); 13519 RewriteEntry &Entry = RewriteMap[Expr]; 13520 13521 // If we already have an entry and the version matches, return it. 13522 if (Entry.second && Generation == Entry.first) 13523 return Entry.second; 13524 13525 // We found an entry but it's stale. Rewrite the stale entry 13526 // according to the current predicate. 13527 if (Entry.second) 13528 Expr = Entry.second; 13529 13530 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13531 Entry = {Generation, NewSCEV}; 13532 13533 return NewSCEV; 13534 } 13535 13536 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13537 if (!BackedgeCount) { 13538 SCEVUnionPredicate BackedgePred; 13539 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13540 addPredicate(BackedgePred); 13541 } 13542 return BackedgeCount; 13543 } 13544 13545 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13546 if (Preds.implies(&Pred)) 13547 return; 13548 Preds.add(&Pred); 13549 updateGeneration(); 13550 } 13551 13552 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13553 return Preds; 13554 } 13555 13556 void PredicatedScalarEvolution::updateGeneration() { 13557 // If the generation number wrapped recompute everything. 13558 if (++Generation == 0) { 13559 for (auto &II : RewriteMap) { 13560 const SCEV *Rewritten = II.second.second; 13561 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13562 } 13563 } 13564 } 13565 13566 void PredicatedScalarEvolution::setNoOverflow( 13567 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13568 const SCEV *Expr = getSCEV(V); 13569 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13570 13571 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13572 13573 // Clear the statically implied flags. 13574 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13575 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13576 13577 auto II = FlagsMap.insert({V, Flags}); 13578 if (!II.second) 13579 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13580 } 13581 13582 bool PredicatedScalarEvolution::hasNoOverflow( 13583 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13584 const SCEV *Expr = getSCEV(V); 13585 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13586 13587 Flags = SCEVWrapPredicate::clearFlags( 13588 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13589 13590 auto II = FlagsMap.find(V); 13591 13592 if (II != FlagsMap.end()) 13593 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13594 13595 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13596 } 13597 13598 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13599 const SCEV *Expr = this->getSCEV(V); 13600 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13601 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13602 13603 if (!New) 13604 return nullptr; 13605 13606 for (auto *P : NewPreds) 13607 Preds.add(P); 13608 13609 updateGeneration(); 13610 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13611 return New; 13612 } 13613 13614 PredicatedScalarEvolution::PredicatedScalarEvolution( 13615 const PredicatedScalarEvolution &Init) 13616 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13617 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13618 for (auto I : Init.FlagsMap) 13619 FlagsMap.insert(I); 13620 } 13621 13622 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13623 // For each block. 13624 for (auto *BB : L.getBlocks()) 13625 for (auto &I : *BB) { 13626 if (!SE.isSCEVable(I.getType())) 13627 continue; 13628 13629 auto *Expr = SE.getSCEV(&I); 13630 auto II = RewriteMap.find(Expr); 13631 13632 if (II == RewriteMap.end()) 13633 continue; 13634 13635 // Don't print things that are not interesting. 13636 if (II->second.second == Expr) 13637 continue; 13638 13639 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13640 OS.indent(Depth + 2) << *Expr << "\n"; 13641 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13642 } 13643 } 13644 13645 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13646 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13647 // for URem with constant power-of-2 second operands. 13648 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13649 // 4, A / B becomes X / 8). 13650 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13651 const SCEV *&RHS) { 13652 // Try to match 'zext (trunc A to iB) to iY', which is used 13653 // for URem with constant power-of-2 second operands. Make sure the size of 13654 // the operand A matches the size of the whole expressions. 13655 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13656 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13657 LHS = Trunc->getOperand(); 13658 // Bail out if the type of the LHS is larger than the type of the 13659 // expression for now. 13660 if (getTypeSizeInBits(LHS->getType()) > 13661 getTypeSizeInBits(Expr->getType())) 13662 return false; 13663 if (LHS->getType() != Expr->getType()) 13664 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13665 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13666 << getTypeSizeInBits(Trunc->getType())); 13667 return true; 13668 } 13669 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13670 if (Add == nullptr || Add->getNumOperands() != 2) 13671 return false; 13672 13673 const SCEV *A = Add->getOperand(1); 13674 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13675 13676 if (Mul == nullptr) 13677 return false; 13678 13679 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13680 // (SomeExpr + (-(SomeExpr / B) * B)). 13681 if (Expr == getURemExpr(A, B)) { 13682 LHS = A; 13683 RHS = B; 13684 return true; 13685 } 13686 return false; 13687 }; 13688 13689 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13690 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13691 return MatchURemWithDivisor(Mul->getOperand(1)) || 13692 MatchURemWithDivisor(Mul->getOperand(2)); 13693 13694 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13695 if (Mul->getNumOperands() == 2) 13696 return MatchURemWithDivisor(Mul->getOperand(1)) || 13697 MatchURemWithDivisor(Mul->getOperand(0)) || 13698 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13699 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13700 return false; 13701 } 13702 13703 const SCEV * 13704 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13705 SmallVector<BasicBlock*, 16> ExitingBlocks; 13706 L->getExitingBlocks(ExitingBlocks); 13707 13708 // Form an expression for the maximum exit count possible for this loop. We 13709 // merge the max and exact information to approximate a version of 13710 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13711 SmallVector<const SCEV*, 4> ExitCounts; 13712 for (BasicBlock *ExitingBB : ExitingBlocks) { 13713 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13714 if (isa<SCEVCouldNotCompute>(ExitCount)) 13715 ExitCount = getExitCount(L, ExitingBB, 13716 ScalarEvolution::ConstantMaximum); 13717 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13718 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13719 "We should only have known counts for exiting blocks that " 13720 "dominate latch!"); 13721 ExitCounts.push_back(ExitCount); 13722 } 13723 } 13724 if (ExitCounts.empty()) 13725 return getCouldNotCompute(); 13726 return getUMinFromMismatchedTypes(ExitCounts); 13727 } 13728 13729 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13730 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13731 /// we cannot guarantee that the replacement is loop invariant in the loop of 13732 /// the AddRec. 13733 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13734 ValueToSCEVMapTy ⤅ 13735 13736 public: 13737 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13738 : SCEVRewriteVisitor(SE), Map(M) {} 13739 13740 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13741 13742 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13743 auto I = Map.find(Expr->getValue()); 13744 if (I == Map.end()) 13745 return Expr; 13746 return I->second; 13747 } 13748 }; 13749 13750 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13751 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13752 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13753 // If we have LHS == 0, check if LHS is computing a property of some unknown 13754 // SCEV %v which we can rewrite %v to express explicitly. 13755 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13756 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13757 RHSC->getValue()->isNullValue()) { 13758 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13759 // explicitly express that. 13760 const SCEV *URemLHS = nullptr; 13761 const SCEV *URemRHS = nullptr; 13762 if (matchURem(LHS, URemLHS, URemRHS)) { 13763 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13764 Value *V = LHSUnknown->getValue(); 13765 auto Multiple = 13766 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13767 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13768 RewriteMap[V] = Multiple; 13769 return; 13770 } 13771 } 13772 } 13773 13774 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13775 std::swap(LHS, RHS); 13776 Predicate = CmpInst::getSwappedPredicate(Predicate); 13777 } 13778 13779 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13780 // create this form when combining two checks of the form (X u< C2 + C1) and 13781 // (X >=u C1). 13782 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13783 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13784 if (!AddExpr || AddExpr->getNumOperands() != 2) 13785 return false; 13786 13787 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13788 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13789 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13790 if (!C1 || !C2 || !LHSUnknown) 13791 return false; 13792 13793 auto ExactRegion = 13794 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13795 .sub(C1->getAPInt()); 13796 13797 // Bail out, unless we have a non-wrapping, monotonic range. 13798 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13799 return false; 13800 auto I = RewriteMap.find(LHSUnknown->getValue()); 13801 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13802 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13803 getConstant(ExactRegion.getUnsignedMin()), 13804 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13805 return true; 13806 }; 13807 if (MatchRangeCheckIdiom()) 13808 return; 13809 13810 // For now, limit to conditions that provide information about unknown 13811 // expressions. RHS also cannot contain add recurrences. 13812 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13813 if (!LHSUnknown || containsAddRecurrence(RHS)) 13814 return; 13815 13816 // Check whether LHS has already been rewritten. In that case we want to 13817 // chain further rewrites onto the already rewritten value. 13818 auto I = RewriteMap.find(LHSUnknown->getValue()); 13819 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13820 const SCEV *RewrittenRHS = nullptr; 13821 switch (Predicate) { 13822 case CmpInst::ICMP_ULT: 13823 RewrittenRHS = 13824 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13825 break; 13826 case CmpInst::ICMP_SLT: 13827 RewrittenRHS = 13828 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13829 break; 13830 case CmpInst::ICMP_ULE: 13831 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13832 break; 13833 case CmpInst::ICMP_SLE: 13834 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13835 break; 13836 case CmpInst::ICMP_UGT: 13837 RewrittenRHS = 13838 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13839 break; 13840 case CmpInst::ICMP_SGT: 13841 RewrittenRHS = 13842 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13843 break; 13844 case CmpInst::ICMP_UGE: 13845 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13846 break; 13847 case CmpInst::ICMP_SGE: 13848 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13849 break; 13850 case CmpInst::ICMP_EQ: 13851 if (isa<SCEVConstant>(RHS)) 13852 RewrittenRHS = RHS; 13853 break; 13854 case CmpInst::ICMP_NE: 13855 if (isa<SCEVConstant>(RHS) && 13856 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13857 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13858 break; 13859 default: 13860 break; 13861 } 13862 13863 if (RewrittenRHS) 13864 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13865 }; 13866 // Starting at the loop predecessor, climb up the predecessor chain, as long 13867 // as there are predecessors that can be found that have unique successors 13868 // leading to the original header. 13869 // TODO: share this logic with isLoopEntryGuardedByCond. 13870 ValueToSCEVMapTy RewriteMap; 13871 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13872 L->getLoopPredecessor(), L->getHeader()); 13873 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13874 13875 const BranchInst *LoopEntryPredicate = 13876 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13877 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13878 continue; 13879 13880 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13881 SmallVector<Value *, 8> Worklist; 13882 SmallPtrSet<Value *, 8> Visited; 13883 Worklist.push_back(LoopEntryPredicate->getCondition()); 13884 while (!Worklist.empty()) { 13885 Value *Cond = Worklist.pop_back_val(); 13886 if (!Visited.insert(Cond).second) 13887 continue; 13888 13889 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13890 auto Predicate = 13891 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13892 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13893 getSCEV(Cmp->getOperand(1)), RewriteMap); 13894 continue; 13895 } 13896 13897 Value *L, *R; 13898 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13899 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13900 Worklist.push_back(L); 13901 Worklist.push_back(R); 13902 } 13903 } 13904 } 13905 13906 // Also collect information from assumptions dominating the loop. 13907 for (auto &AssumeVH : AC.assumptions()) { 13908 if (!AssumeVH) 13909 continue; 13910 auto *AssumeI = cast<CallInst>(AssumeVH); 13911 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13912 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13913 continue; 13914 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13915 getSCEV(Cmp->getOperand(1)), RewriteMap); 13916 } 13917 13918 if (RewriteMap.empty()) 13919 return Expr; 13920 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13921 return Rewriter.visit(Expr); 13922 } 13923