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 case scMulExpr: 390 case scUMaxExpr: 391 case scSMaxExpr: 392 case scUMinExpr: 393 case scSMinExpr: 394 return cast<SCEVNAryExpr>(this)->getType(); 395 case scAddExpr: 396 return cast<SCEVAddExpr>(this)->getType(); 397 case scUDivExpr: 398 return cast<SCEVUDivExpr>(this)->getType(); 399 case scUnknown: 400 return cast<SCEVUnknown>(this)->getType(); 401 case scCouldNotCompute: 402 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 403 } 404 llvm_unreachable("Unknown SCEV kind!"); 405 } 406 407 bool SCEV::isZero() const { 408 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 409 return SC->getValue()->isZero(); 410 return false; 411 } 412 413 bool SCEV::isOne() const { 414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 415 return SC->getValue()->isOne(); 416 return false; 417 } 418 419 bool SCEV::isAllOnesValue() const { 420 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 421 return SC->getValue()->isMinusOne(); 422 return false; 423 } 424 425 bool SCEV::isNonConstantNegative() const { 426 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 427 if (!Mul) return false; 428 429 // If there is a constant factor, it will be first. 430 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 431 if (!SC) return false; 432 433 // Return true if the value is negative, this matches things like (-42 * V). 434 return SC->getAPInt().isNegative(); 435 } 436 437 SCEVCouldNotCompute::SCEVCouldNotCompute() : 438 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 439 440 bool SCEVCouldNotCompute::classof(const SCEV *S) { 441 return S->getSCEVType() == scCouldNotCompute; 442 } 443 444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 445 FoldingSetNodeID ID; 446 ID.AddInteger(scConstant); 447 ID.AddPointer(V); 448 void *IP = nullptr; 449 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 450 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 451 UniqueSCEVs.InsertNode(S, IP); 452 return S; 453 } 454 455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 456 return getConstant(ConstantInt::get(getContext(), Val)); 457 } 458 459 const SCEV * 460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 461 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 462 return getConstant(ConstantInt::get(ITy, V, isSigned)); 463 } 464 465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 466 const SCEV *op, Type *ty) 467 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 468 Operands[0] = op; 469 } 470 471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 472 Type *ITy) 473 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 474 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 475 "Must be a non-bit-width-changing pointer-to-integer cast!"); 476 } 477 478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 479 SCEVTypes SCEVTy, const SCEV *op, 480 Type *ty) 481 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 482 483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 484 Type *ty) 485 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 486 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 487 "Cannot truncate non-integer value!"); 488 } 489 490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 491 const SCEV *op, Type *ty) 492 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 493 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 494 "Cannot zero extend non-integer value!"); 495 } 496 497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 498 const SCEV *op, Type *ty) 499 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 500 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 501 "Cannot sign extend non-integer value!"); 502 } 503 504 void SCEVUnknown::deleted() { 505 // Clear this SCEVUnknown from various maps. 506 SE->forgetMemoizedResults(this); 507 508 // Remove this SCEVUnknown from the uniquing map. 509 SE->UniqueSCEVs.RemoveNode(this); 510 511 // Release the value. 512 setValPtr(nullptr); 513 } 514 515 void SCEVUnknown::allUsesReplacedWith(Value *New) { 516 // Remove this SCEVUnknown from the uniquing map. 517 SE->UniqueSCEVs.RemoveNode(this); 518 519 // Update this SCEVUnknown to point to the new value. This is needed 520 // because there may still be outstanding SCEVs which still point to 521 // this SCEVUnknown. 522 setValPtr(New); 523 } 524 525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 526 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 527 if (VCE->getOpcode() == Instruction::PtrToInt) 528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 529 if (CE->getOpcode() == Instruction::GetElementPtr && 530 CE->getOperand(0)->isNullValue() && 531 CE->getNumOperands() == 2) 532 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 533 if (CI->isOne()) { 534 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 535 ->getElementType(); 536 return true; 537 } 538 539 return false; 540 } 541 542 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 543 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 544 if (VCE->getOpcode() == Instruction::PtrToInt) 545 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 546 if (CE->getOpcode() == Instruction::GetElementPtr && 547 CE->getOperand(0)->isNullValue()) { 548 Type *Ty = 549 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 550 if (StructType *STy = dyn_cast<StructType>(Ty)) 551 if (!STy->isPacked() && 552 CE->getNumOperands() == 3 && 553 CE->getOperand(1)->isNullValue()) { 554 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 555 if (CI->isOne() && 556 STy->getNumElements() == 2 && 557 STy->getElementType(0)->isIntegerTy(1)) { 558 AllocTy = STy->getElementType(1); 559 return true; 560 } 561 } 562 } 563 564 return false; 565 } 566 567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 568 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 569 if (VCE->getOpcode() == Instruction::PtrToInt) 570 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 571 if (CE->getOpcode() == Instruction::GetElementPtr && 572 CE->getNumOperands() == 3 && 573 CE->getOperand(0)->isNullValue() && 574 CE->getOperand(1)->isNullValue()) { 575 Type *Ty = 576 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 577 // Ignore vector types here so that ScalarEvolutionExpander doesn't 578 // emit getelementptrs that index into vectors. 579 if (Ty->isStructTy() || Ty->isArrayTy()) { 580 CTy = Ty; 581 FieldNo = CE->getOperand(2); 582 return true; 583 } 584 } 585 586 return false; 587 } 588 589 //===----------------------------------------------------------------------===// 590 // SCEV Utilities 591 //===----------------------------------------------------------------------===// 592 593 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 594 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 595 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 596 /// have been previously deemed to be "equally complex" by this routine. It is 597 /// intended to avoid exponential time complexity in cases like: 598 /// 599 /// %a = f(%x, %y) 600 /// %b = f(%a, %a) 601 /// %c = f(%b, %b) 602 /// 603 /// %d = f(%x, %y) 604 /// %e = f(%d, %d) 605 /// %f = f(%e, %e) 606 /// 607 /// CompareValueComplexity(%f, %c) 608 /// 609 /// Since we do not continue running this routine on expression trees once we 610 /// have seen unequal values, there is no need to track them in the cache. 611 static int 612 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 613 const LoopInfo *const LI, Value *LV, Value *RV, 614 unsigned Depth) { 615 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 616 return 0; 617 618 // Order pointer values after integer values. This helps SCEVExpander form 619 // GEPs. 620 bool LIsPointer = LV->getType()->isPointerTy(), 621 RIsPointer = RV->getType()->isPointerTy(); 622 if (LIsPointer != RIsPointer) 623 return (int)LIsPointer - (int)RIsPointer; 624 625 // Compare getValueID values. 626 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 627 if (LID != RID) 628 return (int)LID - (int)RID; 629 630 // Sort arguments by their position. 631 if (const auto *LA = dyn_cast<Argument>(LV)) { 632 const auto *RA = cast<Argument>(RV); 633 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 634 return (int)LArgNo - (int)RArgNo; 635 } 636 637 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 638 const auto *RGV = cast<GlobalValue>(RV); 639 640 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 641 auto LT = GV->getLinkage(); 642 return !(GlobalValue::isPrivateLinkage(LT) || 643 GlobalValue::isInternalLinkage(LT)); 644 }; 645 646 // Use the names to distinguish the two values, but only if the 647 // names are semantically important. 648 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 649 return LGV->getName().compare(RGV->getName()); 650 } 651 652 // For instructions, compare their loop depth, and their operand count. This 653 // is pretty loose. 654 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 655 const auto *RInst = cast<Instruction>(RV); 656 657 // Compare loop depths. 658 const BasicBlock *LParent = LInst->getParent(), 659 *RParent = RInst->getParent(); 660 if (LParent != RParent) { 661 unsigned LDepth = LI->getLoopDepth(LParent), 662 RDepth = LI->getLoopDepth(RParent); 663 if (LDepth != RDepth) 664 return (int)LDepth - (int)RDepth; 665 } 666 667 // Compare the number of operands. 668 unsigned LNumOps = LInst->getNumOperands(), 669 RNumOps = RInst->getNumOperands(); 670 if (LNumOps != RNumOps) 671 return (int)LNumOps - (int)RNumOps; 672 673 for (unsigned Idx : seq(0u, LNumOps)) { 674 int Result = 675 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 676 RInst->getOperand(Idx), Depth + 1); 677 if (Result != 0) 678 return Result; 679 } 680 } 681 682 EqCacheValue.unionSets(LV, RV); 683 return 0; 684 } 685 686 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 687 // than RHS, respectively. A three-way result allows recursive comparisons to be 688 // more efficient. 689 // If the max analysis depth was reached, return None, assuming we do not know 690 // if they are equivalent for sure. 691 static Optional<int> 692 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 693 EquivalenceClasses<const Value *> &EqCacheValue, 694 const LoopInfo *const LI, const SCEV *LHS, 695 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 696 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 697 if (LHS == RHS) 698 return 0; 699 700 // Primarily, sort the SCEVs by their getSCEVType(). 701 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 702 if (LType != RType) 703 return (int)LType - (int)RType; 704 705 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 706 return 0; 707 708 if (Depth > MaxSCEVCompareDepth) 709 return None; 710 711 // Aside from the getSCEVType() ordering, the particular ordering 712 // isn't very important except that it's beneficial to be consistent, 713 // so that (a + b) and (b + a) don't end up as different expressions. 714 switch (LType) { 715 case scUnknown: { 716 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 717 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 718 719 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 720 RU->getValue(), Depth + 1); 721 if (X == 0) 722 EqCacheSCEV.unionSets(LHS, RHS); 723 return X; 724 } 725 726 case scConstant: { 727 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 728 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 729 730 // Compare constant values. 731 const APInt &LA = LC->getAPInt(); 732 const APInt &RA = RC->getAPInt(); 733 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 734 if (LBitWidth != RBitWidth) 735 return (int)LBitWidth - (int)RBitWidth; 736 return LA.ult(RA) ? -1 : 1; 737 } 738 739 case scAddRecExpr: { 740 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 741 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 742 743 // There is always a dominance between two recs that are used by one SCEV, 744 // so we can safely sort recs by loop header dominance. We require such 745 // order in getAddExpr. 746 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 747 if (LLoop != RLoop) { 748 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 749 assert(LHead != RHead && "Two loops share the same header?"); 750 if (DT.dominates(LHead, RHead)) 751 return 1; 752 else 753 assert(DT.dominates(RHead, LHead) && 754 "No dominance between recurrences used by one SCEV?"); 755 return -1; 756 } 757 758 // Addrec complexity grows with operand count. 759 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 760 if (LNumOps != RNumOps) 761 return (int)LNumOps - (int)RNumOps; 762 763 // Lexicographically compare. 764 for (unsigned i = 0; i != LNumOps; ++i) { 765 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 766 LA->getOperand(i), RA->getOperand(i), DT, 767 Depth + 1); 768 if (X != 0) 769 return X; 770 } 771 EqCacheSCEV.unionSets(LHS, RHS); 772 return 0; 773 } 774 775 case scAddExpr: 776 case scMulExpr: 777 case scSMaxExpr: 778 case scUMaxExpr: 779 case scSMinExpr: 780 case scUMinExpr: { 781 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 782 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 783 784 // Lexicographically compare n-ary expressions. 785 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 786 if (LNumOps != RNumOps) 787 return (int)LNumOps - (int)RNumOps; 788 789 for (unsigned i = 0; i != LNumOps; ++i) { 790 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 791 LC->getOperand(i), RC->getOperand(i), DT, 792 Depth + 1); 793 if (X != 0) 794 return X; 795 } 796 EqCacheSCEV.unionSets(LHS, RHS); 797 return 0; 798 } 799 800 case scUDivExpr: { 801 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 802 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 803 804 // Lexicographically compare udiv expressions. 805 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 806 RC->getLHS(), DT, Depth + 1); 807 if (X != 0) 808 return X; 809 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 810 RC->getRHS(), DT, Depth + 1); 811 if (X == 0) 812 EqCacheSCEV.unionSets(LHS, RHS); 813 return X; 814 } 815 816 case scPtrToInt: 817 case scTruncate: 818 case scZeroExtend: 819 case scSignExtend: { 820 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 821 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 822 823 // Compare cast expressions by operand. 824 auto X = 825 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 826 RC->getOperand(), DT, Depth + 1); 827 if (X == 0) 828 EqCacheSCEV.unionSets(LHS, RHS); 829 return X; 830 } 831 832 case scCouldNotCompute: 833 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 834 } 835 llvm_unreachable("Unknown SCEV kind!"); 836 } 837 838 /// Given a list of SCEV objects, order them by their complexity, and group 839 /// objects of the same complexity together by value. When this routine is 840 /// finished, we know that any duplicates in the vector are consecutive and that 841 /// complexity is monotonically increasing. 842 /// 843 /// Note that we go take special precautions to ensure that we get deterministic 844 /// results from this routine. In other words, we don't want the results of 845 /// this to depend on where the addresses of various SCEV objects happened to 846 /// land in memory. 847 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 848 LoopInfo *LI, DominatorTree &DT) { 849 if (Ops.size() < 2) return; // Noop 850 851 EquivalenceClasses<const SCEV *> EqCacheSCEV; 852 EquivalenceClasses<const Value *> EqCacheValue; 853 854 // Whether LHS has provably less complexity than RHS. 855 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 856 auto Complexity = 857 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 858 return Complexity && *Complexity < 0; 859 }; 860 if (Ops.size() == 2) { 861 // This is the common case, which also happens to be trivially simple. 862 // Special case it. 863 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 864 if (IsLessComplex(RHS, LHS)) 865 std::swap(LHS, RHS); 866 return; 867 } 868 869 // Do the rough sort by complexity. 870 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 871 return IsLessComplex(LHS, RHS); 872 }); 873 874 // Now that we are sorted by complexity, group elements of the same 875 // complexity. Note that this is, at worst, N^2, but the vector is likely to 876 // be extremely short in practice. Note that we take this approach because we 877 // do not want to depend on the addresses of the objects we are grouping. 878 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 879 const SCEV *S = Ops[i]; 880 unsigned Complexity = S->getSCEVType(); 881 882 // If there are any objects of the same complexity and same value as this 883 // one, group them. 884 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 885 if (Ops[j] == S) { // Found a duplicate. 886 // Move it to immediately after i'th element. 887 std::swap(Ops[i+1], Ops[j]); 888 ++i; // no need to rescan it. 889 if (i == e-2) return; // Done! 890 } 891 } 892 } 893 } 894 895 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 896 /// least HugeExprThreshold nodes). 897 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 898 return any_of(Ops, [](const SCEV *S) { 899 return S->getExpressionSize() >= HugeExprThreshold; 900 }); 901 } 902 903 //===----------------------------------------------------------------------===// 904 // Simple SCEV method implementations 905 //===----------------------------------------------------------------------===// 906 907 /// Compute BC(It, K). The result has width W. Assume, K > 0. 908 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 909 ScalarEvolution &SE, 910 Type *ResultTy) { 911 // Handle the simplest case efficiently. 912 if (K == 1) 913 return SE.getTruncateOrZeroExtend(It, ResultTy); 914 915 // We are using the following formula for BC(It, K): 916 // 917 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 918 // 919 // Suppose, W is the bitwidth of the return value. We must be prepared for 920 // overflow. Hence, we must assure that the result of our computation is 921 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 922 // safe in modular arithmetic. 923 // 924 // However, this code doesn't use exactly that formula; the formula it uses 925 // is something like the following, where T is the number of factors of 2 in 926 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 927 // exponentiation: 928 // 929 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 930 // 931 // This formula is trivially equivalent to the previous formula. However, 932 // this formula can be implemented much more efficiently. The trick is that 933 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 934 // arithmetic. To do exact division in modular arithmetic, all we have 935 // to do is multiply by the inverse. Therefore, this step can be done at 936 // width W. 937 // 938 // The next issue is how to safely do the division by 2^T. The way this 939 // is done is by doing the multiplication step at a width of at least W + T 940 // bits. This way, the bottom W+T bits of the product are accurate. Then, 941 // when we perform the division by 2^T (which is equivalent to a right shift 942 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 943 // truncated out after the division by 2^T. 944 // 945 // In comparison to just directly using the first formula, this technique 946 // is much more efficient; using the first formula requires W * K bits, 947 // but this formula less than W + K bits. Also, the first formula requires 948 // a division step, whereas this formula only requires multiplies and shifts. 949 // 950 // It doesn't matter whether the subtraction step is done in the calculation 951 // width or the input iteration count's width; if the subtraction overflows, 952 // the result must be zero anyway. We prefer here to do it in the width of 953 // the induction variable because it helps a lot for certain cases; CodeGen 954 // isn't smart enough to ignore the overflow, which leads to much less 955 // efficient code if the width of the subtraction is wider than the native 956 // register width. 957 // 958 // (It's possible to not widen at all by pulling out factors of 2 before 959 // the multiplication; for example, K=2 can be calculated as 960 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 961 // extra arithmetic, so it's not an obvious win, and it gets 962 // much more complicated for K > 3.) 963 964 // Protection from insane SCEVs; this bound is conservative, 965 // but it probably doesn't matter. 966 if (K > 1000) 967 return SE.getCouldNotCompute(); 968 969 unsigned W = SE.getTypeSizeInBits(ResultTy); 970 971 // Calculate K! / 2^T and T; we divide out the factors of two before 972 // multiplying for calculating K! / 2^T to avoid overflow. 973 // Other overflow doesn't matter because we only care about the bottom 974 // W bits of the result. 975 APInt OddFactorial(W, 1); 976 unsigned T = 1; 977 for (unsigned i = 3; i <= K; ++i) { 978 APInt Mult(W, i); 979 unsigned TwoFactors = Mult.countTrailingZeros(); 980 T += TwoFactors; 981 Mult.lshrInPlace(TwoFactors); 982 OddFactorial *= Mult; 983 } 984 985 // We need at least W + T bits for the multiplication step 986 unsigned CalculationBits = W + T; 987 988 // Calculate 2^T, at width T+W. 989 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 990 991 // Calculate the multiplicative inverse of K! / 2^T; 992 // this multiplication factor will perform the exact division by 993 // K! / 2^T. 994 APInt Mod = APInt::getSignedMinValue(W+1); 995 APInt MultiplyFactor = OddFactorial.zext(W+1); 996 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 997 MultiplyFactor = MultiplyFactor.trunc(W); 998 999 // Calculate the product, at width T+W 1000 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1001 CalculationBits); 1002 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1003 for (unsigned i = 1; i != K; ++i) { 1004 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1005 Dividend = SE.getMulExpr(Dividend, 1006 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1007 } 1008 1009 // Divide by 2^T 1010 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1011 1012 // Truncate the result, and divide by K! / 2^T. 1013 1014 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1015 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1016 } 1017 1018 /// Return the value of this chain of recurrences at the specified iteration 1019 /// number. We can evaluate this recurrence by multiplying each element in the 1020 /// chain by the binomial coefficient corresponding to it. In other words, we 1021 /// can evaluate {A,+,B,+,C,+,D} as: 1022 /// 1023 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1024 /// 1025 /// where BC(It, k) stands for binomial coefficient. 1026 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1027 ScalarEvolution &SE) const { 1028 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1029 } 1030 1031 const SCEV * 1032 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1033 const SCEV *It, ScalarEvolution &SE) { 1034 assert(Operands.size() > 0); 1035 const SCEV *Result = Operands[0]; 1036 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1037 // The computation is correct in the face of overflow provided that the 1038 // multiplication is performed _after_ the evaluation of the binomial 1039 // coefficient. 1040 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1041 if (isa<SCEVCouldNotCompute>(Coeff)) 1042 return Coeff; 1043 1044 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1045 } 1046 return Result; 1047 } 1048 1049 //===----------------------------------------------------------------------===// 1050 // SCEV Expression folder implementations 1051 //===----------------------------------------------------------------------===// 1052 1053 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1054 unsigned Depth) { 1055 assert(Depth <= 1 && 1056 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1057 1058 // We could be called with an integer-typed operands during SCEV rewrites. 1059 // Since the operand is an integer already, just perform zext/trunc/self cast. 1060 if (!Op->getType()->isPointerTy()) 1061 return Op; 1062 1063 assert(!getDataLayout().isNonIntegralPointerType(Op->getType()) && 1064 "Source pointer type must be integral for ptrtoint!"); 1065 1066 // What would be an ID for such a SCEV cast expression? 1067 FoldingSetNodeID ID; 1068 ID.AddInteger(scPtrToInt); 1069 ID.AddPointer(Op); 1070 1071 void *IP = nullptr; 1072 1073 // Is there already an expression for such a cast? 1074 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1075 return S; 1076 1077 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1078 1079 // We can only model ptrtoint if SCEV's effective (integer) type 1080 // is sufficiently wide to represent all possible pointer values. 1081 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1082 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1083 return getCouldNotCompute(); 1084 1085 // If not, is this expression something we can't reduce any further? 1086 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1087 // Perform some basic constant folding. If the operand of the ptr2int cast 1088 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1089 // left as-is), but produce a zero constant. 1090 // NOTE: We could handle a more general case, but lack motivational cases. 1091 if (isa<ConstantPointerNull>(U->getValue())) 1092 return getZero(IntPtrTy); 1093 1094 // Create an explicit cast node. 1095 // We can reuse the existing insert position since if we get here, 1096 // we won't have made any changes which would invalidate it. 1097 SCEV *S = new (SCEVAllocator) 1098 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1099 UniqueSCEVs.InsertNode(S, IP); 1100 addToLoopUseLists(S); 1101 return S; 1102 } 1103 1104 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1105 "non-SCEVUnknown's."); 1106 1107 // Otherwise, we've got some expression that is more complex than just a 1108 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1109 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1110 // only, and the expressions must otherwise be integer-typed. 1111 // So sink the cast down to the SCEVUnknown's. 1112 1113 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1114 /// which computes a pointer-typed value, and rewrites the whole expression 1115 /// tree so that *all* the computations are done on integers, and the only 1116 /// pointer-typed operands in the expression are SCEVUnknown. 1117 class SCEVPtrToIntSinkingRewriter 1118 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1119 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1120 1121 public: 1122 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1123 1124 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1125 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1126 return Rewriter.visit(Scev); 1127 } 1128 1129 const SCEV *visit(const SCEV *S) { 1130 Type *STy = S->getType(); 1131 // If the expression is not pointer-typed, just keep it as-is. 1132 if (!STy->isPointerTy()) 1133 return S; 1134 // Else, recursively sink the cast down into it. 1135 return Base::visit(S); 1136 } 1137 1138 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1139 SmallVector<const SCEV *, 2> Operands; 1140 bool Changed = false; 1141 for (auto *Op : Expr->operands()) { 1142 Operands.push_back(visit(Op)); 1143 Changed |= Op != Operands.back(); 1144 } 1145 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1146 } 1147 1148 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1149 SmallVector<const SCEV *, 2> Operands; 1150 bool Changed = false; 1151 for (auto *Op : Expr->operands()) { 1152 Operands.push_back(visit(Op)); 1153 Changed |= Op != Operands.back(); 1154 } 1155 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1156 } 1157 1158 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1159 assert(Expr->getType()->isPointerTy() && 1160 "Should only reach pointer-typed SCEVUnknown's."); 1161 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1162 } 1163 }; 1164 1165 // And actually perform the cast sinking. 1166 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1167 assert(IntOp->getType()->isIntegerTy() && 1168 "We must have succeeded in sinking the cast, " 1169 "and ending up with an integer-typed expression!"); 1170 return IntOp; 1171 } 1172 1173 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1174 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1175 1176 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1177 if (isa<SCEVCouldNotCompute>(IntOp)) 1178 return IntOp; 1179 1180 return getTruncateOrZeroExtend(IntOp, Ty); 1181 } 1182 1183 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1184 unsigned Depth) { 1185 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1186 "This is not a truncating conversion!"); 1187 assert(isSCEVable(Ty) && 1188 "This is not a conversion to a SCEVable type!"); 1189 Ty = getEffectiveSCEVType(Ty); 1190 1191 FoldingSetNodeID ID; 1192 ID.AddInteger(scTruncate); 1193 ID.AddPointer(Op); 1194 ID.AddPointer(Ty); 1195 void *IP = nullptr; 1196 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1197 1198 // Fold if the operand is constant. 1199 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1200 return getConstant( 1201 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1202 1203 // trunc(trunc(x)) --> trunc(x) 1204 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1205 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1206 1207 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1208 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1209 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1210 1211 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1212 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1213 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1214 1215 if (Depth > MaxCastDepth) { 1216 SCEV *S = 1217 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1218 UniqueSCEVs.InsertNode(S, IP); 1219 addToLoopUseLists(S); 1220 return S; 1221 } 1222 1223 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1224 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1225 // if after transforming we have at most one truncate, not counting truncates 1226 // that replace other casts. 1227 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1228 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1229 SmallVector<const SCEV *, 4> Operands; 1230 unsigned numTruncs = 0; 1231 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1232 ++i) { 1233 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1234 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1235 isa<SCEVTruncateExpr>(S)) 1236 numTruncs++; 1237 Operands.push_back(S); 1238 } 1239 if (numTruncs < 2) { 1240 if (isa<SCEVAddExpr>(Op)) 1241 return getAddExpr(Operands); 1242 else if (isa<SCEVMulExpr>(Op)) 1243 return getMulExpr(Operands); 1244 else 1245 llvm_unreachable("Unexpected SCEV type for Op."); 1246 } 1247 // Although we checked in the beginning that ID is not in the cache, it is 1248 // possible that during recursion and different modification ID was inserted 1249 // into the cache. So if we find it, just return it. 1250 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1251 return S; 1252 } 1253 1254 // If the input value is a chrec scev, truncate the chrec's operands. 1255 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1256 SmallVector<const SCEV *, 4> Operands; 1257 for (const SCEV *Op : AddRec->operands()) 1258 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1259 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1260 } 1261 1262 // Return zero if truncating to known zeros. 1263 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1264 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1265 return getZero(Ty); 1266 1267 // The cast wasn't folded; create an explicit cast node. We can reuse 1268 // the existing insert position since if we get here, we won't have 1269 // made any changes which would invalidate it. 1270 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1271 Op, Ty); 1272 UniqueSCEVs.InsertNode(S, IP); 1273 addToLoopUseLists(S); 1274 return S; 1275 } 1276 1277 // Get the limit of a recurrence such that incrementing by Step cannot cause 1278 // signed overflow as long as the value of the recurrence within the 1279 // loop does not exceed this limit before incrementing. 1280 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1281 ICmpInst::Predicate *Pred, 1282 ScalarEvolution *SE) { 1283 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1284 if (SE->isKnownPositive(Step)) { 1285 *Pred = ICmpInst::ICMP_SLT; 1286 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1287 SE->getSignedRangeMax(Step)); 1288 } 1289 if (SE->isKnownNegative(Step)) { 1290 *Pred = ICmpInst::ICMP_SGT; 1291 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1292 SE->getSignedRangeMin(Step)); 1293 } 1294 return nullptr; 1295 } 1296 1297 // Get the limit of a recurrence such that incrementing by Step cannot cause 1298 // unsigned overflow as long as the value of the recurrence within the loop does 1299 // not exceed this limit before incrementing. 1300 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1301 ICmpInst::Predicate *Pred, 1302 ScalarEvolution *SE) { 1303 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1304 *Pred = ICmpInst::ICMP_ULT; 1305 1306 return SE->getConstant(APInt::getMinValue(BitWidth) - 1307 SE->getUnsignedRangeMax(Step)); 1308 } 1309 1310 namespace { 1311 1312 struct ExtendOpTraitsBase { 1313 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1314 unsigned); 1315 }; 1316 1317 // Used to make code generic over signed and unsigned overflow. 1318 template <typename ExtendOp> struct ExtendOpTraits { 1319 // Members present: 1320 // 1321 // static const SCEV::NoWrapFlags WrapType; 1322 // 1323 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1324 // 1325 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1326 // ICmpInst::Predicate *Pred, 1327 // ScalarEvolution *SE); 1328 }; 1329 1330 template <> 1331 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1332 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1333 1334 static const GetExtendExprTy GetExtendExpr; 1335 1336 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1337 ICmpInst::Predicate *Pred, 1338 ScalarEvolution *SE) { 1339 return getSignedOverflowLimitForStep(Step, Pred, SE); 1340 } 1341 }; 1342 1343 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1344 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1345 1346 template <> 1347 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1348 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1349 1350 static const GetExtendExprTy GetExtendExpr; 1351 1352 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1353 ICmpInst::Predicate *Pred, 1354 ScalarEvolution *SE) { 1355 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1356 } 1357 }; 1358 1359 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1360 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1361 1362 } // end anonymous namespace 1363 1364 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1365 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1366 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1367 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1368 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1369 // expression "Step + sext/zext(PreIncAR)" is congruent with 1370 // "sext/zext(PostIncAR)" 1371 template <typename ExtendOpTy> 1372 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1373 ScalarEvolution *SE, unsigned Depth) { 1374 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1375 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1376 1377 const Loop *L = AR->getLoop(); 1378 const SCEV *Start = AR->getStart(); 1379 const SCEV *Step = AR->getStepRecurrence(*SE); 1380 1381 // Check for a simple looking step prior to loop entry. 1382 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1383 if (!SA) 1384 return nullptr; 1385 1386 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1387 // subtraction is expensive. For this purpose, perform a quick and dirty 1388 // difference, by checking for Step in the operand list. 1389 SmallVector<const SCEV *, 4> DiffOps; 1390 for (const SCEV *Op : SA->operands()) 1391 if (Op != Step) 1392 DiffOps.push_back(Op); 1393 1394 if (DiffOps.size() == SA->getNumOperands()) 1395 return nullptr; 1396 1397 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1398 // `Step`: 1399 1400 // 1. NSW/NUW flags on the step increment. 1401 auto PreStartFlags = 1402 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1403 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1404 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1405 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1406 1407 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1408 // "S+X does not sign/unsign-overflow". 1409 // 1410 1411 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1412 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1413 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1414 return PreStart; 1415 1416 // 2. Direct overflow check on the step operation's expression. 1417 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1418 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1419 const SCEV *OperandExtendedStart = 1420 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1421 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1422 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1423 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1424 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1425 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1426 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1427 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1428 } 1429 return PreStart; 1430 } 1431 1432 // 3. Loop precondition. 1433 ICmpInst::Predicate Pred; 1434 const SCEV *OverflowLimit = 1435 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1436 1437 if (OverflowLimit && 1438 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1439 return PreStart; 1440 1441 return nullptr; 1442 } 1443 1444 // Get the normalized zero or sign extended expression for this AddRec's Start. 1445 template <typename ExtendOpTy> 1446 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1447 ScalarEvolution *SE, 1448 unsigned Depth) { 1449 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1450 1451 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1452 if (!PreStart) 1453 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1454 1455 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1456 Depth), 1457 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1458 } 1459 1460 // Try to prove away overflow by looking at "nearby" add recurrences. A 1461 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1462 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1463 // 1464 // Formally: 1465 // 1466 // {S,+,X} == {S-T,+,X} + T 1467 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1468 // 1469 // If ({S-T,+,X} + T) does not overflow ... (1) 1470 // 1471 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1472 // 1473 // If {S-T,+,X} does not overflow ... (2) 1474 // 1475 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1476 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1477 // 1478 // If (S-T)+T does not overflow ... (3) 1479 // 1480 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1481 // == {Ext(S),+,Ext(X)} == LHS 1482 // 1483 // Thus, if (1), (2) and (3) are true for some T, then 1484 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1485 // 1486 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1487 // does not overflow" restricted to the 0th iteration. Therefore we only need 1488 // to check for (1) and (2). 1489 // 1490 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1491 // is `Delta` (defined below). 1492 template <typename ExtendOpTy> 1493 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1494 const SCEV *Step, 1495 const Loop *L) { 1496 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1497 1498 // We restrict `Start` to a constant to prevent SCEV from spending too much 1499 // time here. It is correct (but more expensive) to continue with a 1500 // non-constant `Start` and do a general SCEV subtraction to compute 1501 // `PreStart` below. 1502 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1503 if (!StartC) 1504 return false; 1505 1506 APInt StartAI = StartC->getAPInt(); 1507 1508 for (unsigned Delta : {-2, -1, 1, 2}) { 1509 const SCEV *PreStart = getConstant(StartAI - Delta); 1510 1511 FoldingSetNodeID ID; 1512 ID.AddInteger(scAddRecExpr); 1513 ID.AddPointer(PreStart); 1514 ID.AddPointer(Step); 1515 ID.AddPointer(L); 1516 void *IP = nullptr; 1517 const auto *PreAR = 1518 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1519 1520 // Give up if we don't already have the add recurrence we need because 1521 // actually constructing an add recurrence is relatively expensive. 1522 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1523 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1524 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1525 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1526 DeltaS, &Pred, this); 1527 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1528 return true; 1529 } 1530 } 1531 1532 return false; 1533 } 1534 1535 // Finds an integer D for an expression (C + x + y + ...) such that the top 1536 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1537 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1538 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1539 // the (C + x + y + ...) expression is \p WholeAddExpr. 1540 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1541 const SCEVConstant *ConstantTerm, 1542 const SCEVAddExpr *WholeAddExpr) { 1543 const APInt &C = ConstantTerm->getAPInt(); 1544 const unsigned BitWidth = C.getBitWidth(); 1545 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1546 uint32_t TZ = BitWidth; 1547 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1548 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1549 if (TZ) { 1550 // Set D to be as many least significant bits of C as possible while still 1551 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1552 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1553 } 1554 return APInt(BitWidth, 0); 1555 } 1556 1557 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1558 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1559 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1560 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1561 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1562 const APInt &ConstantStart, 1563 const SCEV *Step) { 1564 const unsigned BitWidth = ConstantStart.getBitWidth(); 1565 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1566 if (TZ) 1567 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1568 : ConstantStart; 1569 return APInt(BitWidth, 0); 1570 } 1571 1572 const SCEV * 1573 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1574 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1575 "This is not an extending conversion!"); 1576 assert(isSCEVable(Ty) && 1577 "This is not a conversion to a SCEVable type!"); 1578 Ty = getEffectiveSCEVType(Ty); 1579 1580 // Fold if the operand is constant. 1581 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1582 return getConstant( 1583 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1584 1585 // zext(zext(x)) --> zext(x) 1586 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1587 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1588 1589 // Before doing any expensive analysis, check to see if we've already 1590 // computed a SCEV for this Op and Ty. 1591 FoldingSetNodeID ID; 1592 ID.AddInteger(scZeroExtend); 1593 ID.AddPointer(Op); 1594 ID.AddPointer(Ty); 1595 void *IP = nullptr; 1596 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1597 if (Depth > MaxCastDepth) { 1598 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1599 Op, Ty); 1600 UniqueSCEVs.InsertNode(S, IP); 1601 addToLoopUseLists(S); 1602 return S; 1603 } 1604 1605 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1606 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1607 // It's possible the bits taken off by the truncate were all zero bits. If 1608 // so, we should be able to simplify this further. 1609 const SCEV *X = ST->getOperand(); 1610 ConstantRange CR = getUnsignedRange(X); 1611 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1612 unsigned NewBits = getTypeSizeInBits(Ty); 1613 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1614 CR.zextOrTrunc(NewBits))) 1615 return getTruncateOrZeroExtend(X, Ty, Depth); 1616 } 1617 1618 // If the input value is a chrec scev, and we can prove that the value 1619 // did not overflow the old, smaller, value, we can zero extend all of the 1620 // operands (often constants). This allows analysis of something like 1621 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1622 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1623 if (AR->isAffine()) { 1624 const SCEV *Start = AR->getStart(); 1625 const SCEV *Step = AR->getStepRecurrence(*this); 1626 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1627 const Loop *L = AR->getLoop(); 1628 1629 if (!AR->hasNoUnsignedWrap()) { 1630 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1631 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1632 } 1633 1634 // If we have special knowledge that this addrec won't overflow, 1635 // we don't need to do any further analysis. 1636 if (AR->hasNoUnsignedWrap()) 1637 return getAddRecExpr( 1638 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1639 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1640 1641 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1642 // Note that this serves two purposes: It filters out loops that are 1643 // simply not analyzable, and it covers the case where this code is 1644 // being called from within backedge-taken count analysis, such that 1645 // attempting to ask for the backedge-taken count would likely result 1646 // in infinite recursion. In the later case, the analysis code will 1647 // cope with a conservative value, and it will take care to purge 1648 // that value once it has finished. 1649 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1650 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1651 // Manually compute the final value for AR, checking for overflow. 1652 1653 // Check whether the backedge-taken count can be losslessly casted to 1654 // the addrec's type. The count is always unsigned. 1655 const SCEV *CastedMaxBECount = 1656 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1657 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1658 CastedMaxBECount, MaxBECount->getType(), Depth); 1659 if (MaxBECount == RecastedMaxBECount) { 1660 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1661 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1662 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1663 SCEV::FlagAnyWrap, Depth + 1); 1664 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1665 SCEV::FlagAnyWrap, 1666 Depth + 1), 1667 WideTy, Depth + 1); 1668 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1669 const SCEV *WideMaxBECount = 1670 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1671 const SCEV *OperandExtendedAdd = 1672 getAddExpr(WideStart, 1673 getMulExpr(WideMaxBECount, 1674 getZeroExtendExpr(Step, WideTy, Depth + 1), 1675 SCEV::FlagAnyWrap, Depth + 1), 1676 SCEV::FlagAnyWrap, Depth + 1); 1677 if (ZAdd == OperandExtendedAdd) { 1678 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1679 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1680 // Return the expression with the addrec on the outside. 1681 return getAddRecExpr( 1682 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1683 Depth + 1), 1684 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1685 AR->getNoWrapFlags()); 1686 } 1687 // Similar to above, only this time treat the step value as signed. 1688 // This covers loops that count down. 1689 OperandExtendedAdd = 1690 getAddExpr(WideStart, 1691 getMulExpr(WideMaxBECount, 1692 getSignExtendExpr(Step, WideTy, Depth + 1), 1693 SCEV::FlagAnyWrap, Depth + 1), 1694 SCEV::FlagAnyWrap, Depth + 1); 1695 if (ZAdd == OperandExtendedAdd) { 1696 // Cache knowledge of AR NW, which is propagated to this AddRec. 1697 // Negative step causes unsigned wrap, but it still can't self-wrap. 1698 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1699 // Return the expression with the addrec on the outside. 1700 return getAddRecExpr( 1701 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1702 Depth + 1), 1703 getSignExtendExpr(Step, Ty, Depth + 1), L, 1704 AR->getNoWrapFlags()); 1705 } 1706 } 1707 } 1708 1709 // Normally, in the cases we can prove no-overflow via a 1710 // backedge guarding condition, we can also compute a backedge 1711 // taken count for the loop. The exceptions are assumptions and 1712 // guards present in the loop -- SCEV is not great at exploiting 1713 // these to compute max backedge taken counts, but can still use 1714 // these to prove lack of overflow. Use this fact to avoid 1715 // doing extra work that may not pay off. 1716 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1717 !AC.assumptions().empty()) { 1718 1719 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1720 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1721 if (AR->hasNoUnsignedWrap()) { 1722 // Same as nuw case above - duplicated here to avoid a compile time 1723 // issue. It's not clear that the order of checks does matter, but 1724 // it's one of two issue possible causes for a change which was 1725 // reverted. Be conservative for the moment. 1726 return getAddRecExpr( 1727 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1728 Depth + 1), 1729 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1730 AR->getNoWrapFlags()); 1731 } 1732 1733 // For a negative step, we can extend the operands iff doing so only 1734 // traverses values in the range zext([0,UINT_MAX]). 1735 if (isKnownNegative(Step)) { 1736 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1737 getSignedRangeMin(Step)); 1738 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1739 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1740 // Cache knowledge of AR NW, which is propagated to this 1741 // AddRec. Negative step causes unsigned wrap, but it 1742 // still can't self-wrap. 1743 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1744 // Return the expression with the addrec on the outside. 1745 return getAddRecExpr( 1746 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1747 Depth + 1), 1748 getSignExtendExpr(Step, Ty, Depth + 1), L, 1749 AR->getNoWrapFlags()); 1750 } 1751 } 1752 } 1753 1754 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1755 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1756 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1757 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1758 const APInt &C = SC->getAPInt(); 1759 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1760 if (D != 0) { 1761 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1762 const SCEV *SResidual = 1763 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1764 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1765 return getAddExpr(SZExtD, SZExtR, 1766 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1767 Depth + 1); 1768 } 1769 } 1770 1771 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1772 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1773 return getAddRecExpr( 1774 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1775 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1776 } 1777 } 1778 1779 // zext(A % B) --> zext(A) % zext(B) 1780 { 1781 const SCEV *LHS; 1782 const SCEV *RHS; 1783 if (matchURem(Op, LHS, RHS)) 1784 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1785 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1786 } 1787 1788 // zext(A / B) --> zext(A) / zext(B). 1789 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1790 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1791 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1792 1793 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1794 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1795 if (SA->hasNoUnsignedWrap()) { 1796 // If the addition does not unsign overflow then we can, by definition, 1797 // commute the zero extension with the addition operation. 1798 SmallVector<const SCEV *, 4> Ops; 1799 for (const auto *Op : SA->operands()) 1800 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1801 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1802 } 1803 1804 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1805 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1806 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1807 // 1808 // Often address arithmetics contain expressions like 1809 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1810 // This transformation is useful while proving that such expressions are 1811 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1812 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1813 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1814 if (D != 0) { 1815 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1816 const SCEV *SResidual = 1817 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1818 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1819 return getAddExpr(SZExtD, SZExtR, 1820 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1821 Depth + 1); 1822 } 1823 } 1824 } 1825 1826 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1827 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1828 if (SM->hasNoUnsignedWrap()) { 1829 // If the multiply does not unsign overflow then we can, by definition, 1830 // commute the zero extension with the multiply operation. 1831 SmallVector<const SCEV *, 4> Ops; 1832 for (const auto *Op : SM->operands()) 1833 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1834 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1835 } 1836 1837 // zext(2^K * (trunc X to iN)) to iM -> 1838 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1839 // 1840 // Proof: 1841 // 1842 // zext(2^K * (trunc X to iN)) to iM 1843 // = zext((trunc X to iN) << K) to iM 1844 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1845 // (because shl removes the top K bits) 1846 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1847 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1848 // 1849 if (SM->getNumOperands() == 2) 1850 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1851 if (MulLHS->getAPInt().isPowerOf2()) 1852 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1853 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1854 MulLHS->getAPInt().logBase2(); 1855 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1856 return getMulExpr( 1857 getZeroExtendExpr(MulLHS, Ty), 1858 getZeroExtendExpr( 1859 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1860 SCEV::FlagNUW, Depth + 1); 1861 } 1862 } 1863 1864 // The cast wasn't folded; create an explicit cast node. 1865 // Recompute the insert position, as it may have been invalidated. 1866 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1867 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1868 Op, Ty); 1869 UniqueSCEVs.InsertNode(S, IP); 1870 addToLoopUseLists(S); 1871 return S; 1872 } 1873 1874 const SCEV * 1875 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1876 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1877 "This is not an extending conversion!"); 1878 assert(isSCEVable(Ty) && 1879 "This is not a conversion to a SCEVable type!"); 1880 Ty = getEffectiveSCEVType(Ty); 1881 1882 // Fold if the operand is constant. 1883 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1884 return getConstant( 1885 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1886 1887 // sext(sext(x)) --> sext(x) 1888 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1889 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1890 1891 // sext(zext(x)) --> zext(x) 1892 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1893 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1894 1895 // Before doing any expensive analysis, check to see if we've already 1896 // computed a SCEV for this Op and Ty. 1897 FoldingSetNodeID ID; 1898 ID.AddInteger(scSignExtend); 1899 ID.AddPointer(Op); 1900 ID.AddPointer(Ty); 1901 void *IP = nullptr; 1902 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1903 // Limit recursion depth. 1904 if (Depth > MaxCastDepth) { 1905 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1906 Op, Ty); 1907 UniqueSCEVs.InsertNode(S, IP); 1908 addToLoopUseLists(S); 1909 return S; 1910 } 1911 1912 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1913 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1914 // It's possible the bits taken off by the truncate were all sign bits. If 1915 // so, we should be able to simplify this further. 1916 const SCEV *X = ST->getOperand(); 1917 ConstantRange CR = getSignedRange(X); 1918 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1919 unsigned NewBits = getTypeSizeInBits(Ty); 1920 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1921 CR.sextOrTrunc(NewBits))) 1922 return getTruncateOrSignExtend(X, Ty, Depth); 1923 } 1924 1925 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1926 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1927 if (SA->hasNoSignedWrap()) { 1928 // If the addition does not sign overflow then we can, by definition, 1929 // commute the sign extension with the addition operation. 1930 SmallVector<const SCEV *, 4> Ops; 1931 for (const auto *Op : SA->operands()) 1932 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1933 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1934 } 1935 1936 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1937 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1938 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1939 // 1940 // For instance, this will bring two seemingly different expressions: 1941 // 1 + sext(5 + 20 * %x + 24 * %y) and 1942 // sext(6 + 20 * %x + 24 * %y) 1943 // to the same form: 1944 // 2 + sext(4 + 20 * %x + 24 * %y) 1945 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1946 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1947 if (D != 0) { 1948 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1949 const SCEV *SResidual = 1950 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1951 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1952 return getAddExpr(SSExtD, SSExtR, 1953 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1954 Depth + 1); 1955 } 1956 } 1957 } 1958 // If the input value is a chrec scev, and we can prove that the value 1959 // did not overflow the old, smaller, value, we can sign extend all of the 1960 // operands (often constants). This allows analysis of something like 1961 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1962 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1963 if (AR->isAffine()) { 1964 const SCEV *Start = AR->getStart(); 1965 const SCEV *Step = AR->getStepRecurrence(*this); 1966 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1967 const Loop *L = AR->getLoop(); 1968 1969 if (!AR->hasNoSignedWrap()) { 1970 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1971 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1972 } 1973 1974 // If we have special knowledge that this addrec won't overflow, 1975 // we don't need to do any further analysis. 1976 if (AR->hasNoSignedWrap()) 1977 return getAddRecExpr( 1978 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1979 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1980 1981 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1982 // Note that this serves two purposes: It filters out loops that are 1983 // simply not analyzable, and it covers the case where this code is 1984 // being called from within backedge-taken count analysis, such that 1985 // attempting to ask for the backedge-taken count would likely result 1986 // in infinite recursion. In the later case, the analysis code will 1987 // cope with a conservative value, and it will take care to purge 1988 // that value once it has finished. 1989 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1990 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1991 // Manually compute the final value for AR, checking for 1992 // overflow. 1993 1994 // Check whether the backedge-taken count can be losslessly casted to 1995 // the addrec's type. The count is always unsigned. 1996 const SCEV *CastedMaxBECount = 1997 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1998 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1999 CastedMaxBECount, MaxBECount->getType(), Depth); 2000 if (MaxBECount == RecastedMaxBECount) { 2001 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2002 // Check whether Start+Step*MaxBECount has no signed overflow. 2003 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2004 SCEV::FlagAnyWrap, Depth + 1); 2005 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2006 SCEV::FlagAnyWrap, 2007 Depth + 1), 2008 WideTy, Depth + 1); 2009 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2010 const SCEV *WideMaxBECount = 2011 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2012 const SCEV *OperandExtendedAdd = 2013 getAddExpr(WideStart, 2014 getMulExpr(WideMaxBECount, 2015 getSignExtendExpr(Step, WideTy, Depth + 1), 2016 SCEV::FlagAnyWrap, Depth + 1), 2017 SCEV::FlagAnyWrap, Depth + 1); 2018 if (SAdd == OperandExtendedAdd) { 2019 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2020 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2021 // Return the expression with the addrec on the outside. 2022 return getAddRecExpr( 2023 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2024 Depth + 1), 2025 getSignExtendExpr(Step, Ty, Depth + 1), L, 2026 AR->getNoWrapFlags()); 2027 } 2028 // Similar to above, only this time treat the step value as unsigned. 2029 // This covers loops that count up with an unsigned step. 2030 OperandExtendedAdd = 2031 getAddExpr(WideStart, 2032 getMulExpr(WideMaxBECount, 2033 getZeroExtendExpr(Step, WideTy, Depth + 1), 2034 SCEV::FlagAnyWrap, Depth + 1), 2035 SCEV::FlagAnyWrap, Depth + 1); 2036 if (SAdd == OperandExtendedAdd) { 2037 // If AR wraps around then 2038 // 2039 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2040 // => SAdd != OperandExtendedAdd 2041 // 2042 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2043 // (SAdd == OperandExtendedAdd => AR is NW) 2044 2045 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2046 2047 // Return the expression with the addrec on the outside. 2048 return getAddRecExpr( 2049 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2050 Depth + 1), 2051 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2052 AR->getNoWrapFlags()); 2053 } 2054 } 2055 } 2056 2057 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2058 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2059 if (AR->hasNoSignedWrap()) { 2060 // Same as nsw case above - duplicated here to avoid a compile time 2061 // issue. It's not clear that the order of checks does matter, but 2062 // it's one of two issue possible causes for a change which was 2063 // reverted. Be conservative for the moment. 2064 return getAddRecExpr( 2065 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2066 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2067 } 2068 2069 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2070 // if D + (C - D + Step * n) could be proven to not signed wrap 2071 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2072 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2073 const APInt &C = SC->getAPInt(); 2074 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2075 if (D != 0) { 2076 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2077 const SCEV *SResidual = 2078 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2079 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2080 return getAddExpr(SSExtD, SSExtR, 2081 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2082 Depth + 1); 2083 } 2084 } 2085 2086 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2087 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2088 return getAddRecExpr( 2089 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2090 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2091 } 2092 } 2093 2094 // If the input value is provably positive and we could not simplify 2095 // away the sext build a zext instead. 2096 if (isKnownNonNegative(Op)) 2097 return getZeroExtendExpr(Op, Ty, Depth + 1); 2098 2099 // The cast wasn't folded; create an explicit cast node. 2100 // Recompute the insert position, as it may have been invalidated. 2101 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2102 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2103 Op, Ty); 2104 UniqueSCEVs.InsertNode(S, IP); 2105 addToLoopUseLists(S); 2106 return S; 2107 } 2108 2109 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2110 /// unspecified bits out to the given type. 2111 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2112 Type *Ty) { 2113 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2114 "This is not an extending conversion!"); 2115 assert(isSCEVable(Ty) && 2116 "This is not a conversion to a SCEVable type!"); 2117 Ty = getEffectiveSCEVType(Ty); 2118 2119 // Sign-extend negative constants. 2120 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2121 if (SC->getAPInt().isNegative()) 2122 return getSignExtendExpr(Op, Ty); 2123 2124 // Peel off a truncate cast. 2125 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2126 const SCEV *NewOp = T->getOperand(); 2127 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2128 return getAnyExtendExpr(NewOp, Ty); 2129 return getTruncateOrNoop(NewOp, Ty); 2130 } 2131 2132 // Next try a zext cast. If the cast is folded, use it. 2133 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2134 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2135 return ZExt; 2136 2137 // Next try a sext cast. If the cast is folded, use it. 2138 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2139 if (!isa<SCEVSignExtendExpr>(SExt)) 2140 return SExt; 2141 2142 // Force the cast to be folded into the operands of an addrec. 2143 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2144 SmallVector<const SCEV *, 4> Ops; 2145 for (const SCEV *Op : AR->operands()) 2146 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2147 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2148 } 2149 2150 // If the expression is obviously signed, use the sext cast value. 2151 if (isa<SCEVSMaxExpr>(Op)) 2152 return SExt; 2153 2154 // Absent any other information, use the zext cast value. 2155 return ZExt; 2156 } 2157 2158 /// Process the given Ops list, which is a list of operands to be added under 2159 /// the given scale, update the given map. This is a helper function for 2160 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2161 /// that would form an add expression like this: 2162 /// 2163 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2164 /// 2165 /// where A and B are constants, update the map with these values: 2166 /// 2167 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2168 /// 2169 /// and add 13 + A*B*29 to AccumulatedConstant. 2170 /// This will allow getAddRecExpr to produce this: 2171 /// 2172 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2173 /// 2174 /// This form often exposes folding opportunities that are hidden in 2175 /// the original operand list. 2176 /// 2177 /// Return true iff it appears that any interesting folding opportunities 2178 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2179 /// the common case where no interesting opportunities are present, and 2180 /// is also used as a check to avoid infinite recursion. 2181 static bool 2182 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2183 SmallVectorImpl<const SCEV *> &NewOps, 2184 APInt &AccumulatedConstant, 2185 const SCEV *const *Ops, size_t NumOperands, 2186 const APInt &Scale, 2187 ScalarEvolution &SE) { 2188 bool Interesting = false; 2189 2190 // Iterate over the add operands. They are sorted, with constants first. 2191 unsigned i = 0; 2192 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2193 ++i; 2194 // Pull a buried constant out to the outside. 2195 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2196 Interesting = true; 2197 AccumulatedConstant += Scale * C->getAPInt(); 2198 } 2199 2200 // Next comes everything else. We're especially interested in multiplies 2201 // here, but they're in the middle, so just visit the rest with one loop. 2202 for (; i != NumOperands; ++i) { 2203 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2204 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2205 APInt NewScale = 2206 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2207 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2208 // A multiplication of a constant with another add; recurse. 2209 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2210 Interesting |= 2211 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2212 Add->op_begin(), Add->getNumOperands(), 2213 NewScale, SE); 2214 } else { 2215 // A multiplication of a constant with some other value. Update 2216 // the map. 2217 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2218 const SCEV *Key = SE.getMulExpr(MulOps); 2219 auto Pair = M.insert({Key, NewScale}); 2220 if (Pair.second) { 2221 NewOps.push_back(Pair.first->first); 2222 } else { 2223 Pair.first->second += NewScale; 2224 // The map already had an entry for this value, which may indicate 2225 // a folding opportunity. 2226 Interesting = true; 2227 } 2228 } 2229 } else { 2230 // An ordinary operand. Update the map. 2231 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2232 M.insert({Ops[i], Scale}); 2233 if (Pair.second) { 2234 NewOps.push_back(Pair.first->first); 2235 } else { 2236 Pair.first->second += Scale; 2237 // The map already had an entry for this value, which may indicate 2238 // a folding opportunity. 2239 Interesting = true; 2240 } 2241 } 2242 } 2243 2244 return Interesting; 2245 } 2246 2247 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2248 const SCEV *LHS, const SCEV *RHS) { 2249 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2250 SCEV::NoWrapFlags, unsigned); 2251 switch (BinOp) { 2252 default: 2253 llvm_unreachable("Unsupported binary op"); 2254 case Instruction::Add: 2255 Operation = &ScalarEvolution::getAddExpr; 2256 break; 2257 case Instruction::Sub: 2258 Operation = &ScalarEvolution::getMinusSCEV; 2259 break; 2260 case Instruction::Mul: 2261 Operation = &ScalarEvolution::getMulExpr; 2262 break; 2263 } 2264 2265 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2266 Signed ? &ScalarEvolution::getSignExtendExpr 2267 : &ScalarEvolution::getZeroExtendExpr; 2268 2269 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2270 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2271 auto *WideTy = 2272 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2273 2274 const SCEV *A = (this->*Extension)( 2275 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2276 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2277 (this->*Extension)(RHS, WideTy, 0), 2278 SCEV::FlagAnyWrap, 0); 2279 return A == B; 2280 } 2281 2282 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2283 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2284 const OverflowingBinaryOperator *OBO) { 2285 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2286 2287 if (OBO->hasNoUnsignedWrap()) 2288 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2289 if (OBO->hasNoSignedWrap()) 2290 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2291 2292 bool Deduced = false; 2293 2294 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2295 return {Flags, Deduced}; 2296 2297 if (OBO->getOpcode() != Instruction::Add && 2298 OBO->getOpcode() != Instruction::Sub && 2299 OBO->getOpcode() != Instruction::Mul) 2300 return {Flags, Deduced}; 2301 2302 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2303 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2304 2305 if (!OBO->hasNoUnsignedWrap() && 2306 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2307 /* Signed */ false, LHS, RHS)) { 2308 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2309 Deduced = true; 2310 } 2311 2312 if (!OBO->hasNoSignedWrap() && 2313 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2314 /* Signed */ true, LHS, RHS)) { 2315 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2316 Deduced = true; 2317 } 2318 2319 return {Flags, Deduced}; 2320 } 2321 2322 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2323 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2324 // can't-overflow flags for the operation if possible. 2325 static SCEV::NoWrapFlags 2326 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2327 const ArrayRef<const SCEV *> Ops, 2328 SCEV::NoWrapFlags Flags) { 2329 using namespace std::placeholders; 2330 2331 using OBO = OverflowingBinaryOperator; 2332 2333 bool CanAnalyze = 2334 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2335 (void)CanAnalyze; 2336 assert(CanAnalyze && "don't call from other places!"); 2337 2338 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2339 SCEV::NoWrapFlags SignOrUnsignWrap = 2340 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2341 2342 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2343 auto IsKnownNonNegative = [&](const SCEV *S) { 2344 return SE->isKnownNonNegative(S); 2345 }; 2346 2347 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2348 Flags = 2349 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2350 2351 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2352 2353 if (SignOrUnsignWrap != SignOrUnsignMask && 2354 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2355 isa<SCEVConstant>(Ops[0])) { 2356 2357 auto Opcode = [&] { 2358 switch (Type) { 2359 case scAddExpr: 2360 return Instruction::Add; 2361 case scMulExpr: 2362 return Instruction::Mul; 2363 default: 2364 llvm_unreachable("Unexpected SCEV op."); 2365 } 2366 }(); 2367 2368 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2369 2370 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2371 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2372 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2373 Opcode, C, OBO::NoSignedWrap); 2374 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2375 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2376 } 2377 2378 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2379 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2380 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2381 Opcode, C, OBO::NoUnsignedWrap); 2382 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2383 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2384 } 2385 } 2386 2387 return Flags; 2388 } 2389 2390 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2391 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2392 } 2393 2394 /// Get a canonical add expression, or something simpler if possible. 2395 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2396 SCEV::NoWrapFlags OrigFlags, 2397 unsigned Depth) { 2398 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2399 "only nuw or nsw allowed"); 2400 assert(!Ops.empty() && "Cannot get empty add!"); 2401 if (Ops.size() == 1) return Ops[0]; 2402 #ifndef NDEBUG 2403 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2404 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2405 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2406 "SCEVAddExpr operand types don't match!"); 2407 #endif 2408 2409 // Sort by complexity, this groups all similar expression types together. 2410 GroupByComplexity(Ops, &LI, DT); 2411 2412 // If there are any constants, fold them together. 2413 unsigned Idx = 0; 2414 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2415 ++Idx; 2416 assert(Idx < Ops.size()); 2417 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2418 // We found two constants, fold them together! 2419 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2420 if (Ops.size() == 2) return Ops[0]; 2421 Ops.erase(Ops.begin()+1); // Erase the folded element 2422 LHSC = cast<SCEVConstant>(Ops[0]); 2423 } 2424 2425 // If we are left with a constant zero being added, strip it off. 2426 if (LHSC->getValue()->isZero()) { 2427 Ops.erase(Ops.begin()); 2428 --Idx; 2429 } 2430 2431 if (Ops.size() == 1) return Ops[0]; 2432 } 2433 2434 // Delay expensive flag strengthening until necessary. 2435 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2436 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2437 }; 2438 2439 // Limit recursion calls depth. 2440 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2441 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2442 2443 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2444 // Don't strengthen flags if we have no new information. 2445 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2446 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2447 Add->setNoWrapFlags(ComputeFlags(Ops)); 2448 return S; 2449 } 2450 2451 // Okay, check to see if the same value occurs in the operand list more than 2452 // once. If so, merge them together into an multiply expression. Since we 2453 // sorted the list, these values are required to be adjacent. 2454 Type *Ty = Ops[0]->getType(); 2455 bool FoundMatch = false; 2456 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2457 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2458 // Scan ahead to count how many equal operands there are. 2459 unsigned Count = 2; 2460 while (i+Count != e && Ops[i+Count] == Ops[i]) 2461 ++Count; 2462 // Merge the values into a multiply. 2463 const SCEV *Scale = getConstant(Ty, Count); 2464 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2465 if (Ops.size() == Count) 2466 return Mul; 2467 Ops[i] = Mul; 2468 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2469 --i; e -= Count - 1; 2470 FoundMatch = true; 2471 } 2472 if (FoundMatch) 2473 return getAddExpr(Ops, OrigFlags, Depth + 1); 2474 2475 // Check for truncates. If all the operands are truncated from the same 2476 // type, see if factoring out the truncate would permit the result to be 2477 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2478 // if the contents of the resulting outer trunc fold to something simple. 2479 auto FindTruncSrcType = [&]() -> Type * { 2480 // We're ultimately looking to fold an addrec of truncs and muls of only 2481 // constants and truncs, so if we find any other types of SCEV 2482 // as operands of the addrec then we bail and return nullptr here. 2483 // Otherwise, we return the type of the operand of a trunc that we find. 2484 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2485 return T->getOperand()->getType(); 2486 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2487 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2488 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2489 return T->getOperand()->getType(); 2490 } 2491 return nullptr; 2492 }; 2493 if (auto *SrcType = FindTruncSrcType()) { 2494 SmallVector<const SCEV *, 8> LargeOps; 2495 bool Ok = true; 2496 // Check all the operands to see if they can be represented in the 2497 // source type of the truncate. 2498 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2500 if (T->getOperand()->getType() != SrcType) { 2501 Ok = false; 2502 break; 2503 } 2504 LargeOps.push_back(T->getOperand()); 2505 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2506 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2507 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2508 SmallVector<const SCEV *, 8> LargeMulOps; 2509 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2510 if (const SCEVTruncateExpr *T = 2511 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2512 if (T->getOperand()->getType() != SrcType) { 2513 Ok = false; 2514 break; 2515 } 2516 LargeMulOps.push_back(T->getOperand()); 2517 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2518 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2519 } else { 2520 Ok = false; 2521 break; 2522 } 2523 } 2524 if (Ok) 2525 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2526 } else { 2527 Ok = false; 2528 break; 2529 } 2530 } 2531 if (Ok) { 2532 // Evaluate the expression in the larger type. 2533 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2534 // If it folds to something simple, use it. Otherwise, don't. 2535 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2536 return getTruncateExpr(Fold, Ty); 2537 } 2538 } 2539 2540 // Skip past any other cast SCEVs. 2541 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2542 ++Idx; 2543 2544 // If there are add operands they would be next. 2545 if (Idx < Ops.size()) { 2546 bool DeletedAdd = false; 2547 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2548 // common NUW flag for expression after inlining. Other flags cannot be 2549 // preserved, because they may depend on the original order of operations. 2550 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2551 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2552 if (Ops.size() > AddOpsInlineThreshold || 2553 Add->getNumOperands() > AddOpsInlineThreshold) 2554 break; 2555 // If we have an add, expand the add operands onto the end of the operands 2556 // list. 2557 Ops.erase(Ops.begin()+Idx); 2558 Ops.append(Add->op_begin(), Add->op_end()); 2559 DeletedAdd = true; 2560 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2561 } 2562 2563 // If we deleted at least one add, we added operands to the end of the list, 2564 // and they are not necessarily sorted. Recurse to resort and resimplify 2565 // any operands we just acquired. 2566 if (DeletedAdd) 2567 return getAddExpr(Ops, CommonFlags, Depth + 1); 2568 } 2569 2570 // Skip over the add expression until we get to a multiply. 2571 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2572 ++Idx; 2573 2574 // Check to see if there are any folding opportunities present with 2575 // operands multiplied by constant values. 2576 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2577 uint64_t BitWidth = getTypeSizeInBits(Ty); 2578 DenseMap<const SCEV *, APInt> M; 2579 SmallVector<const SCEV *, 8> NewOps; 2580 APInt AccumulatedConstant(BitWidth, 0); 2581 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2582 Ops.data(), Ops.size(), 2583 APInt(BitWidth, 1), *this)) { 2584 struct APIntCompare { 2585 bool operator()(const APInt &LHS, const APInt &RHS) const { 2586 return LHS.ult(RHS); 2587 } 2588 }; 2589 2590 // Some interesting folding opportunity is present, so its worthwhile to 2591 // re-generate the operands list. Group the operands by constant scale, 2592 // to avoid multiplying by the same constant scale multiple times. 2593 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2594 for (const SCEV *NewOp : NewOps) 2595 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2596 // Re-generate the operands list. 2597 Ops.clear(); 2598 if (AccumulatedConstant != 0) 2599 Ops.push_back(getConstant(AccumulatedConstant)); 2600 for (auto &MulOp : MulOpLists) 2601 if (MulOp.first != 0) 2602 Ops.push_back(getMulExpr( 2603 getConstant(MulOp.first), 2604 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2605 SCEV::FlagAnyWrap, Depth + 1)); 2606 if (Ops.empty()) 2607 return getZero(Ty); 2608 if (Ops.size() == 1) 2609 return Ops[0]; 2610 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2611 } 2612 } 2613 2614 // If we are adding something to a multiply expression, make sure the 2615 // something is not already an operand of the multiply. If so, merge it into 2616 // the multiply. 2617 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2618 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2619 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2620 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2621 if (isa<SCEVConstant>(MulOpSCEV)) 2622 continue; 2623 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2624 if (MulOpSCEV == Ops[AddOp]) { 2625 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2626 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2627 if (Mul->getNumOperands() != 2) { 2628 // If the multiply has more than two operands, we must get the 2629 // Y*Z term. 2630 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2631 Mul->op_begin()+MulOp); 2632 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2633 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2634 } 2635 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2636 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2637 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2638 SCEV::FlagAnyWrap, Depth + 1); 2639 if (Ops.size() == 2) return OuterMul; 2640 if (AddOp < Idx) { 2641 Ops.erase(Ops.begin()+AddOp); 2642 Ops.erase(Ops.begin()+Idx-1); 2643 } else { 2644 Ops.erase(Ops.begin()+Idx); 2645 Ops.erase(Ops.begin()+AddOp-1); 2646 } 2647 Ops.push_back(OuterMul); 2648 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2649 } 2650 2651 // Check this multiply against other multiplies being added together. 2652 for (unsigned OtherMulIdx = Idx+1; 2653 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2654 ++OtherMulIdx) { 2655 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2656 // If MulOp occurs in OtherMul, we can fold the two multiplies 2657 // together. 2658 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2659 OMulOp != e; ++OMulOp) 2660 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2661 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2662 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2663 if (Mul->getNumOperands() != 2) { 2664 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2665 Mul->op_begin()+MulOp); 2666 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2667 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2668 } 2669 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2670 if (OtherMul->getNumOperands() != 2) { 2671 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2672 OtherMul->op_begin()+OMulOp); 2673 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2674 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2675 } 2676 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2677 const SCEV *InnerMulSum = 2678 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2679 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2680 SCEV::FlagAnyWrap, Depth + 1); 2681 if (Ops.size() == 2) return OuterMul; 2682 Ops.erase(Ops.begin()+Idx); 2683 Ops.erase(Ops.begin()+OtherMulIdx-1); 2684 Ops.push_back(OuterMul); 2685 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2686 } 2687 } 2688 } 2689 } 2690 2691 // If there are any add recurrences in the operands list, see if any other 2692 // added values are loop invariant. If so, we can fold them into the 2693 // recurrence. 2694 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2695 ++Idx; 2696 2697 // Scan over all recurrences, trying to fold loop invariants into them. 2698 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2699 // Scan all of the other operands to this add and add them to the vector if 2700 // they are loop invariant w.r.t. the recurrence. 2701 SmallVector<const SCEV *, 8> LIOps; 2702 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2703 const Loop *AddRecLoop = AddRec->getLoop(); 2704 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2705 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2706 LIOps.push_back(Ops[i]); 2707 Ops.erase(Ops.begin()+i); 2708 --i; --e; 2709 } 2710 2711 // If we found some loop invariants, fold them into the recurrence. 2712 if (!LIOps.empty()) { 2713 // Compute nowrap flags for the addition of the loop-invariant ops and 2714 // the addrec. Temporarily push it as an operand for that purpose. 2715 LIOps.push_back(AddRec); 2716 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2717 LIOps.pop_back(); 2718 2719 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2720 LIOps.push_back(AddRec->getStart()); 2721 2722 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2723 // This follows from the fact that the no-wrap flags on the outer add 2724 // expression are applicable on the 0th iteration, when the add recurrence 2725 // will be equal to its start value. 2726 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2727 2728 // Build the new addrec. Propagate the NUW and NSW flags if both the 2729 // outer add and the inner addrec are guaranteed to have no overflow. 2730 // Always propagate NW. 2731 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2732 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2733 2734 // If all of the other operands were loop invariant, we are done. 2735 if (Ops.size() == 1) return NewRec; 2736 2737 // Otherwise, add the folded AddRec by the non-invariant parts. 2738 for (unsigned i = 0;; ++i) 2739 if (Ops[i] == AddRec) { 2740 Ops[i] = NewRec; 2741 break; 2742 } 2743 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2744 } 2745 2746 // Okay, if there weren't any loop invariants to be folded, check to see if 2747 // there are multiple AddRec's with the same loop induction variable being 2748 // added together. If so, we can fold them. 2749 for (unsigned OtherIdx = Idx+1; 2750 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2751 ++OtherIdx) { 2752 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2753 // so that the 1st found AddRecExpr is dominated by all others. 2754 assert(DT.dominates( 2755 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2756 AddRec->getLoop()->getHeader()) && 2757 "AddRecExprs are not sorted in reverse dominance order?"); 2758 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2759 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2760 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2761 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2762 ++OtherIdx) { 2763 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2764 if (OtherAddRec->getLoop() == AddRecLoop) { 2765 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2766 i != e; ++i) { 2767 if (i >= AddRecOps.size()) { 2768 AddRecOps.append(OtherAddRec->op_begin()+i, 2769 OtherAddRec->op_end()); 2770 break; 2771 } 2772 SmallVector<const SCEV *, 2> TwoOps = { 2773 AddRecOps[i], OtherAddRec->getOperand(i)}; 2774 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2775 } 2776 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2777 } 2778 } 2779 // Step size has changed, so we cannot guarantee no self-wraparound. 2780 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2781 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2782 } 2783 } 2784 2785 // Otherwise couldn't fold anything into this recurrence. Move onto the 2786 // next one. 2787 } 2788 2789 // Okay, it looks like we really DO need an add expr. Check to see if we 2790 // already have one, otherwise create a new one. 2791 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2792 } 2793 2794 const SCEV * 2795 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2796 SCEV::NoWrapFlags Flags) { 2797 FoldingSetNodeID ID; 2798 ID.AddInteger(scAddExpr); 2799 for (const SCEV *Op : Ops) 2800 ID.AddPointer(Op); 2801 void *IP = nullptr; 2802 SCEVAddExpr *S = 2803 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2804 if (!S) { 2805 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2806 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2807 S = new (SCEVAllocator) 2808 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2809 UniqueSCEVs.InsertNode(S, IP); 2810 addToLoopUseLists(S); 2811 } 2812 S->setNoWrapFlags(Flags); 2813 return S; 2814 } 2815 2816 const SCEV * 2817 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2818 const Loop *L, SCEV::NoWrapFlags Flags) { 2819 FoldingSetNodeID ID; 2820 ID.AddInteger(scAddRecExpr); 2821 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2822 ID.AddPointer(Ops[i]); 2823 ID.AddPointer(L); 2824 void *IP = nullptr; 2825 SCEVAddRecExpr *S = 2826 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2827 if (!S) { 2828 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2829 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2830 S = new (SCEVAllocator) 2831 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2832 UniqueSCEVs.InsertNode(S, IP); 2833 addToLoopUseLists(S); 2834 } 2835 setNoWrapFlags(S, Flags); 2836 return S; 2837 } 2838 2839 const SCEV * 2840 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2841 SCEV::NoWrapFlags Flags) { 2842 FoldingSetNodeID ID; 2843 ID.AddInteger(scMulExpr); 2844 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2845 ID.AddPointer(Ops[i]); 2846 void *IP = nullptr; 2847 SCEVMulExpr *S = 2848 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2849 if (!S) { 2850 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2851 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2852 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2853 O, Ops.size()); 2854 UniqueSCEVs.InsertNode(S, IP); 2855 addToLoopUseLists(S); 2856 } 2857 S->setNoWrapFlags(Flags); 2858 return S; 2859 } 2860 2861 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2862 uint64_t k = i*j; 2863 if (j > 1 && k / j != i) Overflow = true; 2864 return k; 2865 } 2866 2867 /// Compute the result of "n choose k", the binomial coefficient. If an 2868 /// intermediate computation overflows, Overflow will be set and the return will 2869 /// be garbage. Overflow is not cleared on absence of overflow. 2870 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2871 // We use the multiplicative formula: 2872 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2873 // At each iteration, we take the n-th term of the numeral and divide by the 2874 // (k-n)th term of the denominator. This division will always produce an 2875 // integral result, and helps reduce the chance of overflow in the 2876 // intermediate computations. However, we can still overflow even when the 2877 // final result would fit. 2878 2879 if (n == 0 || n == k) return 1; 2880 if (k > n) return 0; 2881 2882 if (k > n/2) 2883 k = n-k; 2884 2885 uint64_t r = 1; 2886 for (uint64_t i = 1; i <= k; ++i) { 2887 r = umul_ov(r, n-(i-1), Overflow); 2888 r /= i; 2889 } 2890 return r; 2891 } 2892 2893 /// Determine if any of the operands in this SCEV are a constant or if 2894 /// any of the add or multiply expressions in this SCEV contain a constant. 2895 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2896 struct FindConstantInAddMulChain { 2897 bool FoundConstant = false; 2898 2899 bool follow(const SCEV *S) { 2900 FoundConstant |= isa<SCEVConstant>(S); 2901 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2902 } 2903 2904 bool isDone() const { 2905 return FoundConstant; 2906 } 2907 }; 2908 2909 FindConstantInAddMulChain F; 2910 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2911 ST.visitAll(StartExpr); 2912 return F.FoundConstant; 2913 } 2914 2915 /// Get a canonical multiply expression, or something simpler if possible. 2916 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2917 SCEV::NoWrapFlags OrigFlags, 2918 unsigned Depth) { 2919 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2920 "only nuw or nsw allowed"); 2921 assert(!Ops.empty() && "Cannot get empty mul!"); 2922 if (Ops.size() == 1) return Ops[0]; 2923 #ifndef NDEBUG 2924 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2925 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2926 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2927 "SCEVMulExpr operand types don't match!"); 2928 #endif 2929 2930 // Sort by complexity, this groups all similar expression types together. 2931 GroupByComplexity(Ops, &LI, DT); 2932 2933 // If there are any constants, fold them together. 2934 unsigned Idx = 0; 2935 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2936 ++Idx; 2937 assert(Idx < Ops.size()); 2938 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2939 // We found two constants, fold them together! 2940 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2941 if (Ops.size() == 2) return Ops[0]; 2942 Ops.erase(Ops.begin()+1); // Erase the folded element 2943 LHSC = cast<SCEVConstant>(Ops[0]); 2944 } 2945 2946 // If we have a multiply of zero, it will always be zero. 2947 if (LHSC->getValue()->isZero()) 2948 return LHSC; 2949 2950 // If we are left with a constant one being multiplied, strip it off. 2951 if (LHSC->getValue()->isOne()) { 2952 Ops.erase(Ops.begin()); 2953 --Idx; 2954 } 2955 2956 if (Ops.size() == 1) 2957 return Ops[0]; 2958 } 2959 2960 // Delay expensive flag strengthening until necessary. 2961 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2962 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2963 }; 2964 2965 // Limit recursion calls depth. 2966 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2967 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2968 2969 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2970 // Don't strengthen flags if we have no new information. 2971 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2972 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2973 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2974 return S; 2975 } 2976 2977 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2978 if (Ops.size() == 2) { 2979 // C1*(C2+V) -> C1*C2 + C1*V 2980 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2981 // If any of Add's ops are Adds or Muls with a constant, apply this 2982 // transformation as well. 2983 // 2984 // TODO: There are some cases where this transformation is not 2985 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2986 // this transformation should be narrowed down. 2987 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2988 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2989 SCEV::FlagAnyWrap, Depth + 1), 2990 getMulExpr(LHSC, Add->getOperand(1), 2991 SCEV::FlagAnyWrap, Depth + 1), 2992 SCEV::FlagAnyWrap, Depth + 1); 2993 2994 if (Ops[0]->isAllOnesValue()) { 2995 // If we have a mul by -1 of an add, try distributing the -1 among the 2996 // add operands. 2997 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2998 SmallVector<const SCEV *, 4> NewOps; 2999 bool AnyFolded = false; 3000 for (const SCEV *AddOp : Add->operands()) { 3001 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3002 Depth + 1); 3003 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3004 NewOps.push_back(Mul); 3005 } 3006 if (AnyFolded) 3007 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3008 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3009 // Negation preserves a recurrence's no self-wrap property. 3010 SmallVector<const SCEV *, 4> Operands; 3011 for (const SCEV *AddRecOp : AddRec->operands()) 3012 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3013 Depth + 1)); 3014 3015 return getAddRecExpr(Operands, AddRec->getLoop(), 3016 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3017 } 3018 } 3019 } 3020 } 3021 3022 // Skip over the add expression until we get to a multiply. 3023 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3024 ++Idx; 3025 3026 // If there are mul operands inline them all into this expression. 3027 if (Idx < Ops.size()) { 3028 bool DeletedMul = false; 3029 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3030 if (Ops.size() > MulOpsInlineThreshold) 3031 break; 3032 // If we have an mul, expand the mul operands onto the end of the 3033 // operands list. 3034 Ops.erase(Ops.begin()+Idx); 3035 Ops.append(Mul->op_begin(), Mul->op_end()); 3036 DeletedMul = true; 3037 } 3038 3039 // If we deleted at least one mul, we added operands to the end of the 3040 // list, and they are not necessarily sorted. Recurse to resort and 3041 // resimplify any operands we just acquired. 3042 if (DeletedMul) 3043 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3044 } 3045 3046 // If there are any add recurrences in the operands list, see if any other 3047 // added values are loop invariant. If so, we can fold them into the 3048 // recurrence. 3049 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3050 ++Idx; 3051 3052 // Scan over all recurrences, trying to fold loop invariants into them. 3053 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3054 // Scan all of the other operands to this mul and add them to the vector 3055 // if they are loop invariant w.r.t. the recurrence. 3056 SmallVector<const SCEV *, 8> LIOps; 3057 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3058 const Loop *AddRecLoop = AddRec->getLoop(); 3059 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3060 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3061 LIOps.push_back(Ops[i]); 3062 Ops.erase(Ops.begin()+i); 3063 --i; --e; 3064 } 3065 3066 // If we found some loop invariants, fold them into the recurrence. 3067 if (!LIOps.empty()) { 3068 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3069 SmallVector<const SCEV *, 4> NewOps; 3070 NewOps.reserve(AddRec->getNumOperands()); 3071 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3072 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3073 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3074 SCEV::FlagAnyWrap, Depth + 1)); 3075 3076 // Build the new addrec. Propagate the NUW and NSW flags if both the 3077 // outer mul and the inner addrec are guaranteed to have no overflow. 3078 // 3079 // No self-wrap cannot be guaranteed after changing the step size, but 3080 // will be inferred if either NUW or NSW is true. 3081 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3082 const SCEV *NewRec = getAddRecExpr( 3083 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3084 3085 // If all of the other operands were loop invariant, we are done. 3086 if (Ops.size() == 1) return NewRec; 3087 3088 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3089 for (unsigned i = 0;; ++i) 3090 if (Ops[i] == AddRec) { 3091 Ops[i] = NewRec; 3092 break; 3093 } 3094 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3095 } 3096 3097 // Okay, if there weren't any loop invariants to be folded, check to see 3098 // if there are multiple AddRec's with the same loop induction variable 3099 // being multiplied together. If so, we can fold them. 3100 3101 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3102 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3103 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3104 // ]]],+,...up to x=2n}. 3105 // Note that the arguments to choose() are always integers with values 3106 // known at compile time, never SCEV objects. 3107 // 3108 // The implementation avoids pointless extra computations when the two 3109 // addrec's are of different length (mathematically, it's equivalent to 3110 // an infinite stream of zeros on the right). 3111 bool OpsModified = false; 3112 for (unsigned OtherIdx = Idx+1; 3113 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3114 ++OtherIdx) { 3115 const SCEVAddRecExpr *OtherAddRec = 3116 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3117 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3118 continue; 3119 3120 // Limit max number of arguments to avoid creation of unreasonably big 3121 // SCEVAddRecs with very complex operands. 3122 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3123 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3124 continue; 3125 3126 bool Overflow = false; 3127 Type *Ty = AddRec->getType(); 3128 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3129 SmallVector<const SCEV*, 7> AddRecOps; 3130 for (int x = 0, xe = AddRec->getNumOperands() + 3131 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3132 SmallVector <const SCEV *, 7> SumOps; 3133 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3134 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3135 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3136 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3137 z < ze && !Overflow; ++z) { 3138 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3139 uint64_t Coeff; 3140 if (LargerThan64Bits) 3141 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3142 else 3143 Coeff = Coeff1*Coeff2; 3144 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3145 const SCEV *Term1 = AddRec->getOperand(y-z); 3146 const SCEV *Term2 = OtherAddRec->getOperand(z); 3147 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3148 SCEV::FlagAnyWrap, Depth + 1)); 3149 } 3150 } 3151 if (SumOps.empty()) 3152 SumOps.push_back(getZero(Ty)); 3153 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3154 } 3155 if (!Overflow) { 3156 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3157 SCEV::FlagAnyWrap); 3158 if (Ops.size() == 2) return NewAddRec; 3159 Ops[Idx] = NewAddRec; 3160 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3161 OpsModified = true; 3162 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3163 if (!AddRec) 3164 break; 3165 } 3166 } 3167 if (OpsModified) 3168 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3169 3170 // Otherwise couldn't fold anything into this recurrence. Move onto the 3171 // next one. 3172 } 3173 3174 // Okay, it looks like we really DO need an mul expr. Check to see if we 3175 // already have one, otherwise create a new one. 3176 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3177 } 3178 3179 /// Represents an unsigned remainder expression based on unsigned division. 3180 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3181 const SCEV *RHS) { 3182 assert(getEffectiveSCEVType(LHS->getType()) == 3183 getEffectiveSCEVType(RHS->getType()) && 3184 "SCEVURemExpr operand types don't match!"); 3185 3186 // Short-circuit easy cases 3187 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3188 // If constant is one, the result is trivial 3189 if (RHSC->getValue()->isOne()) 3190 return getZero(LHS->getType()); // X urem 1 --> 0 3191 3192 // If constant is a power of two, fold into a zext(trunc(LHS)). 3193 if (RHSC->getAPInt().isPowerOf2()) { 3194 Type *FullTy = LHS->getType(); 3195 Type *TruncTy = 3196 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3197 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3198 } 3199 } 3200 3201 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3202 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3203 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3204 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3205 } 3206 3207 /// Get a canonical unsigned division expression, or something simpler if 3208 /// possible. 3209 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3210 const SCEV *RHS) { 3211 assert(getEffectiveSCEVType(LHS->getType()) == 3212 getEffectiveSCEVType(RHS->getType()) && 3213 "SCEVUDivExpr operand types don't match!"); 3214 3215 FoldingSetNodeID ID; 3216 ID.AddInteger(scUDivExpr); 3217 ID.AddPointer(LHS); 3218 ID.AddPointer(RHS); 3219 void *IP = nullptr; 3220 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3221 return S; 3222 3223 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3224 if (RHSC->getValue()->isOne()) 3225 return LHS; // X udiv 1 --> x 3226 // If the denominator is zero, the result of the udiv is undefined. Don't 3227 // try to analyze it, because the resolution chosen here may differ from 3228 // the resolution chosen in other parts of the compiler. 3229 if (!RHSC->getValue()->isZero()) { 3230 // Determine if the division can be folded into the operands of 3231 // its operands. 3232 // TODO: Generalize this to non-constants by using known-bits information. 3233 Type *Ty = LHS->getType(); 3234 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3235 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3236 // For non-power-of-two values, effectively round the value up to the 3237 // nearest power of two. 3238 if (!RHSC->getAPInt().isPowerOf2()) 3239 ++MaxShiftAmt; 3240 IntegerType *ExtTy = 3241 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3242 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3243 if (const SCEVConstant *Step = 3244 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3245 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3246 const APInt &StepInt = Step->getAPInt(); 3247 const APInt &DivInt = RHSC->getAPInt(); 3248 if (!StepInt.urem(DivInt) && 3249 getZeroExtendExpr(AR, ExtTy) == 3250 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3251 getZeroExtendExpr(Step, ExtTy), 3252 AR->getLoop(), SCEV::FlagAnyWrap)) { 3253 SmallVector<const SCEV *, 4> Operands; 3254 for (const SCEV *Op : AR->operands()) 3255 Operands.push_back(getUDivExpr(Op, RHS)); 3256 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3257 } 3258 /// Get a canonical UDivExpr for a recurrence. 3259 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3260 // We can currently only fold X%N if X is constant. 3261 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3262 if (StartC && !DivInt.urem(StepInt) && 3263 getZeroExtendExpr(AR, ExtTy) == 3264 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3265 getZeroExtendExpr(Step, ExtTy), 3266 AR->getLoop(), SCEV::FlagAnyWrap)) { 3267 const APInt &StartInt = StartC->getAPInt(); 3268 const APInt &StartRem = StartInt.urem(StepInt); 3269 if (StartRem != 0) { 3270 const SCEV *NewLHS = 3271 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3272 AR->getLoop(), SCEV::FlagNW); 3273 if (LHS != NewLHS) { 3274 LHS = NewLHS; 3275 3276 // Reset the ID to include the new LHS, and check if it is 3277 // already cached. 3278 ID.clear(); 3279 ID.AddInteger(scUDivExpr); 3280 ID.AddPointer(LHS); 3281 ID.AddPointer(RHS); 3282 IP = nullptr; 3283 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3284 return S; 3285 } 3286 } 3287 } 3288 } 3289 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3290 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3291 SmallVector<const SCEV *, 4> Operands; 3292 for (const SCEV *Op : M->operands()) 3293 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3294 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3295 // Find an operand that's safely divisible. 3296 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3297 const SCEV *Op = M->getOperand(i); 3298 const SCEV *Div = getUDivExpr(Op, RHSC); 3299 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3300 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3301 Operands[i] = Div; 3302 return getMulExpr(Operands); 3303 } 3304 } 3305 } 3306 3307 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3308 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3309 if (auto *DivisorConstant = 3310 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3311 bool Overflow = false; 3312 APInt NewRHS = 3313 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3314 if (Overflow) { 3315 return getConstant(RHSC->getType(), 0, false); 3316 } 3317 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3318 } 3319 } 3320 3321 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3322 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3323 SmallVector<const SCEV *, 4> Operands; 3324 for (const SCEV *Op : A->operands()) 3325 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3326 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3327 Operands.clear(); 3328 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3329 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3330 if (isa<SCEVUDivExpr>(Op) || 3331 getMulExpr(Op, RHS) != A->getOperand(i)) 3332 break; 3333 Operands.push_back(Op); 3334 } 3335 if (Operands.size() == A->getNumOperands()) 3336 return getAddExpr(Operands); 3337 } 3338 } 3339 3340 // Fold if both operands are constant. 3341 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3342 Constant *LHSCV = LHSC->getValue(); 3343 Constant *RHSCV = RHSC->getValue(); 3344 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3345 RHSCV))); 3346 } 3347 } 3348 } 3349 3350 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3351 // changes). Make sure we get a new one. 3352 IP = nullptr; 3353 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3354 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3355 LHS, RHS); 3356 UniqueSCEVs.InsertNode(S, IP); 3357 addToLoopUseLists(S); 3358 return S; 3359 } 3360 3361 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3362 APInt A = C1->getAPInt().abs(); 3363 APInt B = C2->getAPInt().abs(); 3364 uint32_t ABW = A.getBitWidth(); 3365 uint32_t BBW = B.getBitWidth(); 3366 3367 if (ABW > BBW) 3368 B = B.zext(ABW); 3369 else if (ABW < BBW) 3370 A = A.zext(BBW); 3371 3372 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3373 } 3374 3375 /// Get a canonical unsigned division expression, or something simpler if 3376 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3377 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3378 /// it's not exact because the udiv may be clearing bits. 3379 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3380 const SCEV *RHS) { 3381 // TODO: we could try to find factors in all sorts of things, but for now we 3382 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3383 // end of this file for inspiration. 3384 3385 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3386 if (!Mul || !Mul->hasNoUnsignedWrap()) 3387 return getUDivExpr(LHS, RHS); 3388 3389 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3390 // If the mulexpr multiplies by a constant, then that constant must be the 3391 // first element of the mulexpr. 3392 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3393 if (LHSCst == RHSCst) { 3394 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3395 return getMulExpr(Operands); 3396 } 3397 3398 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3399 // that there's a factor provided by one of the other terms. We need to 3400 // check. 3401 APInt Factor = gcd(LHSCst, RHSCst); 3402 if (!Factor.isIntN(1)) { 3403 LHSCst = 3404 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3405 RHSCst = 3406 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3407 SmallVector<const SCEV *, 2> Operands; 3408 Operands.push_back(LHSCst); 3409 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3410 LHS = getMulExpr(Operands); 3411 RHS = RHSCst; 3412 Mul = dyn_cast<SCEVMulExpr>(LHS); 3413 if (!Mul) 3414 return getUDivExactExpr(LHS, RHS); 3415 } 3416 } 3417 } 3418 3419 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3420 if (Mul->getOperand(i) == RHS) { 3421 SmallVector<const SCEV *, 2> Operands; 3422 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3423 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3424 return getMulExpr(Operands); 3425 } 3426 } 3427 3428 return getUDivExpr(LHS, RHS); 3429 } 3430 3431 /// Get an add recurrence expression for the specified loop. Simplify the 3432 /// expression as much as possible. 3433 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3434 const Loop *L, 3435 SCEV::NoWrapFlags Flags) { 3436 SmallVector<const SCEV *, 4> Operands; 3437 Operands.push_back(Start); 3438 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3439 if (StepChrec->getLoop() == L) { 3440 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3441 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3442 } 3443 3444 Operands.push_back(Step); 3445 return getAddRecExpr(Operands, L, Flags); 3446 } 3447 3448 /// Get an add recurrence expression for the specified loop. Simplify the 3449 /// expression as much as possible. 3450 const SCEV * 3451 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3452 const Loop *L, SCEV::NoWrapFlags Flags) { 3453 if (Operands.size() == 1) return Operands[0]; 3454 #ifndef NDEBUG 3455 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3456 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3457 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3458 "SCEVAddRecExpr operand types don't match!"); 3459 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3460 assert(isLoopInvariant(Operands[i], L) && 3461 "SCEVAddRecExpr operand is not loop-invariant!"); 3462 #endif 3463 3464 if (Operands.back()->isZero()) { 3465 Operands.pop_back(); 3466 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3467 } 3468 3469 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3470 // use that information to infer NUW and NSW flags. However, computing a 3471 // BE count requires calling getAddRecExpr, so we may not yet have a 3472 // meaningful BE count at this point (and if we don't, we'd be stuck 3473 // with a SCEVCouldNotCompute as the cached BE count). 3474 3475 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3476 3477 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3478 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3479 const Loop *NestedLoop = NestedAR->getLoop(); 3480 if (L->contains(NestedLoop) 3481 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3482 : (!NestedLoop->contains(L) && 3483 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3484 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3485 Operands[0] = NestedAR->getStart(); 3486 // AddRecs require their operands be loop-invariant with respect to their 3487 // loops. Don't perform this transformation if it would break this 3488 // requirement. 3489 bool AllInvariant = all_of( 3490 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3491 3492 if (AllInvariant) { 3493 // Create a recurrence for the outer loop with the same step size. 3494 // 3495 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3496 // inner recurrence has the same property. 3497 SCEV::NoWrapFlags OuterFlags = 3498 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3499 3500 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3501 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3502 return isLoopInvariant(Op, NestedLoop); 3503 }); 3504 3505 if (AllInvariant) { 3506 // Ok, both add recurrences are valid after the transformation. 3507 // 3508 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3509 // the outer recurrence has the same property. 3510 SCEV::NoWrapFlags InnerFlags = 3511 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3512 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3513 } 3514 } 3515 // Reset Operands to its original state. 3516 Operands[0] = NestedAR; 3517 } 3518 } 3519 3520 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3521 // already have one, otherwise create a new one. 3522 return getOrCreateAddRecExpr(Operands, L, Flags); 3523 } 3524 3525 const SCEV * 3526 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3527 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3528 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3529 // getSCEV(Base)->getType() has the same address space as Base->getType() 3530 // because SCEV::getType() preserves the address space. 3531 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3532 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3533 // instruction to its SCEV, because the Instruction may be guarded by control 3534 // flow and the no-overflow bits may not be valid for the expression in any 3535 // context. This can be fixed similarly to how these flags are handled for 3536 // adds. 3537 SCEV::NoWrapFlags OffsetWrap = 3538 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3539 3540 Type *CurTy = GEP->getType(); 3541 bool FirstIter = true; 3542 SmallVector<const SCEV *, 4> Offsets; 3543 for (const SCEV *IndexExpr : IndexExprs) { 3544 // Compute the (potentially symbolic) offset in bytes for this index. 3545 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3546 // For a struct, add the member offset. 3547 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3548 unsigned FieldNo = Index->getZExtValue(); 3549 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3550 Offsets.push_back(FieldOffset); 3551 3552 // Update CurTy to the type of the field at Index. 3553 CurTy = STy->getTypeAtIndex(Index); 3554 } else { 3555 // Update CurTy to its element type. 3556 if (FirstIter) { 3557 assert(isa<PointerType>(CurTy) && 3558 "The first index of a GEP indexes a pointer"); 3559 CurTy = GEP->getSourceElementType(); 3560 FirstIter = false; 3561 } else { 3562 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3563 } 3564 // For an array, add the element offset, explicitly scaled. 3565 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3566 // Getelementptr indices are signed. 3567 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3568 3569 // Multiply the index by the element size to compute the element offset. 3570 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3571 Offsets.push_back(LocalOffset); 3572 } 3573 } 3574 3575 // Handle degenerate case of GEP without offsets. 3576 if (Offsets.empty()) 3577 return BaseExpr; 3578 3579 // Add the offsets together, assuming nsw if inbounds. 3580 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3581 // Add the base address and the offset. We cannot use the nsw flag, as the 3582 // base address is unsigned. However, if we know that the offset is 3583 // non-negative, we can use nuw. 3584 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3585 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3586 return getAddExpr(BaseExpr, Offset, BaseWrap); 3587 } 3588 3589 std::tuple<SCEV *, FoldingSetNodeID, void *> 3590 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3591 ArrayRef<const SCEV *> Ops) { 3592 FoldingSetNodeID ID; 3593 void *IP = nullptr; 3594 ID.AddInteger(SCEVType); 3595 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3596 ID.AddPointer(Ops[i]); 3597 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3598 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3599 } 3600 3601 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3602 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3603 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3604 } 3605 3606 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3607 SmallVectorImpl<const SCEV *> &Ops) { 3608 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3609 if (Ops.size() == 1) return Ops[0]; 3610 #ifndef NDEBUG 3611 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3612 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3613 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3614 "Operand types don't match!"); 3615 #endif 3616 3617 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3618 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3619 3620 // Sort by complexity, this groups all similar expression types together. 3621 GroupByComplexity(Ops, &LI, DT); 3622 3623 // Check if we have created the same expression before. 3624 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3625 return S; 3626 } 3627 3628 // If there are any constants, fold them together. 3629 unsigned Idx = 0; 3630 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3631 ++Idx; 3632 assert(Idx < Ops.size()); 3633 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3634 if (Kind == scSMaxExpr) 3635 return APIntOps::smax(LHS, RHS); 3636 else if (Kind == scSMinExpr) 3637 return APIntOps::smin(LHS, RHS); 3638 else if (Kind == scUMaxExpr) 3639 return APIntOps::umax(LHS, RHS); 3640 else if (Kind == scUMinExpr) 3641 return APIntOps::umin(LHS, RHS); 3642 llvm_unreachable("Unknown SCEV min/max opcode"); 3643 }; 3644 3645 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3646 // We found two constants, fold them together! 3647 ConstantInt *Fold = ConstantInt::get( 3648 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3649 Ops[0] = getConstant(Fold); 3650 Ops.erase(Ops.begin()+1); // Erase the folded element 3651 if (Ops.size() == 1) return Ops[0]; 3652 LHSC = cast<SCEVConstant>(Ops[0]); 3653 } 3654 3655 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3656 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3657 3658 if (IsMax ? IsMinV : IsMaxV) { 3659 // If we are left with a constant minimum(/maximum)-int, strip it off. 3660 Ops.erase(Ops.begin()); 3661 --Idx; 3662 } else if (IsMax ? IsMaxV : IsMinV) { 3663 // If we have a max(/min) with a constant maximum(/minimum)-int, 3664 // it will always be the extremum. 3665 return LHSC; 3666 } 3667 3668 if (Ops.size() == 1) return Ops[0]; 3669 } 3670 3671 // Find the first operation of the same kind 3672 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3673 ++Idx; 3674 3675 // Check to see if one of the operands is of the same kind. If so, expand its 3676 // operands onto our operand list, and recurse to simplify. 3677 if (Idx < Ops.size()) { 3678 bool DeletedAny = false; 3679 while (Ops[Idx]->getSCEVType() == Kind) { 3680 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3681 Ops.erase(Ops.begin()+Idx); 3682 Ops.append(SMME->op_begin(), SMME->op_end()); 3683 DeletedAny = true; 3684 } 3685 3686 if (DeletedAny) 3687 return getMinMaxExpr(Kind, Ops); 3688 } 3689 3690 // Okay, check to see if the same value occurs in the operand list twice. If 3691 // so, delete one. Since we sorted the list, these values are required to 3692 // be adjacent. 3693 llvm::CmpInst::Predicate GEPred = 3694 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3695 llvm::CmpInst::Predicate LEPred = 3696 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3697 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3698 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3699 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3700 if (Ops[i] == Ops[i + 1] || 3701 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3702 // X op Y op Y --> X op Y 3703 // X op Y --> X, if we know X, Y are ordered appropriately 3704 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3705 --i; 3706 --e; 3707 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3708 Ops[i + 1])) { 3709 // X op Y --> Y, if we know X, Y are ordered appropriately 3710 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3711 --i; 3712 --e; 3713 } 3714 } 3715 3716 if (Ops.size() == 1) return Ops[0]; 3717 3718 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3719 3720 // Okay, it looks like we really DO need an expr. Check to see if we 3721 // already have one, otherwise create a new one. 3722 const SCEV *ExistingSCEV; 3723 FoldingSetNodeID ID; 3724 void *IP; 3725 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3726 if (ExistingSCEV) 3727 return ExistingSCEV; 3728 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3729 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3730 SCEV *S = new (SCEVAllocator) 3731 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3732 3733 UniqueSCEVs.InsertNode(S, IP); 3734 addToLoopUseLists(S); 3735 return S; 3736 } 3737 3738 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3739 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3740 return getSMaxExpr(Ops); 3741 } 3742 3743 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3744 return getMinMaxExpr(scSMaxExpr, Ops); 3745 } 3746 3747 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3748 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3749 return getUMaxExpr(Ops); 3750 } 3751 3752 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3753 return getMinMaxExpr(scUMaxExpr, Ops); 3754 } 3755 3756 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3757 const SCEV *RHS) { 3758 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3759 return getSMinExpr(Ops); 3760 } 3761 3762 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3763 return getMinMaxExpr(scSMinExpr, Ops); 3764 } 3765 3766 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3767 const SCEV *RHS) { 3768 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3769 return getUMinExpr(Ops); 3770 } 3771 3772 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3773 return getMinMaxExpr(scUMinExpr, Ops); 3774 } 3775 3776 const SCEV * 3777 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3778 ScalableVectorType *ScalableTy) { 3779 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3780 Constant *One = ConstantInt::get(IntTy, 1); 3781 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3782 // Note that the expression we created is the final expression, we don't 3783 // want to simplify it any further Also, if we call a normal getSCEV(), 3784 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3785 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3786 } 3787 3788 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3789 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3790 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3791 // We can bypass creating a target-independent constant expression and then 3792 // folding it back into a ConstantInt. This is just a compile-time 3793 // optimization. 3794 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3795 } 3796 3797 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3798 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3799 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3800 // We can bypass creating a target-independent constant expression and then 3801 // folding it back into a ConstantInt. This is just a compile-time 3802 // optimization. 3803 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3804 } 3805 3806 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3807 StructType *STy, 3808 unsigned FieldNo) { 3809 // We can bypass creating a target-independent constant expression and then 3810 // folding it back into a ConstantInt. This is just a compile-time 3811 // optimization. 3812 return getConstant( 3813 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3814 } 3815 3816 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3817 // Don't attempt to do anything other than create a SCEVUnknown object 3818 // here. createSCEV only calls getUnknown after checking for all other 3819 // interesting possibilities, and any other code that calls getUnknown 3820 // is doing so in order to hide a value from SCEV canonicalization. 3821 3822 FoldingSetNodeID ID; 3823 ID.AddInteger(scUnknown); 3824 ID.AddPointer(V); 3825 void *IP = nullptr; 3826 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3827 assert(cast<SCEVUnknown>(S)->getValue() == V && 3828 "Stale SCEVUnknown in uniquing map!"); 3829 return S; 3830 } 3831 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3832 FirstUnknown); 3833 FirstUnknown = cast<SCEVUnknown>(S); 3834 UniqueSCEVs.InsertNode(S, IP); 3835 return S; 3836 } 3837 3838 //===----------------------------------------------------------------------===// 3839 // Basic SCEV Analysis and PHI Idiom Recognition Code 3840 // 3841 3842 /// Test if values of the given type are analyzable within the SCEV 3843 /// framework. This primarily includes integer types, and it can optionally 3844 /// include pointer types if the ScalarEvolution class has access to 3845 /// target-specific information. 3846 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3847 // Integers and pointers are always SCEVable. 3848 return Ty->isIntOrPtrTy(); 3849 } 3850 3851 /// Return the size in bits of the specified type, for which isSCEVable must 3852 /// return true. 3853 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3854 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3855 if (Ty->isPointerTy()) 3856 return getDataLayout().getIndexTypeSizeInBits(Ty); 3857 return getDataLayout().getTypeSizeInBits(Ty); 3858 } 3859 3860 /// Return a type with the same bitwidth as the given type and which represents 3861 /// how SCEV will treat the given type, for which isSCEVable must return 3862 /// true. For pointer types, this is the pointer index sized integer type. 3863 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3864 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3865 3866 if (Ty->isIntegerTy()) 3867 return Ty; 3868 3869 // The only other support type is pointer. 3870 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3871 return getDataLayout().getIndexType(Ty); 3872 } 3873 3874 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3875 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3876 } 3877 3878 const SCEV *ScalarEvolution::getCouldNotCompute() { 3879 return CouldNotCompute.get(); 3880 } 3881 3882 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3883 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3884 auto *SU = dyn_cast<SCEVUnknown>(S); 3885 return SU && SU->getValue() == nullptr; 3886 }); 3887 3888 return !ContainsNulls; 3889 } 3890 3891 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3892 HasRecMapType::iterator I = HasRecMap.find(S); 3893 if (I != HasRecMap.end()) 3894 return I->second; 3895 3896 bool FoundAddRec = 3897 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3898 HasRecMap.insert({S, FoundAddRec}); 3899 return FoundAddRec; 3900 } 3901 3902 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3903 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3904 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3905 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3906 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3907 if (!Add) 3908 return {S, nullptr}; 3909 3910 if (Add->getNumOperands() != 2) 3911 return {S, nullptr}; 3912 3913 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3914 if (!ConstOp) 3915 return {S, nullptr}; 3916 3917 return {Add->getOperand(1), ConstOp->getValue()}; 3918 } 3919 3920 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3921 /// by the value and offset from any ValueOffsetPair in the set. 3922 ScalarEvolution::ValueOffsetPairSetVector * 3923 ScalarEvolution::getSCEVValues(const SCEV *S) { 3924 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3925 if (SI == ExprValueMap.end()) 3926 return nullptr; 3927 #ifndef NDEBUG 3928 if (VerifySCEVMap) { 3929 // Check there is no dangling Value in the set returned. 3930 for (const auto &VE : SI->second) 3931 assert(ValueExprMap.count(VE.first)); 3932 } 3933 #endif 3934 return &SI->second; 3935 } 3936 3937 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3938 /// cannot be used separately. eraseValueFromMap should be used to remove 3939 /// V from ValueExprMap and ExprValueMap at the same time. 3940 void ScalarEvolution::eraseValueFromMap(Value *V) { 3941 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3942 if (I != ValueExprMap.end()) { 3943 const SCEV *S = I->second; 3944 // Remove {V, 0} from the set of ExprValueMap[S] 3945 if (auto *SV = getSCEVValues(S)) 3946 SV->remove({V, nullptr}); 3947 3948 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3949 const SCEV *Stripped; 3950 ConstantInt *Offset; 3951 std::tie(Stripped, Offset) = splitAddExpr(S); 3952 if (Offset != nullptr) { 3953 if (auto *SV = getSCEVValues(Stripped)) 3954 SV->remove({V, Offset}); 3955 } 3956 ValueExprMap.erase(V); 3957 } 3958 } 3959 3960 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3961 /// TODO: In reality it is better to check the poison recursively 3962 /// but this is better than nothing. 3963 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3964 if (auto *I = dyn_cast<Instruction>(V)) { 3965 if (isa<OverflowingBinaryOperator>(I)) { 3966 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3967 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3968 return true; 3969 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3970 return true; 3971 } 3972 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3973 return true; 3974 } 3975 return false; 3976 } 3977 3978 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3979 /// create a new one. 3980 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3981 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3982 3983 const SCEV *S = getExistingSCEV(V); 3984 if (S == nullptr) { 3985 S = createSCEV(V); 3986 // During PHI resolution, it is possible to create two SCEVs for the same 3987 // V, so it is needed to double check whether V->S is inserted into 3988 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3989 std::pair<ValueExprMapType::iterator, bool> Pair = 3990 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3991 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3992 ExprValueMap[S].insert({V, nullptr}); 3993 3994 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3995 // ExprValueMap. 3996 const SCEV *Stripped = S; 3997 ConstantInt *Offset = nullptr; 3998 std::tie(Stripped, Offset) = splitAddExpr(S); 3999 // If stripped is SCEVUnknown, don't bother to save 4000 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4001 // increase the complexity of the expansion code. 4002 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4003 // because it may generate add/sub instead of GEP in SCEV expansion. 4004 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4005 !isa<GetElementPtrInst>(V)) 4006 ExprValueMap[Stripped].insert({V, Offset}); 4007 } 4008 } 4009 return S; 4010 } 4011 4012 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4013 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4014 4015 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4016 if (I != ValueExprMap.end()) { 4017 const SCEV *S = I->second; 4018 if (checkValidity(S)) 4019 return S; 4020 eraseValueFromMap(V); 4021 forgetMemoizedResults(S); 4022 } 4023 return nullptr; 4024 } 4025 4026 /// Return a SCEV corresponding to -V = -1*V 4027 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4028 SCEV::NoWrapFlags Flags) { 4029 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4030 return getConstant( 4031 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4032 4033 Type *Ty = V->getType(); 4034 Ty = getEffectiveSCEVType(Ty); 4035 return getMulExpr(V, getMinusOne(Ty), Flags); 4036 } 4037 4038 /// If Expr computes ~A, return A else return nullptr 4039 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4040 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4041 if (!Add || Add->getNumOperands() != 2 || 4042 !Add->getOperand(0)->isAllOnesValue()) 4043 return nullptr; 4044 4045 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4046 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4047 !AddRHS->getOperand(0)->isAllOnesValue()) 4048 return nullptr; 4049 4050 return AddRHS->getOperand(1); 4051 } 4052 4053 /// Return a SCEV corresponding to ~V = -1-V 4054 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4055 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4056 return getConstant( 4057 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4058 4059 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4060 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4061 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4062 SmallVector<const SCEV *, 2> MatchedOperands; 4063 for (const SCEV *Operand : MME->operands()) { 4064 const SCEV *Matched = MatchNotExpr(Operand); 4065 if (!Matched) 4066 return (const SCEV *)nullptr; 4067 MatchedOperands.push_back(Matched); 4068 } 4069 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4070 MatchedOperands); 4071 }; 4072 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4073 return Replaced; 4074 } 4075 4076 Type *Ty = V->getType(); 4077 Ty = getEffectiveSCEVType(Ty); 4078 return getMinusSCEV(getMinusOne(Ty), V); 4079 } 4080 4081 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4082 SCEV::NoWrapFlags Flags, 4083 unsigned Depth) { 4084 // Fast path: X - X --> 0. 4085 if (LHS == RHS) 4086 return getZero(LHS->getType()); 4087 4088 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4089 // makes it so that we cannot make much use of NUW. 4090 auto AddFlags = SCEV::FlagAnyWrap; 4091 const bool RHSIsNotMinSigned = 4092 !getSignedRangeMin(RHS).isMinSignedValue(); 4093 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4094 // Let M be the minimum representable signed value. Then (-1)*RHS 4095 // signed-wraps if and only if RHS is M. That can happen even for 4096 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4097 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4098 // (-1)*RHS, we need to prove that RHS != M. 4099 // 4100 // If LHS is non-negative and we know that LHS - RHS does not 4101 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4102 // either by proving that RHS > M or that LHS >= 0. 4103 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4104 AddFlags = SCEV::FlagNSW; 4105 } 4106 } 4107 4108 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4109 // RHS is NSW and LHS >= 0. 4110 // 4111 // The difficulty here is that the NSW flag may have been proven 4112 // relative to a loop that is to be found in a recurrence in LHS and 4113 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4114 // larger scope than intended. 4115 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4116 4117 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4118 } 4119 4120 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4121 unsigned Depth) { 4122 Type *SrcTy = V->getType(); 4123 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4124 "Cannot truncate or zero extend with non-integer arguments!"); 4125 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4126 return V; // No conversion 4127 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4128 return getTruncateExpr(V, Ty, Depth); 4129 return getZeroExtendExpr(V, Ty, Depth); 4130 } 4131 4132 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4133 unsigned Depth) { 4134 Type *SrcTy = V->getType(); 4135 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4136 "Cannot truncate or zero extend with non-integer arguments!"); 4137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4138 return V; // No conversion 4139 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4140 return getTruncateExpr(V, Ty, Depth); 4141 return getSignExtendExpr(V, Ty, Depth); 4142 } 4143 4144 const SCEV * 4145 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4146 Type *SrcTy = V->getType(); 4147 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4148 "Cannot noop or zero extend with non-integer arguments!"); 4149 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4150 "getNoopOrZeroExtend cannot truncate!"); 4151 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4152 return V; // No conversion 4153 return getZeroExtendExpr(V, Ty); 4154 } 4155 4156 const SCEV * 4157 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4158 Type *SrcTy = V->getType(); 4159 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4160 "Cannot noop or sign extend with non-integer arguments!"); 4161 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4162 "getNoopOrSignExtend cannot truncate!"); 4163 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4164 return V; // No conversion 4165 return getSignExtendExpr(V, Ty); 4166 } 4167 4168 const SCEV * 4169 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4170 Type *SrcTy = V->getType(); 4171 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4172 "Cannot noop or any extend with non-integer arguments!"); 4173 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4174 "getNoopOrAnyExtend cannot truncate!"); 4175 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4176 return V; // No conversion 4177 return getAnyExtendExpr(V, Ty); 4178 } 4179 4180 const SCEV * 4181 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4182 Type *SrcTy = V->getType(); 4183 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4184 "Cannot truncate or noop with non-integer arguments!"); 4185 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4186 "getTruncateOrNoop cannot extend!"); 4187 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4188 return V; // No conversion 4189 return getTruncateExpr(V, Ty); 4190 } 4191 4192 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4193 const SCEV *RHS) { 4194 const SCEV *PromotedLHS = LHS; 4195 const SCEV *PromotedRHS = RHS; 4196 4197 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4198 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4199 else 4200 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4201 4202 return getUMaxExpr(PromotedLHS, PromotedRHS); 4203 } 4204 4205 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4206 const SCEV *RHS) { 4207 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4208 return getUMinFromMismatchedTypes(Ops); 4209 } 4210 4211 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4212 SmallVectorImpl<const SCEV *> &Ops) { 4213 assert(!Ops.empty() && "At least one operand must be!"); 4214 // Trivial case. 4215 if (Ops.size() == 1) 4216 return Ops[0]; 4217 4218 // Find the max type first. 4219 Type *MaxType = nullptr; 4220 for (auto *S : Ops) 4221 if (MaxType) 4222 MaxType = getWiderType(MaxType, S->getType()); 4223 else 4224 MaxType = S->getType(); 4225 assert(MaxType && "Failed to find maximum type!"); 4226 4227 // Extend all ops to max type. 4228 SmallVector<const SCEV *, 2> PromotedOps; 4229 for (auto *S : Ops) 4230 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4231 4232 // Generate umin. 4233 return getUMinExpr(PromotedOps); 4234 } 4235 4236 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4237 // A pointer operand may evaluate to a nonpointer expression, such as null. 4238 if (!V->getType()->isPointerTy()) 4239 return V; 4240 4241 while (true) { 4242 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4243 V = Cast->getOperand(); 4244 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4245 const SCEV *PtrOp = nullptr; 4246 for (const SCEV *NAryOp : NAry->operands()) { 4247 if (NAryOp->getType()->isPointerTy()) { 4248 // Cannot find the base of an expression with multiple pointer ops. 4249 if (PtrOp) 4250 return V; 4251 PtrOp = NAryOp; 4252 } 4253 } 4254 if (!PtrOp) // All operands were non-pointer. 4255 return V; 4256 V = PtrOp; 4257 } else // Not something we can look further into. 4258 return V; 4259 } 4260 } 4261 4262 /// Push users of the given Instruction onto the given Worklist. 4263 static void 4264 PushDefUseChildren(Instruction *I, 4265 SmallVectorImpl<Instruction *> &Worklist) { 4266 // Push the def-use children onto the Worklist stack. 4267 for (User *U : I->users()) 4268 Worklist.push_back(cast<Instruction>(U)); 4269 } 4270 4271 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4272 SmallVector<Instruction *, 16> Worklist; 4273 PushDefUseChildren(PN, Worklist); 4274 4275 SmallPtrSet<Instruction *, 8> Visited; 4276 Visited.insert(PN); 4277 while (!Worklist.empty()) { 4278 Instruction *I = Worklist.pop_back_val(); 4279 if (!Visited.insert(I).second) 4280 continue; 4281 4282 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4283 if (It != ValueExprMap.end()) { 4284 const SCEV *Old = It->second; 4285 4286 // Short-circuit the def-use traversal if the symbolic name 4287 // ceases to appear in expressions. 4288 if (Old != SymName && !hasOperand(Old, SymName)) 4289 continue; 4290 4291 // SCEVUnknown for a PHI either means that it has an unrecognized 4292 // structure, it's a PHI that's in the progress of being computed 4293 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4294 // additional loop trip count information isn't going to change anything. 4295 // In the second case, createNodeForPHI will perform the necessary 4296 // updates on its own when it gets to that point. In the third, we do 4297 // want to forget the SCEVUnknown. 4298 if (!isa<PHINode>(I) || 4299 !isa<SCEVUnknown>(Old) || 4300 (I != PN && Old == SymName)) { 4301 eraseValueFromMap(It->first); 4302 forgetMemoizedResults(Old); 4303 } 4304 } 4305 4306 PushDefUseChildren(I, Worklist); 4307 } 4308 } 4309 4310 namespace { 4311 4312 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4313 /// expression in case its Loop is L. If it is not L then 4314 /// if IgnoreOtherLoops is true then use AddRec itself 4315 /// otherwise rewrite cannot be done. 4316 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4317 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4318 public: 4319 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4320 bool IgnoreOtherLoops = true) { 4321 SCEVInitRewriter Rewriter(L, SE); 4322 const SCEV *Result = Rewriter.visit(S); 4323 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4324 return SE.getCouldNotCompute(); 4325 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4326 ? SE.getCouldNotCompute() 4327 : Result; 4328 } 4329 4330 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4331 if (!SE.isLoopInvariant(Expr, L)) 4332 SeenLoopVariantSCEVUnknown = true; 4333 return Expr; 4334 } 4335 4336 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4337 // Only re-write AddRecExprs for this loop. 4338 if (Expr->getLoop() == L) 4339 return Expr->getStart(); 4340 SeenOtherLoops = true; 4341 return Expr; 4342 } 4343 4344 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4345 4346 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4347 4348 private: 4349 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4350 : SCEVRewriteVisitor(SE), L(L) {} 4351 4352 const Loop *L; 4353 bool SeenLoopVariantSCEVUnknown = false; 4354 bool SeenOtherLoops = false; 4355 }; 4356 4357 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4358 /// increment expression in case its Loop is L. If it is not L then 4359 /// use AddRec itself. 4360 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4361 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4362 public: 4363 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4364 SCEVPostIncRewriter Rewriter(L, SE); 4365 const SCEV *Result = Rewriter.visit(S); 4366 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4367 ? SE.getCouldNotCompute() 4368 : Result; 4369 } 4370 4371 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4372 if (!SE.isLoopInvariant(Expr, L)) 4373 SeenLoopVariantSCEVUnknown = true; 4374 return Expr; 4375 } 4376 4377 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4378 // Only re-write AddRecExprs for this loop. 4379 if (Expr->getLoop() == L) 4380 return Expr->getPostIncExpr(SE); 4381 SeenOtherLoops = true; 4382 return Expr; 4383 } 4384 4385 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4386 4387 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4388 4389 private: 4390 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4391 : SCEVRewriteVisitor(SE), L(L) {} 4392 4393 const Loop *L; 4394 bool SeenLoopVariantSCEVUnknown = false; 4395 bool SeenOtherLoops = false; 4396 }; 4397 4398 /// This class evaluates the compare condition by matching it against the 4399 /// condition of loop latch. If there is a match we assume a true value 4400 /// for the condition while building SCEV nodes. 4401 class SCEVBackedgeConditionFolder 4402 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4403 public: 4404 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4405 ScalarEvolution &SE) { 4406 bool IsPosBECond = false; 4407 Value *BECond = nullptr; 4408 if (BasicBlock *Latch = L->getLoopLatch()) { 4409 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4410 if (BI && BI->isConditional()) { 4411 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4412 "Both outgoing branches should not target same header!"); 4413 BECond = BI->getCondition(); 4414 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4415 } else { 4416 return S; 4417 } 4418 } 4419 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4420 return Rewriter.visit(S); 4421 } 4422 4423 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4424 const SCEV *Result = Expr; 4425 bool InvariantF = SE.isLoopInvariant(Expr, L); 4426 4427 if (!InvariantF) { 4428 Instruction *I = cast<Instruction>(Expr->getValue()); 4429 switch (I->getOpcode()) { 4430 case Instruction::Select: { 4431 SelectInst *SI = cast<SelectInst>(I); 4432 Optional<const SCEV *> Res = 4433 compareWithBackedgeCondition(SI->getCondition()); 4434 if (Res.hasValue()) { 4435 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4436 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4437 } 4438 break; 4439 } 4440 default: { 4441 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4442 if (Res.hasValue()) 4443 Result = Res.getValue(); 4444 break; 4445 } 4446 } 4447 } 4448 return Result; 4449 } 4450 4451 private: 4452 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4453 bool IsPosBECond, ScalarEvolution &SE) 4454 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4455 IsPositiveBECond(IsPosBECond) {} 4456 4457 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4458 4459 const Loop *L; 4460 /// Loop back condition. 4461 Value *BackedgeCond = nullptr; 4462 /// Set to true if loop back is on positive branch condition. 4463 bool IsPositiveBECond; 4464 }; 4465 4466 Optional<const SCEV *> 4467 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4468 4469 // If value matches the backedge condition for loop latch, 4470 // then return a constant evolution node based on loopback 4471 // branch taken. 4472 if (BackedgeCond == IC) 4473 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4474 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4475 return None; 4476 } 4477 4478 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4479 public: 4480 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4481 ScalarEvolution &SE) { 4482 SCEVShiftRewriter Rewriter(L, SE); 4483 const SCEV *Result = Rewriter.visit(S); 4484 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4485 } 4486 4487 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4488 // Only allow AddRecExprs for this loop. 4489 if (!SE.isLoopInvariant(Expr, L)) 4490 Valid = false; 4491 return Expr; 4492 } 4493 4494 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4495 if (Expr->getLoop() == L && Expr->isAffine()) 4496 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4497 Valid = false; 4498 return Expr; 4499 } 4500 4501 bool isValid() { return Valid; } 4502 4503 private: 4504 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4505 : SCEVRewriteVisitor(SE), L(L) {} 4506 4507 const Loop *L; 4508 bool Valid = true; 4509 }; 4510 4511 } // end anonymous namespace 4512 4513 SCEV::NoWrapFlags 4514 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4515 if (!AR->isAffine()) 4516 return SCEV::FlagAnyWrap; 4517 4518 using OBO = OverflowingBinaryOperator; 4519 4520 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4521 4522 if (!AR->hasNoSignedWrap()) { 4523 ConstantRange AddRecRange = getSignedRange(AR); 4524 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4525 4526 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4527 Instruction::Add, IncRange, OBO::NoSignedWrap); 4528 if (NSWRegion.contains(AddRecRange)) 4529 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4530 } 4531 4532 if (!AR->hasNoUnsignedWrap()) { 4533 ConstantRange AddRecRange = getUnsignedRange(AR); 4534 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4535 4536 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4537 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4538 if (NUWRegion.contains(AddRecRange)) 4539 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4540 } 4541 4542 return Result; 4543 } 4544 4545 SCEV::NoWrapFlags 4546 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4547 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4548 4549 if (AR->hasNoSignedWrap()) 4550 return Result; 4551 4552 if (!AR->isAffine()) 4553 return Result; 4554 4555 const SCEV *Step = AR->getStepRecurrence(*this); 4556 const Loop *L = AR->getLoop(); 4557 4558 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4559 // Note that this serves two purposes: It filters out loops that are 4560 // simply not analyzable, and it covers the case where this code is 4561 // being called from within backedge-taken count analysis, such that 4562 // attempting to ask for the backedge-taken count would likely result 4563 // in infinite recursion. In the later case, the analysis code will 4564 // cope with a conservative value, and it will take care to purge 4565 // that value once it has finished. 4566 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4567 4568 // Normally, in the cases we can prove no-overflow via a 4569 // backedge guarding condition, we can also compute a backedge 4570 // taken count for the loop. The exceptions are assumptions and 4571 // guards present in the loop -- SCEV is not great at exploiting 4572 // these to compute max backedge taken counts, but can still use 4573 // these to prove lack of overflow. Use this fact to avoid 4574 // doing extra work that may not pay off. 4575 4576 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4577 AC.assumptions().empty()) 4578 return Result; 4579 4580 // If the backedge is guarded by a comparison with the pre-inc value the 4581 // addrec is safe. Also, if the entry is guarded by a comparison with the 4582 // start value and the backedge is guarded by a comparison with the post-inc 4583 // value, the addrec is safe. 4584 ICmpInst::Predicate Pred; 4585 const SCEV *OverflowLimit = 4586 getSignedOverflowLimitForStep(Step, &Pred, this); 4587 if (OverflowLimit && 4588 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4589 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4590 Result = setFlags(Result, SCEV::FlagNSW); 4591 } 4592 return Result; 4593 } 4594 SCEV::NoWrapFlags 4595 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4596 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4597 4598 if (AR->hasNoUnsignedWrap()) 4599 return Result; 4600 4601 if (!AR->isAffine()) 4602 return Result; 4603 4604 const SCEV *Step = AR->getStepRecurrence(*this); 4605 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4606 const Loop *L = AR->getLoop(); 4607 4608 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4609 // Note that this serves two purposes: It filters out loops that are 4610 // simply not analyzable, and it covers the case where this code is 4611 // being called from within backedge-taken count analysis, such that 4612 // attempting to ask for the backedge-taken count would likely result 4613 // in infinite recursion. In the later case, the analysis code will 4614 // cope with a conservative value, and it will take care to purge 4615 // that value once it has finished. 4616 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4617 4618 // Normally, in the cases we can prove no-overflow via a 4619 // backedge guarding condition, we can also compute a backedge 4620 // taken count for the loop. The exceptions are assumptions and 4621 // guards present in the loop -- SCEV is not great at exploiting 4622 // these to compute max backedge taken counts, but can still use 4623 // these to prove lack of overflow. Use this fact to avoid 4624 // doing extra work that may not pay off. 4625 4626 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4627 AC.assumptions().empty()) 4628 return Result; 4629 4630 // If the backedge is guarded by a comparison with the pre-inc value the 4631 // addrec is safe. Also, if the entry is guarded by a comparison with the 4632 // start value and the backedge is guarded by a comparison with the post-inc 4633 // value, the addrec is safe. 4634 if (isKnownPositive(Step)) { 4635 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4636 getUnsignedRangeMax(Step)); 4637 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4638 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4639 Result = setFlags(Result, SCEV::FlagNUW); 4640 } 4641 } 4642 4643 return Result; 4644 } 4645 4646 namespace { 4647 4648 /// Represents an abstract binary operation. This may exist as a 4649 /// normal instruction or constant expression, or may have been 4650 /// derived from an expression tree. 4651 struct BinaryOp { 4652 unsigned Opcode; 4653 Value *LHS; 4654 Value *RHS; 4655 bool IsNSW = false; 4656 bool IsNUW = false; 4657 4658 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4659 /// constant expression. 4660 Operator *Op = nullptr; 4661 4662 explicit BinaryOp(Operator *Op) 4663 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4664 Op(Op) { 4665 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4666 IsNSW = OBO->hasNoSignedWrap(); 4667 IsNUW = OBO->hasNoUnsignedWrap(); 4668 } 4669 } 4670 4671 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4672 bool IsNUW = false) 4673 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4674 }; 4675 4676 } // end anonymous namespace 4677 4678 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4679 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4680 auto *Op = dyn_cast<Operator>(V); 4681 if (!Op) 4682 return None; 4683 4684 // Implementation detail: all the cleverness here should happen without 4685 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4686 // SCEV expressions when possible, and we should not break that. 4687 4688 switch (Op->getOpcode()) { 4689 case Instruction::Add: 4690 case Instruction::Sub: 4691 case Instruction::Mul: 4692 case Instruction::UDiv: 4693 case Instruction::URem: 4694 case Instruction::And: 4695 case Instruction::Or: 4696 case Instruction::AShr: 4697 case Instruction::Shl: 4698 return BinaryOp(Op); 4699 4700 case Instruction::Xor: 4701 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4702 // If the RHS of the xor is a signmask, then this is just an add. 4703 // Instcombine turns add of signmask into xor as a strength reduction step. 4704 if (RHSC->getValue().isSignMask()) 4705 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4706 return BinaryOp(Op); 4707 4708 case Instruction::LShr: 4709 // Turn logical shift right of a constant into a unsigned divide. 4710 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4711 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4712 4713 // If the shift count is not less than the bitwidth, the result of 4714 // the shift is undefined. Don't try to analyze it, because the 4715 // resolution chosen here may differ from the resolution chosen in 4716 // other parts of the compiler. 4717 if (SA->getValue().ult(BitWidth)) { 4718 Constant *X = 4719 ConstantInt::get(SA->getContext(), 4720 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4721 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4722 } 4723 } 4724 return BinaryOp(Op); 4725 4726 case Instruction::ExtractValue: { 4727 auto *EVI = cast<ExtractValueInst>(Op); 4728 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4729 break; 4730 4731 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4732 if (!WO) 4733 break; 4734 4735 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4736 bool Signed = WO->isSigned(); 4737 // TODO: Should add nuw/nsw flags for mul as well. 4738 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4739 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4740 4741 // Now that we know that all uses of the arithmetic-result component of 4742 // CI are guarded by the overflow check, we can go ahead and pretend 4743 // that the arithmetic is non-overflowing. 4744 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4745 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4746 } 4747 4748 default: 4749 break; 4750 } 4751 4752 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4753 // semantics as a Sub, return a binary sub expression. 4754 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4755 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4756 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4757 4758 return None; 4759 } 4760 4761 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4762 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4763 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4764 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4765 /// follows one of the following patterns: 4766 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4767 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4768 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4769 /// we return the type of the truncation operation, and indicate whether the 4770 /// truncated type should be treated as signed/unsigned by setting 4771 /// \p Signed to true/false, respectively. 4772 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4773 bool &Signed, ScalarEvolution &SE) { 4774 // The case where Op == SymbolicPHI (that is, with no type conversions on 4775 // the way) is handled by the regular add recurrence creating logic and 4776 // would have already been triggered in createAddRecForPHI. Reaching it here 4777 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4778 // because one of the other operands of the SCEVAddExpr updating this PHI is 4779 // not invariant). 4780 // 4781 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4782 // this case predicates that allow us to prove that Op == SymbolicPHI will 4783 // be added. 4784 if (Op == SymbolicPHI) 4785 return nullptr; 4786 4787 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4788 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4789 if (SourceBits != NewBits) 4790 return nullptr; 4791 4792 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4793 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4794 if (!SExt && !ZExt) 4795 return nullptr; 4796 const SCEVTruncateExpr *Trunc = 4797 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4798 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4799 if (!Trunc) 4800 return nullptr; 4801 const SCEV *X = Trunc->getOperand(); 4802 if (X != SymbolicPHI) 4803 return nullptr; 4804 Signed = SExt != nullptr; 4805 return Trunc->getType(); 4806 } 4807 4808 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4809 if (!PN->getType()->isIntegerTy()) 4810 return nullptr; 4811 const Loop *L = LI.getLoopFor(PN->getParent()); 4812 if (!L || L->getHeader() != PN->getParent()) 4813 return nullptr; 4814 return L; 4815 } 4816 4817 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4818 // computation that updates the phi follows the following pattern: 4819 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4820 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4821 // If so, try to see if it can be rewritten as an AddRecExpr under some 4822 // Predicates. If successful, return them as a pair. Also cache the results 4823 // of the analysis. 4824 // 4825 // Example usage scenario: 4826 // Say the Rewriter is called for the following SCEV: 4827 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4828 // where: 4829 // %X = phi i64 (%Start, %BEValue) 4830 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4831 // and call this function with %SymbolicPHI = %X. 4832 // 4833 // The analysis will find that the value coming around the backedge has 4834 // the following SCEV: 4835 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4836 // Upon concluding that this matches the desired pattern, the function 4837 // will return the pair {NewAddRec, SmallPredsVec} where: 4838 // NewAddRec = {%Start,+,%Step} 4839 // SmallPredsVec = {P1, P2, P3} as follows: 4840 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4841 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4842 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4843 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4844 // under the predicates {P1,P2,P3}. 4845 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4846 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4847 // 4848 // TODO's: 4849 // 4850 // 1) Extend the Induction descriptor to also support inductions that involve 4851 // casts: When needed (namely, when we are called in the context of the 4852 // vectorizer induction analysis), a Set of cast instructions will be 4853 // populated by this method, and provided back to isInductionPHI. This is 4854 // needed to allow the vectorizer to properly record them to be ignored by 4855 // the cost model and to avoid vectorizing them (otherwise these casts, 4856 // which are redundant under the runtime overflow checks, will be 4857 // vectorized, which can be costly). 4858 // 4859 // 2) Support additional induction/PHISCEV patterns: We also want to support 4860 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4861 // after the induction update operation (the induction increment): 4862 // 4863 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4864 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4865 // 4866 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4867 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4868 // 4869 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4870 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4871 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4872 SmallVector<const SCEVPredicate *, 3> Predicates; 4873 4874 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4875 // return an AddRec expression under some predicate. 4876 4877 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4878 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4879 assert(L && "Expecting an integer loop header phi"); 4880 4881 // The loop may have multiple entrances or multiple exits; we can analyze 4882 // this phi as an addrec if it has a unique entry value and a unique 4883 // backedge value. 4884 Value *BEValueV = nullptr, *StartValueV = nullptr; 4885 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4886 Value *V = PN->getIncomingValue(i); 4887 if (L->contains(PN->getIncomingBlock(i))) { 4888 if (!BEValueV) { 4889 BEValueV = V; 4890 } else if (BEValueV != V) { 4891 BEValueV = nullptr; 4892 break; 4893 } 4894 } else if (!StartValueV) { 4895 StartValueV = V; 4896 } else if (StartValueV != V) { 4897 StartValueV = nullptr; 4898 break; 4899 } 4900 } 4901 if (!BEValueV || !StartValueV) 4902 return None; 4903 4904 const SCEV *BEValue = getSCEV(BEValueV); 4905 4906 // If the value coming around the backedge is an add with the symbolic 4907 // value we just inserted, possibly with casts that we can ignore under 4908 // an appropriate runtime guard, then we found a simple induction variable! 4909 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4910 if (!Add) 4911 return None; 4912 4913 // If there is a single occurrence of the symbolic value, possibly 4914 // casted, replace it with a recurrence. 4915 unsigned FoundIndex = Add->getNumOperands(); 4916 Type *TruncTy = nullptr; 4917 bool Signed; 4918 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4919 if ((TruncTy = 4920 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4921 if (FoundIndex == e) { 4922 FoundIndex = i; 4923 break; 4924 } 4925 4926 if (FoundIndex == Add->getNumOperands()) 4927 return None; 4928 4929 // Create an add with everything but the specified operand. 4930 SmallVector<const SCEV *, 8> Ops; 4931 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4932 if (i != FoundIndex) 4933 Ops.push_back(Add->getOperand(i)); 4934 const SCEV *Accum = getAddExpr(Ops); 4935 4936 // The runtime checks will not be valid if the step amount is 4937 // varying inside the loop. 4938 if (!isLoopInvariant(Accum, L)) 4939 return None; 4940 4941 // *** Part2: Create the predicates 4942 4943 // Analysis was successful: we have a phi-with-cast pattern for which we 4944 // can return an AddRec expression under the following predicates: 4945 // 4946 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4947 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4948 // P2: An Equal predicate that guarantees that 4949 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4950 // P3: An Equal predicate that guarantees that 4951 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4952 // 4953 // As we next prove, the above predicates guarantee that: 4954 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4955 // 4956 // 4957 // More formally, we want to prove that: 4958 // Expr(i+1) = Start + (i+1) * Accum 4959 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4960 // 4961 // Given that: 4962 // 1) Expr(0) = Start 4963 // 2) Expr(1) = Start + Accum 4964 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4965 // 3) Induction hypothesis (step i): 4966 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4967 // 4968 // Proof: 4969 // Expr(i+1) = 4970 // = Start + (i+1)*Accum 4971 // = (Start + i*Accum) + Accum 4972 // = Expr(i) + Accum 4973 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4974 // :: from step i 4975 // 4976 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4977 // 4978 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4979 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4980 // + Accum :: from P3 4981 // 4982 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4983 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4984 // 4985 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4986 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4987 // 4988 // By induction, the same applies to all iterations 1<=i<n: 4989 // 4990 4991 // Create a truncated addrec for which we will add a no overflow check (P1). 4992 const SCEV *StartVal = getSCEV(StartValueV); 4993 const SCEV *PHISCEV = 4994 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4995 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4996 4997 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4998 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4999 // will be constant. 5000 // 5001 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5002 // add P1. 5003 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5004 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5005 Signed ? SCEVWrapPredicate::IncrementNSSW 5006 : SCEVWrapPredicate::IncrementNUSW; 5007 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5008 Predicates.push_back(AddRecPred); 5009 } 5010 5011 // Create the Equal Predicates P2,P3: 5012 5013 // It is possible that the predicates P2 and/or P3 are computable at 5014 // compile time due to StartVal and/or Accum being constants. 5015 // If either one is, then we can check that now and escape if either P2 5016 // or P3 is false. 5017 5018 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5019 // for each of StartVal and Accum 5020 auto getExtendedExpr = [&](const SCEV *Expr, 5021 bool CreateSignExtend) -> const SCEV * { 5022 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5023 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5024 const SCEV *ExtendedExpr = 5025 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5026 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5027 return ExtendedExpr; 5028 }; 5029 5030 // Given: 5031 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5032 // = getExtendedExpr(Expr) 5033 // Determine whether the predicate P: Expr == ExtendedExpr 5034 // is known to be false at compile time 5035 auto PredIsKnownFalse = [&](const SCEV *Expr, 5036 const SCEV *ExtendedExpr) -> bool { 5037 return Expr != ExtendedExpr && 5038 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5039 }; 5040 5041 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5042 if (PredIsKnownFalse(StartVal, StartExtended)) { 5043 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5044 return None; 5045 } 5046 5047 // The Step is always Signed (because the overflow checks are either 5048 // NSSW or NUSW) 5049 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5050 if (PredIsKnownFalse(Accum, AccumExtended)) { 5051 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5052 return None; 5053 } 5054 5055 auto AppendPredicate = [&](const SCEV *Expr, 5056 const SCEV *ExtendedExpr) -> void { 5057 if (Expr != ExtendedExpr && 5058 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5059 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5060 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5061 Predicates.push_back(Pred); 5062 } 5063 }; 5064 5065 AppendPredicate(StartVal, StartExtended); 5066 AppendPredicate(Accum, AccumExtended); 5067 5068 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5069 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5070 // into NewAR if it will also add the runtime overflow checks specified in 5071 // Predicates. 5072 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5073 5074 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5075 std::make_pair(NewAR, Predicates); 5076 // Remember the result of the analysis for this SCEV at this locayyytion. 5077 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5078 return PredRewrite; 5079 } 5080 5081 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5082 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5083 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5084 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5085 if (!L) 5086 return None; 5087 5088 // Check to see if we already analyzed this PHI. 5089 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5090 if (I != PredicatedSCEVRewrites.end()) { 5091 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5092 I->second; 5093 // Analysis was done before and failed to create an AddRec: 5094 if (Rewrite.first == SymbolicPHI) 5095 return None; 5096 // Analysis was done before and succeeded to create an AddRec under 5097 // a predicate: 5098 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5099 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5100 return Rewrite; 5101 } 5102 5103 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5104 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5105 5106 // Record in the cache that the analysis failed 5107 if (!Rewrite) { 5108 SmallVector<const SCEVPredicate *, 3> Predicates; 5109 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5110 return None; 5111 } 5112 5113 return Rewrite; 5114 } 5115 5116 // FIXME: This utility is currently required because the Rewriter currently 5117 // does not rewrite this expression: 5118 // {0, +, (sext ix (trunc iy to ix) to iy)} 5119 // into {0, +, %step}, 5120 // even when the following Equal predicate exists: 5121 // "%step == (sext ix (trunc iy to ix) to iy)". 5122 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5123 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5124 if (AR1 == AR2) 5125 return true; 5126 5127 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5128 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5129 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5130 return false; 5131 return true; 5132 }; 5133 5134 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5135 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5136 return false; 5137 return true; 5138 } 5139 5140 /// A helper function for createAddRecFromPHI to handle simple cases. 5141 /// 5142 /// This function tries to find an AddRec expression for the simplest (yet most 5143 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5144 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5145 /// technique for finding the AddRec expression. 5146 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5147 Value *BEValueV, 5148 Value *StartValueV) { 5149 const Loop *L = LI.getLoopFor(PN->getParent()); 5150 assert(L && L->getHeader() == PN->getParent()); 5151 assert(BEValueV && StartValueV); 5152 5153 auto BO = MatchBinaryOp(BEValueV, DT); 5154 if (!BO) 5155 return nullptr; 5156 5157 if (BO->Opcode != Instruction::Add) 5158 return nullptr; 5159 5160 const SCEV *Accum = nullptr; 5161 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5162 Accum = getSCEV(BO->RHS); 5163 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5164 Accum = getSCEV(BO->LHS); 5165 5166 if (!Accum) 5167 return nullptr; 5168 5169 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5170 if (BO->IsNUW) 5171 Flags = setFlags(Flags, SCEV::FlagNUW); 5172 if (BO->IsNSW) 5173 Flags = setFlags(Flags, SCEV::FlagNSW); 5174 5175 const SCEV *StartVal = getSCEV(StartValueV); 5176 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5177 5178 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5179 5180 // We can add Flags to the post-inc expression only if we 5181 // know that it is *undefined behavior* for BEValueV to 5182 // overflow. 5183 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5184 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5185 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5186 5187 return PHISCEV; 5188 } 5189 5190 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5191 const Loop *L = LI.getLoopFor(PN->getParent()); 5192 if (!L || L->getHeader() != PN->getParent()) 5193 return nullptr; 5194 5195 // The loop may have multiple entrances or multiple exits; we can analyze 5196 // this phi as an addrec if it has a unique entry value and a unique 5197 // backedge value. 5198 Value *BEValueV = nullptr, *StartValueV = nullptr; 5199 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5200 Value *V = PN->getIncomingValue(i); 5201 if (L->contains(PN->getIncomingBlock(i))) { 5202 if (!BEValueV) { 5203 BEValueV = V; 5204 } else if (BEValueV != V) { 5205 BEValueV = nullptr; 5206 break; 5207 } 5208 } else if (!StartValueV) { 5209 StartValueV = V; 5210 } else if (StartValueV != V) { 5211 StartValueV = nullptr; 5212 break; 5213 } 5214 } 5215 if (!BEValueV || !StartValueV) 5216 return nullptr; 5217 5218 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5219 "PHI node already processed?"); 5220 5221 // First, try to find AddRec expression without creating a fictituos symbolic 5222 // value for PN. 5223 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5224 return S; 5225 5226 // Handle PHI node value symbolically. 5227 const SCEV *SymbolicName = getUnknown(PN); 5228 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5229 5230 // Using this symbolic name for the PHI, analyze the value coming around 5231 // the back-edge. 5232 const SCEV *BEValue = getSCEV(BEValueV); 5233 5234 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5235 // has a special value for the first iteration of the loop. 5236 5237 // If the value coming around the backedge is an add with the symbolic 5238 // value we just inserted, then we found a simple induction variable! 5239 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5240 // If there is a single occurrence of the symbolic value, replace it 5241 // with a recurrence. 5242 unsigned FoundIndex = Add->getNumOperands(); 5243 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5244 if (Add->getOperand(i) == SymbolicName) 5245 if (FoundIndex == e) { 5246 FoundIndex = i; 5247 break; 5248 } 5249 5250 if (FoundIndex != Add->getNumOperands()) { 5251 // Create an add with everything but the specified operand. 5252 SmallVector<const SCEV *, 8> Ops; 5253 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5254 if (i != FoundIndex) 5255 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5256 L, *this)); 5257 const SCEV *Accum = getAddExpr(Ops); 5258 5259 // This is not a valid addrec if the step amount is varying each 5260 // loop iteration, but is not itself an addrec in this loop. 5261 if (isLoopInvariant(Accum, L) || 5262 (isa<SCEVAddRecExpr>(Accum) && 5263 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5264 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5265 5266 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5267 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5268 if (BO->IsNUW) 5269 Flags = setFlags(Flags, SCEV::FlagNUW); 5270 if (BO->IsNSW) 5271 Flags = setFlags(Flags, SCEV::FlagNSW); 5272 } 5273 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5274 // If the increment is an inbounds GEP, then we know the address 5275 // space cannot be wrapped around. We cannot make any guarantee 5276 // about signed or unsigned overflow because pointers are 5277 // unsigned but we may have a negative index from the base 5278 // pointer. We can guarantee that no unsigned wrap occurs if the 5279 // indices form a positive value. 5280 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5281 Flags = setFlags(Flags, SCEV::FlagNW); 5282 5283 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5284 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5285 Flags = setFlags(Flags, SCEV::FlagNUW); 5286 } 5287 5288 // We cannot transfer nuw and nsw flags from subtraction 5289 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5290 // for instance. 5291 } 5292 5293 const SCEV *StartVal = getSCEV(StartValueV); 5294 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5295 5296 // Okay, for the entire analysis of this edge we assumed the PHI 5297 // to be symbolic. We now need to go back and purge all of the 5298 // entries for the scalars that use the symbolic expression. 5299 forgetSymbolicName(PN, SymbolicName); 5300 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5301 5302 // We can add Flags to the post-inc expression only if we 5303 // know that it is *undefined behavior* for BEValueV to 5304 // overflow. 5305 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5306 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5307 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5308 5309 return PHISCEV; 5310 } 5311 } 5312 } else { 5313 // Otherwise, this could be a loop like this: 5314 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5315 // In this case, j = {1,+,1} and BEValue is j. 5316 // Because the other in-value of i (0) fits the evolution of BEValue 5317 // i really is an addrec evolution. 5318 // 5319 // We can generalize this saying that i is the shifted value of BEValue 5320 // by one iteration: 5321 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5322 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5323 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5324 if (Shifted != getCouldNotCompute() && 5325 Start != getCouldNotCompute()) { 5326 const SCEV *StartVal = getSCEV(StartValueV); 5327 if (Start == StartVal) { 5328 // Okay, for the entire analysis of this edge we assumed the PHI 5329 // to be symbolic. We now need to go back and purge all of the 5330 // entries for the scalars that use the symbolic expression. 5331 forgetSymbolicName(PN, SymbolicName); 5332 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5333 return Shifted; 5334 } 5335 } 5336 } 5337 5338 // Remove the temporary PHI node SCEV that has been inserted while intending 5339 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5340 // as it will prevent later (possibly simpler) SCEV expressions to be added 5341 // to the ValueExprMap. 5342 eraseValueFromMap(PN); 5343 5344 return nullptr; 5345 } 5346 5347 // Checks if the SCEV S is available at BB. S is considered available at BB 5348 // if S can be materialized at BB without introducing a fault. 5349 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5350 BasicBlock *BB) { 5351 struct CheckAvailable { 5352 bool TraversalDone = false; 5353 bool Available = true; 5354 5355 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5356 BasicBlock *BB = nullptr; 5357 DominatorTree &DT; 5358 5359 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5360 : L(L), BB(BB), DT(DT) {} 5361 5362 bool setUnavailable() { 5363 TraversalDone = true; 5364 Available = false; 5365 return false; 5366 } 5367 5368 bool follow(const SCEV *S) { 5369 switch (S->getSCEVType()) { 5370 case scConstant: 5371 case scPtrToInt: 5372 case scTruncate: 5373 case scZeroExtend: 5374 case scSignExtend: 5375 case scAddExpr: 5376 case scMulExpr: 5377 case scUMaxExpr: 5378 case scSMaxExpr: 5379 case scUMinExpr: 5380 case scSMinExpr: 5381 // These expressions are available if their operand(s) is/are. 5382 return true; 5383 5384 case scAddRecExpr: { 5385 // We allow add recurrences that are on the loop BB is in, or some 5386 // outer loop. This guarantees availability because the value of the 5387 // add recurrence at BB is simply the "current" value of the induction 5388 // variable. We can relax this in the future; for instance an add 5389 // recurrence on a sibling dominating loop is also available at BB. 5390 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5391 if (L && (ARLoop == L || ARLoop->contains(L))) 5392 return true; 5393 5394 return setUnavailable(); 5395 } 5396 5397 case scUnknown: { 5398 // For SCEVUnknown, we check for simple dominance. 5399 const auto *SU = cast<SCEVUnknown>(S); 5400 Value *V = SU->getValue(); 5401 5402 if (isa<Argument>(V)) 5403 return false; 5404 5405 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5406 return false; 5407 5408 return setUnavailable(); 5409 } 5410 5411 case scUDivExpr: 5412 case scCouldNotCompute: 5413 // We do not try to smart about these at all. 5414 return setUnavailable(); 5415 } 5416 llvm_unreachable("Unknown SCEV kind!"); 5417 } 5418 5419 bool isDone() { return TraversalDone; } 5420 }; 5421 5422 CheckAvailable CA(L, BB, DT); 5423 SCEVTraversal<CheckAvailable> ST(CA); 5424 5425 ST.visitAll(S); 5426 return CA.Available; 5427 } 5428 5429 // Try to match a control flow sequence that branches out at BI and merges back 5430 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5431 // match. 5432 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5433 Value *&C, Value *&LHS, Value *&RHS) { 5434 C = BI->getCondition(); 5435 5436 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5437 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5438 5439 if (!LeftEdge.isSingleEdge()) 5440 return false; 5441 5442 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5443 5444 Use &LeftUse = Merge->getOperandUse(0); 5445 Use &RightUse = Merge->getOperandUse(1); 5446 5447 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5448 LHS = LeftUse; 5449 RHS = RightUse; 5450 return true; 5451 } 5452 5453 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5454 LHS = RightUse; 5455 RHS = LeftUse; 5456 return true; 5457 } 5458 5459 return false; 5460 } 5461 5462 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5463 auto IsReachable = 5464 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5465 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5466 const Loop *L = LI.getLoopFor(PN->getParent()); 5467 5468 // We don't want to break LCSSA, even in a SCEV expression tree. 5469 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5470 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5471 return nullptr; 5472 5473 // Try to match 5474 // 5475 // br %cond, label %left, label %right 5476 // left: 5477 // br label %merge 5478 // right: 5479 // br label %merge 5480 // merge: 5481 // V = phi [ %x, %left ], [ %y, %right ] 5482 // 5483 // as "select %cond, %x, %y" 5484 5485 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5486 assert(IDom && "At least the entry block should dominate PN"); 5487 5488 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5489 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5490 5491 if (BI && BI->isConditional() && 5492 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5493 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5494 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5495 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5496 } 5497 5498 return nullptr; 5499 } 5500 5501 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5502 if (const SCEV *S = createAddRecFromPHI(PN)) 5503 return S; 5504 5505 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5506 return S; 5507 5508 // If the PHI has a single incoming value, follow that value, unless the 5509 // PHI's incoming blocks are in a different loop, in which case doing so 5510 // risks breaking LCSSA form. Instcombine would normally zap these, but 5511 // it doesn't have DominatorTree information, so it may miss cases. 5512 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5513 if (LI.replacementPreservesLCSSAForm(PN, V)) 5514 return getSCEV(V); 5515 5516 // If it's not a loop phi, we can't handle it yet. 5517 return getUnknown(PN); 5518 } 5519 5520 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5521 Value *Cond, 5522 Value *TrueVal, 5523 Value *FalseVal) { 5524 // Handle "constant" branch or select. This can occur for instance when a 5525 // loop pass transforms an inner loop and moves on to process the outer loop. 5526 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5527 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5528 5529 // Try to match some simple smax or umax patterns. 5530 auto *ICI = dyn_cast<ICmpInst>(Cond); 5531 if (!ICI) 5532 return getUnknown(I); 5533 5534 Value *LHS = ICI->getOperand(0); 5535 Value *RHS = ICI->getOperand(1); 5536 5537 switch (ICI->getPredicate()) { 5538 case ICmpInst::ICMP_SLT: 5539 case ICmpInst::ICMP_SLE: 5540 std::swap(LHS, RHS); 5541 LLVM_FALLTHROUGH; 5542 case ICmpInst::ICMP_SGT: 5543 case ICmpInst::ICMP_SGE: 5544 // a >s b ? a+x : b+x -> smax(a, b)+x 5545 // a >s b ? b+x : a+x -> smin(a, b)+x 5546 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5547 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5548 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5549 const SCEV *LA = getSCEV(TrueVal); 5550 const SCEV *RA = getSCEV(FalseVal); 5551 const SCEV *LDiff = getMinusSCEV(LA, LS); 5552 const SCEV *RDiff = getMinusSCEV(RA, RS); 5553 if (LDiff == RDiff) 5554 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5555 LDiff = getMinusSCEV(LA, RS); 5556 RDiff = getMinusSCEV(RA, LS); 5557 if (LDiff == RDiff) 5558 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5559 } 5560 break; 5561 case ICmpInst::ICMP_ULT: 5562 case ICmpInst::ICMP_ULE: 5563 std::swap(LHS, RHS); 5564 LLVM_FALLTHROUGH; 5565 case ICmpInst::ICMP_UGT: 5566 case ICmpInst::ICMP_UGE: 5567 // a >u b ? a+x : b+x -> umax(a, b)+x 5568 // a >u b ? b+x : a+x -> umin(a, b)+x 5569 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5570 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5571 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5572 const SCEV *LA = getSCEV(TrueVal); 5573 const SCEV *RA = getSCEV(FalseVal); 5574 const SCEV *LDiff = getMinusSCEV(LA, LS); 5575 const SCEV *RDiff = getMinusSCEV(RA, RS); 5576 if (LDiff == RDiff) 5577 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5578 LDiff = getMinusSCEV(LA, RS); 5579 RDiff = getMinusSCEV(RA, LS); 5580 if (LDiff == RDiff) 5581 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5582 } 5583 break; 5584 case ICmpInst::ICMP_NE: 5585 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5586 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5587 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5588 const SCEV *One = getOne(I->getType()); 5589 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5590 const SCEV *LA = getSCEV(TrueVal); 5591 const SCEV *RA = getSCEV(FalseVal); 5592 const SCEV *LDiff = getMinusSCEV(LA, LS); 5593 const SCEV *RDiff = getMinusSCEV(RA, One); 5594 if (LDiff == RDiff) 5595 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5596 } 5597 break; 5598 case ICmpInst::ICMP_EQ: 5599 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5600 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5601 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5602 const SCEV *One = getOne(I->getType()); 5603 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5604 const SCEV *LA = getSCEV(TrueVal); 5605 const SCEV *RA = getSCEV(FalseVal); 5606 const SCEV *LDiff = getMinusSCEV(LA, One); 5607 const SCEV *RDiff = getMinusSCEV(RA, LS); 5608 if (LDiff == RDiff) 5609 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5610 } 5611 break; 5612 default: 5613 break; 5614 } 5615 5616 return getUnknown(I); 5617 } 5618 5619 /// Expand GEP instructions into add and multiply operations. This allows them 5620 /// to be analyzed by regular SCEV code. 5621 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5622 // Don't attempt to analyze GEPs over unsized objects. 5623 if (!GEP->getSourceElementType()->isSized()) 5624 return getUnknown(GEP); 5625 5626 SmallVector<const SCEV *, 4> IndexExprs; 5627 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5628 IndexExprs.push_back(getSCEV(*Index)); 5629 return getGEPExpr(GEP, IndexExprs); 5630 } 5631 5632 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5633 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5634 return C->getAPInt().countTrailingZeros(); 5635 5636 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5637 return GetMinTrailingZeros(I->getOperand()); 5638 5639 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5640 return std::min(GetMinTrailingZeros(T->getOperand()), 5641 (uint32_t)getTypeSizeInBits(T->getType())); 5642 5643 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5644 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5645 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5646 ? getTypeSizeInBits(E->getType()) 5647 : OpRes; 5648 } 5649 5650 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5651 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5652 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5653 ? getTypeSizeInBits(E->getType()) 5654 : OpRes; 5655 } 5656 5657 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5658 // The result is the min of all operands results. 5659 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5660 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5661 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5662 return MinOpRes; 5663 } 5664 5665 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5666 // The result is the sum of all operands results. 5667 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5668 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5669 for (unsigned i = 1, e = M->getNumOperands(); 5670 SumOpRes != BitWidth && i != e; ++i) 5671 SumOpRes = 5672 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5673 return SumOpRes; 5674 } 5675 5676 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5677 // The result is the min of all operands results. 5678 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5679 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5680 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5681 return MinOpRes; 5682 } 5683 5684 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5685 // The result is the min of all operands results. 5686 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5687 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5688 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5689 return MinOpRes; 5690 } 5691 5692 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5693 // The result is the min of all operands results. 5694 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5695 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5696 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5697 return MinOpRes; 5698 } 5699 5700 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5701 // For a SCEVUnknown, ask ValueTracking. 5702 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5703 return Known.countMinTrailingZeros(); 5704 } 5705 5706 // SCEVUDivExpr 5707 return 0; 5708 } 5709 5710 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5711 auto I = MinTrailingZerosCache.find(S); 5712 if (I != MinTrailingZerosCache.end()) 5713 return I->second; 5714 5715 uint32_t Result = GetMinTrailingZerosImpl(S); 5716 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5717 assert(InsertPair.second && "Should insert a new key"); 5718 return InsertPair.first->second; 5719 } 5720 5721 /// Helper method to assign a range to V from metadata present in the IR. 5722 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5723 if (Instruction *I = dyn_cast<Instruction>(V)) 5724 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5725 return getConstantRangeFromMetadata(*MD); 5726 5727 return None; 5728 } 5729 5730 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5731 SCEV::NoWrapFlags Flags) { 5732 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5733 AddRec->setNoWrapFlags(Flags); 5734 UnsignedRanges.erase(AddRec); 5735 SignedRanges.erase(AddRec); 5736 } 5737 } 5738 5739 ConstantRange ScalarEvolution:: 5740 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5741 const DataLayout &DL = getDataLayout(); 5742 5743 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5744 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5745 5746 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5747 // use information about the trip count to improve our available range. Note 5748 // that the trip count independent cases are already handled by known bits. 5749 // WARNING: The definition of recurrence used here is subtly different than 5750 // the one used by AddRec (and thus most of this file). Step is allowed to 5751 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5752 // and other addrecs in the same loop (for non-affine addrecs). The code 5753 // below intentionally handles the case where step is not loop invariant. 5754 auto *P = dyn_cast<PHINode>(U->getValue()); 5755 if (!P) 5756 return FullSet; 5757 5758 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5759 // even the values that are not available in these blocks may come from them, 5760 // and this leads to false-positive recurrence test. 5761 for (auto *Pred : predecessors(P->getParent())) 5762 if (!DT.isReachableFromEntry(Pred)) 5763 return FullSet; 5764 5765 BinaryOperator *BO; 5766 Value *Start, *Step; 5767 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5768 return FullSet; 5769 5770 // If we found a recurrence in reachable code, we must be in a loop. Note 5771 // that BO might be in some subloop of L, and that's completely okay. 5772 auto *L = LI.getLoopFor(P->getParent()); 5773 assert(L && L->getHeader() == P->getParent()); 5774 if (!L->contains(BO->getParent())) 5775 // NOTE: This bailout should be an assert instead. However, asserting 5776 // the condition here exposes a case where LoopFusion is querying SCEV 5777 // with malformed loop information during the midst of the transform. 5778 // There doesn't appear to be an obvious fix, so for the moment bailout 5779 // until the caller issue can be fixed. PR49566 tracks the bug. 5780 return FullSet; 5781 5782 // TODO: Extend to other opcodes such as mul, and div 5783 switch (BO->getOpcode()) { 5784 default: 5785 return FullSet; 5786 case Instruction::AShr: 5787 case Instruction::LShr: 5788 case Instruction::Shl: 5789 break; 5790 }; 5791 5792 if (BO->getOperand(0) != P) 5793 // TODO: Handle the power function forms some day. 5794 return FullSet; 5795 5796 unsigned TC = getSmallConstantMaxTripCount(L); 5797 if (!TC || TC >= BitWidth) 5798 return FullSet; 5799 5800 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5801 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5802 assert(KnownStart.getBitWidth() == BitWidth && 5803 KnownStep.getBitWidth() == BitWidth); 5804 5805 // Compute total shift amount, being careful of overflow and bitwidths. 5806 auto MaxShiftAmt = KnownStep.getMaxValue(); 5807 APInt TCAP(BitWidth, TC-1); 5808 bool Overflow = false; 5809 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5810 if (Overflow) 5811 return FullSet; 5812 5813 switch (BO->getOpcode()) { 5814 default: 5815 llvm_unreachable("filtered out above"); 5816 case Instruction::AShr: { 5817 // For each ashr, three cases: 5818 // shift = 0 => unchanged value 5819 // saturation => 0 or -1 5820 // other => a value closer to zero (of the same sign) 5821 // Thus, the end value is closer to zero than the start. 5822 auto KnownEnd = KnownBits::ashr(KnownStart, 5823 KnownBits::makeConstant(TotalShift)); 5824 if (KnownStart.isNonNegative()) 5825 // Analogous to lshr (simply not yet canonicalized) 5826 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5827 KnownStart.getMaxValue() + 1); 5828 if (KnownStart.isNegative()) 5829 // End >=u Start && End <=s Start 5830 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5831 KnownEnd.getMaxValue() + 1); 5832 break; 5833 } 5834 case Instruction::LShr: { 5835 // For each lshr, three cases: 5836 // shift = 0 => unchanged value 5837 // saturation => 0 5838 // other => a smaller positive number 5839 // Thus, the low end of the unsigned range is the last value produced. 5840 auto KnownEnd = KnownBits::lshr(KnownStart, 5841 KnownBits::makeConstant(TotalShift)); 5842 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5843 KnownStart.getMaxValue() + 1); 5844 } 5845 case Instruction::Shl: { 5846 // Iff no bits are shifted out, value increases on every shift. 5847 auto KnownEnd = KnownBits::shl(KnownStart, 5848 KnownBits::makeConstant(TotalShift)); 5849 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5850 return ConstantRange(KnownStart.getMinValue(), 5851 KnownEnd.getMaxValue() + 1); 5852 break; 5853 } 5854 }; 5855 return FullSet; 5856 } 5857 5858 /// Determine the range for a particular SCEV. If SignHint is 5859 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5860 /// with a "cleaner" unsigned (resp. signed) representation. 5861 const ConstantRange & 5862 ScalarEvolution::getRangeRef(const SCEV *S, 5863 ScalarEvolution::RangeSignHint SignHint) { 5864 DenseMap<const SCEV *, ConstantRange> &Cache = 5865 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5866 : SignedRanges; 5867 ConstantRange::PreferredRangeType RangeType = 5868 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5869 ? ConstantRange::Unsigned : ConstantRange::Signed; 5870 5871 // See if we've computed this range already. 5872 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5873 if (I != Cache.end()) 5874 return I->second; 5875 5876 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5877 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5878 5879 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5880 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5881 using OBO = OverflowingBinaryOperator; 5882 5883 // If the value has known zeros, the maximum value will have those known zeros 5884 // as well. 5885 uint32_t TZ = GetMinTrailingZeros(S); 5886 if (TZ != 0) { 5887 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5888 ConservativeResult = 5889 ConstantRange(APInt::getMinValue(BitWidth), 5890 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5891 else 5892 ConservativeResult = ConstantRange( 5893 APInt::getSignedMinValue(BitWidth), 5894 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5895 } 5896 5897 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5898 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5899 unsigned WrapType = OBO::AnyWrap; 5900 if (Add->hasNoSignedWrap()) 5901 WrapType |= OBO::NoSignedWrap; 5902 if (Add->hasNoUnsignedWrap()) 5903 WrapType |= OBO::NoUnsignedWrap; 5904 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5905 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5906 WrapType, RangeType); 5907 return setRange(Add, SignHint, 5908 ConservativeResult.intersectWith(X, RangeType)); 5909 } 5910 5911 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5912 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5913 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5914 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5915 return setRange(Mul, SignHint, 5916 ConservativeResult.intersectWith(X, RangeType)); 5917 } 5918 5919 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5920 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5921 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5922 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5923 return setRange(SMax, SignHint, 5924 ConservativeResult.intersectWith(X, RangeType)); 5925 } 5926 5927 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5928 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5929 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5930 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5931 return setRange(UMax, SignHint, 5932 ConservativeResult.intersectWith(X, RangeType)); 5933 } 5934 5935 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5936 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5937 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5938 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5939 return setRange(SMin, SignHint, 5940 ConservativeResult.intersectWith(X, RangeType)); 5941 } 5942 5943 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5944 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5945 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5946 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5947 return setRange(UMin, SignHint, 5948 ConservativeResult.intersectWith(X, RangeType)); 5949 } 5950 5951 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5952 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5953 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5954 return setRange(UDiv, SignHint, 5955 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5956 } 5957 5958 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5959 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5960 return setRange(ZExt, SignHint, 5961 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5962 RangeType)); 5963 } 5964 5965 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5966 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5967 return setRange(SExt, SignHint, 5968 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5969 RangeType)); 5970 } 5971 5972 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5973 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5974 return setRange(PtrToInt, SignHint, X); 5975 } 5976 5977 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5978 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5979 return setRange(Trunc, SignHint, 5980 ConservativeResult.intersectWith(X.truncate(BitWidth), 5981 RangeType)); 5982 } 5983 5984 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5985 // If there's no unsigned wrap, the value will never be less than its 5986 // initial value. 5987 if (AddRec->hasNoUnsignedWrap()) { 5988 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5989 if (!UnsignedMinValue.isNullValue()) 5990 ConservativeResult = ConservativeResult.intersectWith( 5991 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5992 } 5993 5994 // If there's no signed wrap, and all the operands except initial value have 5995 // the same sign or zero, the value won't ever be: 5996 // 1: smaller than initial value if operands are non negative, 5997 // 2: bigger than initial value if operands are non positive. 5998 // For both cases, value can not cross signed min/max boundary. 5999 if (AddRec->hasNoSignedWrap()) { 6000 bool AllNonNeg = true; 6001 bool AllNonPos = true; 6002 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6003 if (!isKnownNonNegative(AddRec->getOperand(i))) 6004 AllNonNeg = false; 6005 if (!isKnownNonPositive(AddRec->getOperand(i))) 6006 AllNonPos = false; 6007 } 6008 if (AllNonNeg) 6009 ConservativeResult = ConservativeResult.intersectWith( 6010 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6011 APInt::getSignedMinValue(BitWidth)), 6012 RangeType); 6013 else if (AllNonPos) 6014 ConservativeResult = ConservativeResult.intersectWith( 6015 ConstantRange::getNonEmpty( 6016 APInt::getSignedMinValue(BitWidth), 6017 getSignedRangeMax(AddRec->getStart()) + 1), 6018 RangeType); 6019 } 6020 6021 // TODO: non-affine addrec 6022 if (AddRec->isAffine()) { 6023 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6024 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6025 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6026 auto RangeFromAffine = getRangeForAffineAR( 6027 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6028 BitWidth); 6029 ConservativeResult = 6030 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6031 6032 auto RangeFromFactoring = getRangeViaFactoring( 6033 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6034 BitWidth); 6035 ConservativeResult = 6036 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6037 } 6038 6039 // Now try symbolic BE count and more powerful methods. 6040 if (UseExpensiveRangeSharpening) { 6041 const SCEV *SymbolicMaxBECount = 6042 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6043 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6044 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6045 AddRec->hasNoSelfWrap()) { 6046 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6047 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6048 ConservativeResult = 6049 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6050 } 6051 } 6052 } 6053 6054 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6055 } 6056 6057 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6058 6059 // Check if the IR explicitly contains !range metadata. 6060 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6061 if (MDRange.hasValue()) 6062 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6063 RangeType); 6064 6065 // Use facts about recurrences in the underlying IR. Note that add 6066 // recurrences are AddRecExprs and thus don't hit this path. This 6067 // primarily handles shift recurrences. 6068 auto CR = getRangeForUnknownRecurrence(U); 6069 ConservativeResult = ConservativeResult.intersectWith(CR); 6070 6071 // See if ValueTracking can give us a useful range. 6072 const DataLayout &DL = getDataLayout(); 6073 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6074 if (Known.getBitWidth() != BitWidth) 6075 Known = Known.zextOrTrunc(BitWidth); 6076 6077 // ValueTracking may be able to compute a tighter result for the number of 6078 // sign bits than for the value of those sign bits. 6079 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6080 if (U->getType()->isPointerTy()) { 6081 // If the pointer size is larger than the index size type, this can cause 6082 // NS to be larger than BitWidth. So compensate for this. 6083 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6084 int ptrIdxDiff = ptrSize - BitWidth; 6085 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6086 NS -= ptrIdxDiff; 6087 } 6088 6089 if (NS > 1) { 6090 // If we know any of the sign bits, we know all of the sign bits. 6091 if (!Known.Zero.getHiBits(NS).isNullValue()) 6092 Known.Zero.setHighBits(NS); 6093 if (!Known.One.getHiBits(NS).isNullValue()) 6094 Known.One.setHighBits(NS); 6095 } 6096 6097 if (Known.getMinValue() != Known.getMaxValue() + 1) 6098 ConservativeResult = ConservativeResult.intersectWith( 6099 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6100 RangeType); 6101 if (NS > 1) 6102 ConservativeResult = ConservativeResult.intersectWith( 6103 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6104 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6105 RangeType); 6106 6107 // A range of Phi is a subset of union of all ranges of its input. 6108 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6109 // Make sure that we do not run over cycled Phis. 6110 if (PendingPhiRanges.insert(Phi).second) { 6111 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6112 for (auto &Op : Phi->operands()) { 6113 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6114 RangeFromOps = RangeFromOps.unionWith(OpRange); 6115 // No point to continue if we already have a full set. 6116 if (RangeFromOps.isFullSet()) 6117 break; 6118 } 6119 ConservativeResult = 6120 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6121 bool Erased = PendingPhiRanges.erase(Phi); 6122 assert(Erased && "Failed to erase Phi properly?"); 6123 (void) Erased; 6124 } 6125 } 6126 6127 return setRange(U, SignHint, std::move(ConservativeResult)); 6128 } 6129 6130 return setRange(S, SignHint, std::move(ConservativeResult)); 6131 } 6132 6133 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6134 // values that the expression can take. Initially, the expression has a value 6135 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6136 // argument defines if we treat Step as signed or unsigned. 6137 static ConstantRange getRangeForAffineARHelper(APInt Step, 6138 const ConstantRange &StartRange, 6139 const APInt &MaxBECount, 6140 unsigned BitWidth, bool Signed) { 6141 // If either Step or MaxBECount is 0, then the expression won't change, and we 6142 // just need to return the initial range. 6143 if (Step == 0 || MaxBECount == 0) 6144 return StartRange; 6145 6146 // If we don't know anything about the initial value (i.e. StartRange is 6147 // FullRange), then we don't know anything about the final range either. 6148 // Return FullRange. 6149 if (StartRange.isFullSet()) 6150 return ConstantRange::getFull(BitWidth); 6151 6152 // If Step is signed and negative, then we use its absolute value, but we also 6153 // note that we're moving in the opposite direction. 6154 bool Descending = Signed && Step.isNegative(); 6155 6156 if (Signed) 6157 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6158 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6159 // This equations hold true due to the well-defined wrap-around behavior of 6160 // APInt. 6161 Step = Step.abs(); 6162 6163 // Check if Offset is more than full span of BitWidth. If it is, the 6164 // expression is guaranteed to overflow. 6165 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6166 return ConstantRange::getFull(BitWidth); 6167 6168 // Offset is by how much the expression can change. Checks above guarantee no 6169 // overflow here. 6170 APInt Offset = Step * MaxBECount; 6171 6172 // Minimum value of the final range will match the minimal value of StartRange 6173 // if the expression is increasing and will be decreased by Offset otherwise. 6174 // Maximum value of the final range will match the maximal value of StartRange 6175 // if the expression is decreasing and will be increased by Offset otherwise. 6176 APInt StartLower = StartRange.getLower(); 6177 APInt StartUpper = StartRange.getUpper() - 1; 6178 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6179 : (StartUpper + std::move(Offset)); 6180 6181 // It's possible that the new minimum/maximum value will fall into the initial 6182 // range (due to wrap around). This means that the expression can take any 6183 // value in this bitwidth, and we have to return full range. 6184 if (StartRange.contains(MovedBoundary)) 6185 return ConstantRange::getFull(BitWidth); 6186 6187 APInt NewLower = 6188 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6189 APInt NewUpper = 6190 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6191 NewUpper += 1; 6192 6193 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6194 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6195 } 6196 6197 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6198 const SCEV *Step, 6199 const SCEV *MaxBECount, 6200 unsigned BitWidth) { 6201 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6202 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6203 "Precondition!"); 6204 6205 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6206 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6207 6208 // First, consider step signed. 6209 ConstantRange StartSRange = getSignedRange(Start); 6210 ConstantRange StepSRange = getSignedRange(Step); 6211 6212 // If Step can be both positive and negative, we need to find ranges for the 6213 // maximum absolute step values in both directions and union them. 6214 ConstantRange SR = 6215 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6216 MaxBECountValue, BitWidth, /* Signed = */ true); 6217 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6218 StartSRange, MaxBECountValue, 6219 BitWidth, /* Signed = */ true)); 6220 6221 // Next, consider step unsigned. 6222 ConstantRange UR = getRangeForAffineARHelper( 6223 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6224 MaxBECountValue, BitWidth, /* Signed = */ false); 6225 6226 // Finally, intersect signed and unsigned ranges. 6227 return SR.intersectWith(UR, ConstantRange::Smallest); 6228 } 6229 6230 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6231 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6232 ScalarEvolution::RangeSignHint SignHint) { 6233 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6234 assert(AddRec->hasNoSelfWrap() && 6235 "This only works for non-self-wrapping AddRecs!"); 6236 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6237 const SCEV *Step = AddRec->getStepRecurrence(*this); 6238 // Only deal with constant step to save compile time. 6239 if (!isa<SCEVConstant>(Step)) 6240 return ConstantRange::getFull(BitWidth); 6241 // Let's make sure that we can prove that we do not self-wrap during 6242 // MaxBECount iterations. We need this because MaxBECount is a maximum 6243 // iteration count estimate, and we might infer nw from some exit for which we 6244 // do not know max exit count (or any other side reasoning). 6245 // TODO: Turn into assert at some point. 6246 if (getTypeSizeInBits(MaxBECount->getType()) > 6247 getTypeSizeInBits(AddRec->getType())) 6248 return ConstantRange::getFull(BitWidth); 6249 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6250 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6251 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6252 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6253 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6254 MaxItersWithoutWrap)) 6255 return ConstantRange::getFull(BitWidth); 6256 6257 ICmpInst::Predicate LEPred = 6258 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6259 ICmpInst::Predicate GEPred = 6260 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6261 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6262 6263 // We know that there is no self-wrap. Let's take Start and End values and 6264 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6265 // the iteration. They either lie inside the range [Min(Start, End), 6266 // Max(Start, End)] or outside it: 6267 // 6268 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6269 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6270 // 6271 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6272 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6273 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6274 // Start <= End and step is positive, or Start >= End and step is negative. 6275 const SCEV *Start = AddRec->getStart(); 6276 ConstantRange StartRange = getRangeRef(Start, SignHint); 6277 ConstantRange EndRange = getRangeRef(End, SignHint); 6278 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6279 // If they already cover full iteration space, we will know nothing useful 6280 // even if we prove what we want to prove. 6281 if (RangeBetween.isFullSet()) 6282 return RangeBetween; 6283 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6284 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6285 : RangeBetween.isWrappedSet(); 6286 if (IsWrappedSet) 6287 return ConstantRange::getFull(BitWidth); 6288 6289 if (isKnownPositive(Step) && 6290 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6291 return RangeBetween; 6292 else if (isKnownNegative(Step) && 6293 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6294 return RangeBetween; 6295 return ConstantRange::getFull(BitWidth); 6296 } 6297 6298 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6299 const SCEV *Step, 6300 const SCEV *MaxBECount, 6301 unsigned BitWidth) { 6302 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6303 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6304 6305 struct SelectPattern { 6306 Value *Condition = nullptr; 6307 APInt TrueValue; 6308 APInt FalseValue; 6309 6310 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6311 const SCEV *S) { 6312 Optional<unsigned> CastOp; 6313 APInt Offset(BitWidth, 0); 6314 6315 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6316 "Should be!"); 6317 6318 // Peel off a constant offset: 6319 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6320 // In the future we could consider being smarter here and handle 6321 // {Start+Step,+,Step} too. 6322 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6323 return; 6324 6325 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6326 S = SA->getOperand(1); 6327 } 6328 6329 // Peel off a cast operation 6330 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6331 CastOp = SCast->getSCEVType(); 6332 S = SCast->getOperand(); 6333 } 6334 6335 using namespace llvm::PatternMatch; 6336 6337 auto *SU = dyn_cast<SCEVUnknown>(S); 6338 const APInt *TrueVal, *FalseVal; 6339 if (!SU || 6340 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6341 m_APInt(FalseVal)))) { 6342 Condition = nullptr; 6343 return; 6344 } 6345 6346 TrueValue = *TrueVal; 6347 FalseValue = *FalseVal; 6348 6349 // Re-apply the cast we peeled off earlier 6350 if (CastOp.hasValue()) 6351 switch (*CastOp) { 6352 default: 6353 llvm_unreachable("Unknown SCEV cast type!"); 6354 6355 case scTruncate: 6356 TrueValue = TrueValue.trunc(BitWidth); 6357 FalseValue = FalseValue.trunc(BitWidth); 6358 break; 6359 case scZeroExtend: 6360 TrueValue = TrueValue.zext(BitWidth); 6361 FalseValue = FalseValue.zext(BitWidth); 6362 break; 6363 case scSignExtend: 6364 TrueValue = TrueValue.sext(BitWidth); 6365 FalseValue = FalseValue.sext(BitWidth); 6366 break; 6367 } 6368 6369 // Re-apply the constant offset we peeled off earlier 6370 TrueValue += Offset; 6371 FalseValue += Offset; 6372 } 6373 6374 bool isRecognized() { return Condition != nullptr; } 6375 }; 6376 6377 SelectPattern StartPattern(*this, BitWidth, Start); 6378 if (!StartPattern.isRecognized()) 6379 return ConstantRange::getFull(BitWidth); 6380 6381 SelectPattern StepPattern(*this, BitWidth, Step); 6382 if (!StepPattern.isRecognized()) 6383 return ConstantRange::getFull(BitWidth); 6384 6385 if (StartPattern.Condition != StepPattern.Condition) { 6386 // We don't handle this case today; but we could, by considering four 6387 // possibilities below instead of two. I'm not sure if there are cases where 6388 // that will help over what getRange already does, though. 6389 return ConstantRange::getFull(BitWidth); 6390 } 6391 6392 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6393 // construct arbitrary general SCEV expressions here. This function is called 6394 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6395 // say) can end up caching a suboptimal value. 6396 6397 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6398 // C2352 and C2512 (otherwise it isn't needed). 6399 6400 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6401 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6402 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6403 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6404 6405 ConstantRange TrueRange = 6406 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6407 ConstantRange FalseRange = 6408 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6409 6410 return TrueRange.unionWith(FalseRange); 6411 } 6412 6413 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6414 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6415 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6416 6417 // Return early if there are no flags to propagate to the SCEV. 6418 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6419 if (BinOp->hasNoUnsignedWrap()) 6420 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6421 if (BinOp->hasNoSignedWrap()) 6422 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6423 if (Flags == SCEV::FlagAnyWrap) 6424 return SCEV::FlagAnyWrap; 6425 6426 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6427 } 6428 6429 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6430 // Here we check that I is in the header of the innermost loop containing I, 6431 // since we only deal with instructions in the loop header. The actual loop we 6432 // need to check later will come from an add recurrence, but getting that 6433 // requires computing the SCEV of the operands, which can be expensive. This 6434 // check we can do cheaply to rule out some cases early. 6435 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6436 if (InnermostContainingLoop == nullptr || 6437 InnermostContainingLoop->getHeader() != I->getParent()) 6438 return false; 6439 6440 // Only proceed if we can prove that I does not yield poison. 6441 if (!programUndefinedIfPoison(I)) 6442 return false; 6443 6444 // At this point we know that if I is executed, then it does not wrap 6445 // according to at least one of NSW or NUW. If I is not executed, then we do 6446 // not know if the calculation that I represents would wrap. Multiple 6447 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6448 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6449 // derived from other instructions that map to the same SCEV. We cannot make 6450 // that guarantee for cases where I is not executed. So we need to find the 6451 // loop that I is considered in relation to and prove that I is executed for 6452 // every iteration of that loop. That implies that the value that I 6453 // calculates does not wrap anywhere in the loop, so then we can apply the 6454 // flags to the SCEV. 6455 // 6456 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6457 // from different loops, so that we know which loop to prove that I is 6458 // executed in. 6459 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6460 // I could be an extractvalue from a call to an overflow intrinsic. 6461 // TODO: We can do better here in some cases. 6462 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6463 return false; 6464 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6465 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6466 bool AllOtherOpsLoopInvariant = true; 6467 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6468 ++OtherOpIndex) { 6469 if (OtherOpIndex != OpIndex) { 6470 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6471 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6472 AllOtherOpsLoopInvariant = false; 6473 break; 6474 } 6475 } 6476 } 6477 if (AllOtherOpsLoopInvariant && 6478 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6479 return true; 6480 } 6481 } 6482 return false; 6483 } 6484 6485 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6486 // If we know that \c I can never be poison period, then that's enough. 6487 if (isSCEVExprNeverPoison(I)) 6488 return true; 6489 6490 // For an add recurrence specifically, we assume that infinite loops without 6491 // side effects are undefined behavior, and then reason as follows: 6492 // 6493 // If the add recurrence is poison in any iteration, it is poison on all 6494 // future iterations (since incrementing poison yields poison). If the result 6495 // of the add recurrence is fed into the loop latch condition and the loop 6496 // does not contain any throws or exiting blocks other than the latch, we now 6497 // have the ability to "choose" whether the backedge is taken or not (by 6498 // choosing a sufficiently evil value for the poison feeding into the branch) 6499 // for every iteration including and after the one in which \p I first became 6500 // poison. There are two possibilities (let's call the iteration in which \p 6501 // I first became poison as K): 6502 // 6503 // 1. In the set of iterations including and after K, the loop body executes 6504 // no side effects. In this case executing the backege an infinte number 6505 // of times will yield undefined behavior. 6506 // 6507 // 2. In the set of iterations including and after K, the loop body executes 6508 // at least one side effect. In this case, that specific instance of side 6509 // effect is control dependent on poison, which also yields undefined 6510 // behavior. 6511 6512 auto *ExitingBB = L->getExitingBlock(); 6513 auto *LatchBB = L->getLoopLatch(); 6514 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6515 return false; 6516 6517 SmallPtrSet<const Instruction *, 16> Pushed; 6518 SmallVector<const Instruction *, 8> PoisonStack; 6519 6520 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6521 // things that are known to be poison under that assumption go on the 6522 // PoisonStack. 6523 Pushed.insert(I); 6524 PoisonStack.push_back(I); 6525 6526 bool LatchControlDependentOnPoison = false; 6527 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6528 const Instruction *Poison = PoisonStack.pop_back_val(); 6529 6530 for (auto *PoisonUser : Poison->users()) { 6531 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6532 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6533 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6534 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6535 assert(BI->isConditional() && "Only possibility!"); 6536 if (BI->getParent() == LatchBB) { 6537 LatchControlDependentOnPoison = true; 6538 break; 6539 } 6540 } 6541 } 6542 } 6543 6544 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6545 } 6546 6547 ScalarEvolution::LoopProperties 6548 ScalarEvolution::getLoopProperties(const Loop *L) { 6549 using LoopProperties = ScalarEvolution::LoopProperties; 6550 6551 auto Itr = LoopPropertiesCache.find(L); 6552 if (Itr == LoopPropertiesCache.end()) { 6553 auto HasSideEffects = [](Instruction *I) { 6554 if (auto *SI = dyn_cast<StoreInst>(I)) 6555 return !SI->isSimple(); 6556 6557 return I->mayHaveSideEffects(); 6558 }; 6559 6560 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6561 /*HasNoSideEffects*/ true}; 6562 6563 for (auto *BB : L->getBlocks()) 6564 for (auto &I : *BB) { 6565 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6566 LP.HasNoAbnormalExits = false; 6567 if (HasSideEffects(&I)) 6568 LP.HasNoSideEffects = false; 6569 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6570 break; // We're already as pessimistic as we can get. 6571 } 6572 6573 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6574 assert(InsertPair.second && "We just checked!"); 6575 Itr = InsertPair.first; 6576 } 6577 6578 return Itr->second; 6579 } 6580 6581 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6582 // A mustprogress loop without side effects must be finite. 6583 // TODO: The check used here is very conservative. It's only *specific* 6584 // side effects which are well defined in infinite loops. 6585 return isMustProgress(L) && loopHasNoSideEffects(L); 6586 } 6587 6588 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6589 if (!isSCEVable(V->getType())) 6590 return getUnknown(V); 6591 6592 if (Instruction *I = dyn_cast<Instruction>(V)) { 6593 // Don't attempt to analyze instructions in blocks that aren't 6594 // reachable. Such instructions don't matter, and they aren't required 6595 // to obey basic rules for definitions dominating uses which this 6596 // analysis depends on. 6597 if (!DT.isReachableFromEntry(I->getParent())) 6598 return getUnknown(UndefValue::get(V->getType())); 6599 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6600 return getConstant(CI); 6601 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6602 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6603 else if (!isa<ConstantExpr>(V)) 6604 return getUnknown(V); 6605 6606 Operator *U = cast<Operator>(V); 6607 if (auto BO = MatchBinaryOp(U, DT)) { 6608 switch (BO->Opcode) { 6609 case Instruction::Add: { 6610 // The simple thing to do would be to just call getSCEV on both operands 6611 // and call getAddExpr with the result. However if we're looking at a 6612 // bunch of things all added together, this can be quite inefficient, 6613 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6614 // Instead, gather up all the operands and make a single getAddExpr call. 6615 // LLVM IR canonical form means we need only traverse the left operands. 6616 SmallVector<const SCEV *, 4> AddOps; 6617 do { 6618 if (BO->Op) { 6619 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6620 AddOps.push_back(OpSCEV); 6621 break; 6622 } 6623 6624 // If a NUW or NSW flag can be applied to the SCEV for this 6625 // addition, then compute the SCEV for this addition by itself 6626 // with a separate call to getAddExpr. We need to do that 6627 // instead of pushing the operands of the addition onto AddOps, 6628 // since the flags are only known to apply to this particular 6629 // addition - they may not apply to other additions that can be 6630 // formed with operands from AddOps. 6631 const SCEV *RHS = getSCEV(BO->RHS); 6632 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6633 if (Flags != SCEV::FlagAnyWrap) { 6634 const SCEV *LHS = getSCEV(BO->LHS); 6635 if (BO->Opcode == Instruction::Sub) 6636 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6637 else 6638 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6639 break; 6640 } 6641 } 6642 6643 if (BO->Opcode == Instruction::Sub) 6644 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6645 else 6646 AddOps.push_back(getSCEV(BO->RHS)); 6647 6648 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6649 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6650 NewBO->Opcode != Instruction::Sub)) { 6651 AddOps.push_back(getSCEV(BO->LHS)); 6652 break; 6653 } 6654 BO = NewBO; 6655 } while (true); 6656 6657 return getAddExpr(AddOps); 6658 } 6659 6660 case Instruction::Mul: { 6661 SmallVector<const SCEV *, 4> MulOps; 6662 do { 6663 if (BO->Op) { 6664 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6665 MulOps.push_back(OpSCEV); 6666 break; 6667 } 6668 6669 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6670 if (Flags != SCEV::FlagAnyWrap) { 6671 MulOps.push_back( 6672 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6673 break; 6674 } 6675 } 6676 6677 MulOps.push_back(getSCEV(BO->RHS)); 6678 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6679 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6680 MulOps.push_back(getSCEV(BO->LHS)); 6681 break; 6682 } 6683 BO = NewBO; 6684 } while (true); 6685 6686 return getMulExpr(MulOps); 6687 } 6688 case Instruction::UDiv: 6689 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6690 case Instruction::URem: 6691 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6692 case Instruction::Sub: { 6693 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6694 if (BO->Op) 6695 Flags = getNoWrapFlagsFromUB(BO->Op); 6696 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6697 } 6698 case Instruction::And: 6699 // For an expression like x&255 that merely masks off the high bits, 6700 // use zext(trunc(x)) as the SCEV expression. 6701 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6702 if (CI->isZero()) 6703 return getSCEV(BO->RHS); 6704 if (CI->isMinusOne()) 6705 return getSCEV(BO->LHS); 6706 const APInt &A = CI->getValue(); 6707 6708 // Instcombine's ShrinkDemandedConstant may strip bits out of 6709 // constants, obscuring what would otherwise be a low-bits mask. 6710 // Use computeKnownBits to compute what ShrinkDemandedConstant 6711 // knew about to reconstruct a low-bits mask value. 6712 unsigned LZ = A.countLeadingZeros(); 6713 unsigned TZ = A.countTrailingZeros(); 6714 unsigned BitWidth = A.getBitWidth(); 6715 KnownBits Known(BitWidth); 6716 computeKnownBits(BO->LHS, Known, getDataLayout(), 6717 0, &AC, nullptr, &DT); 6718 6719 APInt EffectiveMask = 6720 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6721 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6722 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6723 const SCEV *LHS = getSCEV(BO->LHS); 6724 const SCEV *ShiftedLHS = nullptr; 6725 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6726 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6727 // For an expression like (x * 8) & 8, simplify the multiply. 6728 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6729 unsigned GCD = std::min(MulZeros, TZ); 6730 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6731 SmallVector<const SCEV*, 4> MulOps; 6732 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6733 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6734 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6735 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6736 } 6737 } 6738 if (!ShiftedLHS) 6739 ShiftedLHS = getUDivExpr(LHS, MulCount); 6740 return getMulExpr( 6741 getZeroExtendExpr( 6742 getTruncateExpr(ShiftedLHS, 6743 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6744 BO->LHS->getType()), 6745 MulCount); 6746 } 6747 } 6748 break; 6749 6750 case Instruction::Or: 6751 // If the RHS of the Or is a constant, we may have something like: 6752 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6753 // optimizations will transparently handle this case. 6754 // 6755 // In order for this transformation to be safe, the LHS must be of the 6756 // form X*(2^n) and the Or constant must be less than 2^n. 6757 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6758 const SCEV *LHS = getSCEV(BO->LHS); 6759 const APInt &CIVal = CI->getValue(); 6760 if (GetMinTrailingZeros(LHS) >= 6761 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6762 // Build a plain add SCEV. 6763 return getAddExpr(LHS, getSCEV(CI), 6764 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6765 } 6766 } 6767 break; 6768 6769 case Instruction::Xor: 6770 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6771 // If the RHS of xor is -1, then this is a not operation. 6772 if (CI->isMinusOne()) 6773 return getNotSCEV(getSCEV(BO->LHS)); 6774 6775 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6776 // This is a variant of the check for xor with -1, and it handles 6777 // the case where instcombine has trimmed non-demanded bits out 6778 // of an xor with -1. 6779 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6780 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6781 if (LBO->getOpcode() == Instruction::And && 6782 LCI->getValue() == CI->getValue()) 6783 if (const SCEVZeroExtendExpr *Z = 6784 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6785 Type *UTy = BO->LHS->getType(); 6786 const SCEV *Z0 = Z->getOperand(); 6787 Type *Z0Ty = Z0->getType(); 6788 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6789 6790 // If C is a low-bits mask, the zero extend is serving to 6791 // mask off the high bits. Complement the operand and 6792 // re-apply the zext. 6793 if (CI->getValue().isMask(Z0TySize)) 6794 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6795 6796 // If C is a single bit, it may be in the sign-bit position 6797 // before the zero-extend. In this case, represent the xor 6798 // using an add, which is equivalent, and re-apply the zext. 6799 APInt Trunc = CI->getValue().trunc(Z0TySize); 6800 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6801 Trunc.isSignMask()) 6802 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6803 UTy); 6804 } 6805 } 6806 break; 6807 6808 case Instruction::Shl: 6809 // Turn shift left of a constant amount into a multiply. 6810 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6811 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6812 6813 // If the shift count is not less than the bitwidth, the result of 6814 // the shift is undefined. Don't try to analyze it, because the 6815 // resolution chosen here may differ from the resolution chosen in 6816 // other parts of the compiler. 6817 if (SA->getValue().uge(BitWidth)) 6818 break; 6819 6820 // We can safely preserve the nuw flag in all cases. It's also safe to 6821 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6822 // requires special handling. It can be preserved as long as we're not 6823 // left shifting by bitwidth - 1. 6824 auto Flags = SCEV::FlagAnyWrap; 6825 if (BO->Op) { 6826 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6827 if ((MulFlags & SCEV::FlagNSW) && 6828 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6829 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6830 if (MulFlags & SCEV::FlagNUW) 6831 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6832 } 6833 6834 Constant *X = ConstantInt::get( 6835 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6836 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6837 } 6838 break; 6839 6840 case Instruction::AShr: { 6841 // AShr X, C, where C is a constant. 6842 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6843 if (!CI) 6844 break; 6845 6846 Type *OuterTy = BO->LHS->getType(); 6847 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6848 // If the shift count is not less than the bitwidth, the result of 6849 // the shift is undefined. Don't try to analyze it, because the 6850 // resolution chosen here may differ from the resolution chosen in 6851 // other parts of the compiler. 6852 if (CI->getValue().uge(BitWidth)) 6853 break; 6854 6855 if (CI->isZero()) 6856 return getSCEV(BO->LHS); // shift by zero --> noop 6857 6858 uint64_t AShrAmt = CI->getZExtValue(); 6859 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6860 6861 Operator *L = dyn_cast<Operator>(BO->LHS); 6862 if (L && L->getOpcode() == Instruction::Shl) { 6863 // X = Shl A, n 6864 // Y = AShr X, m 6865 // Both n and m are constant. 6866 6867 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6868 if (L->getOperand(1) == BO->RHS) 6869 // For a two-shift sext-inreg, i.e. n = m, 6870 // use sext(trunc(x)) as the SCEV expression. 6871 return getSignExtendExpr( 6872 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6873 6874 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6875 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6876 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6877 if (ShlAmt > AShrAmt) { 6878 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6879 // expression. We already checked that ShlAmt < BitWidth, so 6880 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6881 // ShlAmt - AShrAmt < Amt. 6882 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6883 ShlAmt - AShrAmt); 6884 return getSignExtendExpr( 6885 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6886 getConstant(Mul)), OuterTy); 6887 } 6888 } 6889 } 6890 break; 6891 } 6892 } 6893 } 6894 6895 switch (U->getOpcode()) { 6896 case Instruction::Trunc: 6897 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6898 6899 case Instruction::ZExt: 6900 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6901 6902 case Instruction::SExt: 6903 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6904 // The NSW flag of a subtract does not always survive the conversion to 6905 // A + (-1)*B. By pushing sign extension onto its operands we are much 6906 // more likely to preserve NSW and allow later AddRec optimisations. 6907 // 6908 // NOTE: This is effectively duplicating this logic from getSignExtend: 6909 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6910 // but by that point the NSW information has potentially been lost. 6911 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6912 Type *Ty = U->getType(); 6913 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6914 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6915 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6916 } 6917 } 6918 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6919 6920 case Instruction::BitCast: 6921 // BitCasts are no-op casts so we just eliminate the cast. 6922 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6923 return getSCEV(U->getOperand(0)); 6924 break; 6925 6926 case Instruction::PtrToInt: { 6927 // Pointer to integer cast is straight-forward, so do model it. 6928 const SCEV *Op = getSCEV(U->getOperand(0)); 6929 Type *DstIntTy = U->getType(); 6930 // But only if effective SCEV (integer) type is wide enough to represent 6931 // all possible pointer values. 6932 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 6933 if (isa<SCEVCouldNotCompute>(IntOp)) 6934 return getUnknown(V); 6935 return IntOp; 6936 } 6937 case Instruction::IntToPtr: 6938 // Just don't deal with inttoptr casts. 6939 return getUnknown(V); 6940 6941 case Instruction::SDiv: 6942 // If both operands are non-negative, this is just an udiv. 6943 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6944 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6945 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6946 break; 6947 6948 case Instruction::SRem: 6949 // If both operands are non-negative, this is just an urem. 6950 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6951 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6952 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6953 break; 6954 6955 case Instruction::GetElementPtr: 6956 return createNodeForGEP(cast<GEPOperator>(U)); 6957 6958 case Instruction::PHI: 6959 return createNodeForPHI(cast<PHINode>(U)); 6960 6961 case Instruction::Select: 6962 // U can also be a select constant expr, which let fall through. Since 6963 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6964 // constant expressions cannot have instructions as operands, we'd have 6965 // returned getUnknown for a select constant expressions anyway. 6966 if (isa<Instruction>(U)) 6967 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6968 U->getOperand(1), U->getOperand(2)); 6969 break; 6970 6971 case Instruction::Call: 6972 case Instruction::Invoke: 6973 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6974 return getSCEV(RV); 6975 6976 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6977 switch (II->getIntrinsicID()) { 6978 case Intrinsic::abs: 6979 return getAbsExpr( 6980 getSCEV(II->getArgOperand(0)), 6981 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6982 case Intrinsic::umax: 6983 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6984 getSCEV(II->getArgOperand(1))); 6985 case Intrinsic::umin: 6986 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6987 getSCEV(II->getArgOperand(1))); 6988 case Intrinsic::smax: 6989 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6990 getSCEV(II->getArgOperand(1))); 6991 case Intrinsic::smin: 6992 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6993 getSCEV(II->getArgOperand(1))); 6994 case Intrinsic::usub_sat: { 6995 const SCEV *X = getSCEV(II->getArgOperand(0)); 6996 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6997 const SCEV *ClampedY = getUMinExpr(X, Y); 6998 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6999 } 7000 case Intrinsic::uadd_sat: { 7001 const SCEV *X = getSCEV(II->getArgOperand(0)); 7002 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7003 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7004 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7005 } 7006 case Intrinsic::start_loop_iterations: 7007 // A start_loop_iterations is just equivalent to the first operand for 7008 // SCEV purposes. 7009 return getSCEV(II->getArgOperand(0)); 7010 default: 7011 break; 7012 } 7013 } 7014 break; 7015 } 7016 7017 return getUnknown(V); 7018 } 7019 7020 //===----------------------------------------------------------------------===// 7021 // Iteration Count Computation Code 7022 // 7023 7024 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7025 // Get the trip count from the BE count by adding 1. Overflow, results 7026 // in zero which means "unknown". 7027 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7028 } 7029 7030 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7031 if (!ExitCount) 7032 return 0; 7033 7034 ConstantInt *ExitConst = ExitCount->getValue(); 7035 7036 // Guard against huge trip counts. 7037 if (ExitConst->getValue().getActiveBits() > 32) 7038 return 0; 7039 7040 // In case of integer overflow, this returns 0, which is correct. 7041 return ((unsigned)ExitConst->getZExtValue()) + 1; 7042 } 7043 7044 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7045 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7046 return getConstantTripCount(ExitCount); 7047 } 7048 7049 unsigned 7050 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7051 const BasicBlock *ExitingBlock) { 7052 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7053 assert(L->isLoopExiting(ExitingBlock) && 7054 "Exiting block must actually branch out of the loop!"); 7055 const SCEVConstant *ExitCount = 7056 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7057 return getConstantTripCount(ExitCount); 7058 } 7059 7060 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7061 const auto *MaxExitCount = 7062 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7063 return getConstantTripCount(MaxExitCount); 7064 } 7065 7066 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7067 SmallVector<BasicBlock *, 8> ExitingBlocks; 7068 L->getExitingBlocks(ExitingBlocks); 7069 7070 Optional<unsigned> Res = None; 7071 for (auto *ExitingBB : ExitingBlocks) { 7072 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7073 if (!Res) 7074 Res = Multiple; 7075 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7076 } 7077 return Res.getValueOr(1); 7078 } 7079 7080 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7081 const SCEV *ExitCount) { 7082 if (ExitCount == getCouldNotCompute()) 7083 return 1; 7084 7085 // Get the trip count 7086 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7087 7088 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7089 if (!TC) 7090 // Attempt to factor more general cases. Returns the greatest power of 7091 // two divisor. If overflow happens, the trip count expression is still 7092 // divisible by the greatest power of 2 divisor returned. 7093 return 1U << std::min((uint32_t)31, 7094 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7095 7096 ConstantInt *Result = TC->getValue(); 7097 7098 // Guard against huge trip counts (this requires checking 7099 // for zero to handle the case where the trip count == -1 and the 7100 // addition wraps). 7101 if (!Result || Result->getValue().getActiveBits() > 32 || 7102 Result->getValue().getActiveBits() == 0) 7103 return 1; 7104 7105 return (unsigned)Result->getZExtValue(); 7106 } 7107 7108 /// Returns the largest constant divisor of the trip count of this loop as a 7109 /// normal unsigned value, if possible. This means that the actual trip count is 7110 /// always a multiple of the returned value (don't forget the trip count could 7111 /// very well be zero as well!). 7112 /// 7113 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7114 /// multiple of a constant (which is also the case if the trip count is simply 7115 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7116 /// if the trip count is very large (>= 2^32). 7117 /// 7118 /// As explained in the comments for getSmallConstantTripCount, this assumes 7119 /// that control exits the loop via ExitingBlock. 7120 unsigned 7121 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7122 const BasicBlock *ExitingBlock) { 7123 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7124 assert(L->isLoopExiting(ExitingBlock) && 7125 "Exiting block must actually branch out of the loop!"); 7126 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7127 return getSmallConstantTripMultiple(L, ExitCount); 7128 } 7129 7130 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7131 const BasicBlock *ExitingBlock, 7132 ExitCountKind Kind) { 7133 switch (Kind) { 7134 case Exact: 7135 case SymbolicMaximum: 7136 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7137 case ConstantMaximum: 7138 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7139 }; 7140 llvm_unreachable("Invalid ExitCountKind!"); 7141 } 7142 7143 const SCEV * 7144 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7145 SCEVUnionPredicate &Preds) { 7146 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7147 } 7148 7149 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7150 ExitCountKind Kind) { 7151 switch (Kind) { 7152 case Exact: 7153 return getBackedgeTakenInfo(L).getExact(L, this); 7154 case ConstantMaximum: 7155 return getBackedgeTakenInfo(L).getConstantMax(this); 7156 case SymbolicMaximum: 7157 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7158 }; 7159 llvm_unreachable("Invalid ExitCountKind!"); 7160 } 7161 7162 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7163 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7164 } 7165 7166 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7167 static void 7168 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7169 BasicBlock *Header = L->getHeader(); 7170 7171 // Push all Loop-header PHIs onto the Worklist stack. 7172 for (PHINode &PN : Header->phis()) 7173 Worklist.push_back(&PN); 7174 } 7175 7176 const ScalarEvolution::BackedgeTakenInfo & 7177 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7178 auto &BTI = getBackedgeTakenInfo(L); 7179 if (BTI.hasFullInfo()) 7180 return BTI; 7181 7182 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7183 7184 if (!Pair.second) 7185 return Pair.first->second; 7186 7187 BackedgeTakenInfo Result = 7188 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7189 7190 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7191 } 7192 7193 ScalarEvolution::BackedgeTakenInfo & 7194 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7195 // Initially insert an invalid entry for this loop. If the insertion 7196 // succeeds, proceed to actually compute a backedge-taken count and 7197 // update the value. The temporary CouldNotCompute value tells SCEV 7198 // code elsewhere that it shouldn't attempt to request a new 7199 // backedge-taken count, which could result in infinite recursion. 7200 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7201 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7202 if (!Pair.second) 7203 return Pair.first->second; 7204 7205 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7206 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7207 // must be cleared in this scope. 7208 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7209 7210 // In product build, there are no usage of statistic. 7211 (void)NumTripCountsComputed; 7212 (void)NumTripCountsNotComputed; 7213 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7214 const SCEV *BEExact = Result.getExact(L, this); 7215 if (BEExact != getCouldNotCompute()) { 7216 assert(isLoopInvariant(BEExact, L) && 7217 isLoopInvariant(Result.getConstantMax(this), L) && 7218 "Computed backedge-taken count isn't loop invariant for loop!"); 7219 ++NumTripCountsComputed; 7220 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7221 isa<PHINode>(L->getHeader()->begin())) { 7222 // Only count loops that have phi nodes as not being computable. 7223 ++NumTripCountsNotComputed; 7224 } 7225 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7226 7227 // Now that we know more about the trip count for this loop, forget any 7228 // existing SCEV values for PHI nodes in this loop since they are only 7229 // conservative estimates made without the benefit of trip count 7230 // information. This is similar to the code in forgetLoop, except that 7231 // it handles SCEVUnknown PHI nodes specially. 7232 if (Result.hasAnyInfo()) { 7233 SmallVector<Instruction *, 16> Worklist; 7234 PushLoopPHIs(L, Worklist); 7235 7236 SmallPtrSet<Instruction *, 8> Discovered; 7237 while (!Worklist.empty()) { 7238 Instruction *I = Worklist.pop_back_val(); 7239 7240 ValueExprMapType::iterator It = 7241 ValueExprMap.find_as(static_cast<Value *>(I)); 7242 if (It != ValueExprMap.end()) { 7243 const SCEV *Old = It->second; 7244 7245 // SCEVUnknown for a PHI either means that it has an unrecognized 7246 // structure, or it's a PHI that's in the progress of being computed 7247 // by createNodeForPHI. In the former case, additional loop trip 7248 // count information isn't going to change anything. In the later 7249 // case, createNodeForPHI will perform the necessary updates on its 7250 // own when it gets to that point. 7251 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7252 eraseValueFromMap(It->first); 7253 forgetMemoizedResults(Old); 7254 } 7255 if (PHINode *PN = dyn_cast<PHINode>(I)) 7256 ConstantEvolutionLoopExitValue.erase(PN); 7257 } 7258 7259 // Since we don't need to invalidate anything for correctness and we're 7260 // only invalidating to make SCEV's results more precise, we get to stop 7261 // early to avoid invalidating too much. This is especially important in 7262 // cases like: 7263 // 7264 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7265 // loop0: 7266 // %pn0 = phi 7267 // ... 7268 // loop1: 7269 // %pn1 = phi 7270 // ... 7271 // 7272 // where both loop0 and loop1's backedge taken count uses the SCEV 7273 // expression for %v. If we don't have the early stop below then in cases 7274 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7275 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7276 // count for loop1, effectively nullifying SCEV's trip count cache. 7277 for (auto *U : I->users()) 7278 if (auto *I = dyn_cast<Instruction>(U)) { 7279 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7280 if (LoopForUser && L->contains(LoopForUser) && 7281 Discovered.insert(I).second) 7282 Worklist.push_back(I); 7283 } 7284 } 7285 } 7286 7287 // Re-lookup the insert position, since the call to 7288 // computeBackedgeTakenCount above could result in a 7289 // recusive call to getBackedgeTakenInfo (on a different 7290 // loop), which would invalidate the iterator computed 7291 // earlier. 7292 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7293 } 7294 7295 void ScalarEvolution::forgetAllLoops() { 7296 // This method is intended to forget all info about loops. It should 7297 // invalidate caches as if the following happened: 7298 // - The trip counts of all loops have changed arbitrarily 7299 // - Every llvm::Value has been updated in place to produce a different 7300 // result. 7301 BackedgeTakenCounts.clear(); 7302 PredicatedBackedgeTakenCounts.clear(); 7303 LoopPropertiesCache.clear(); 7304 ConstantEvolutionLoopExitValue.clear(); 7305 ValueExprMap.clear(); 7306 ValuesAtScopes.clear(); 7307 LoopDispositions.clear(); 7308 BlockDispositions.clear(); 7309 UnsignedRanges.clear(); 7310 SignedRanges.clear(); 7311 ExprValueMap.clear(); 7312 HasRecMap.clear(); 7313 MinTrailingZerosCache.clear(); 7314 PredicatedSCEVRewrites.clear(); 7315 } 7316 7317 void ScalarEvolution::forgetLoop(const Loop *L) { 7318 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7319 SmallVector<Instruction *, 32> Worklist; 7320 SmallPtrSet<Instruction *, 16> Visited; 7321 7322 // Iterate over all the loops and sub-loops to drop SCEV information. 7323 while (!LoopWorklist.empty()) { 7324 auto *CurrL = LoopWorklist.pop_back_val(); 7325 7326 // Drop any stored trip count value. 7327 BackedgeTakenCounts.erase(CurrL); 7328 PredicatedBackedgeTakenCounts.erase(CurrL); 7329 7330 // Drop information about predicated SCEV rewrites for this loop. 7331 for (auto I = PredicatedSCEVRewrites.begin(); 7332 I != PredicatedSCEVRewrites.end();) { 7333 std::pair<const SCEV *, const Loop *> Entry = I->first; 7334 if (Entry.second == CurrL) 7335 PredicatedSCEVRewrites.erase(I++); 7336 else 7337 ++I; 7338 } 7339 7340 auto LoopUsersItr = LoopUsers.find(CurrL); 7341 if (LoopUsersItr != LoopUsers.end()) { 7342 for (auto *S : LoopUsersItr->second) 7343 forgetMemoizedResults(S); 7344 LoopUsers.erase(LoopUsersItr); 7345 } 7346 7347 // Drop information about expressions based on loop-header PHIs. 7348 PushLoopPHIs(CurrL, Worklist); 7349 7350 while (!Worklist.empty()) { 7351 Instruction *I = Worklist.pop_back_val(); 7352 if (!Visited.insert(I).second) 7353 continue; 7354 7355 ValueExprMapType::iterator It = 7356 ValueExprMap.find_as(static_cast<Value *>(I)); 7357 if (It != ValueExprMap.end()) { 7358 eraseValueFromMap(It->first); 7359 forgetMemoizedResults(It->second); 7360 if (PHINode *PN = dyn_cast<PHINode>(I)) 7361 ConstantEvolutionLoopExitValue.erase(PN); 7362 } 7363 7364 PushDefUseChildren(I, Worklist); 7365 } 7366 7367 LoopPropertiesCache.erase(CurrL); 7368 // Forget all contained loops too, to avoid dangling entries in the 7369 // ValuesAtScopes map. 7370 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7371 } 7372 } 7373 7374 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7375 while (Loop *Parent = L->getParentLoop()) 7376 L = Parent; 7377 forgetLoop(L); 7378 } 7379 7380 void ScalarEvolution::forgetValue(Value *V) { 7381 Instruction *I = dyn_cast<Instruction>(V); 7382 if (!I) return; 7383 7384 // Drop information about expressions based on loop-header PHIs. 7385 SmallVector<Instruction *, 16> Worklist; 7386 Worklist.push_back(I); 7387 7388 SmallPtrSet<Instruction *, 8> Visited; 7389 while (!Worklist.empty()) { 7390 I = Worklist.pop_back_val(); 7391 if (!Visited.insert(I).second) 7392 continue; 7393 7394 ValueExprMapType::iterator It = 7395 ValueExprMap.find_as(static_cast<Value *>(I)); 7396 if (It != ValueExprMap.end()) { 7397 eraseValueFromMap(It->first); 7398 forgetMemoizedResults(It->second); 7399 if (PHINode *PN = dyn_cast<PHINode>(I)) 7400 ConstantEvolutionLoopExitValue.erase(PN); 7401 } 7402 7403 PushDefUseChildren(I, Worklist); 7404 } 7405 } 7406 7407 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7408 LoopDispositions.clear(); 7409 } 7410 7411 /// Get the exact loop backedge taken count considering all loop exits. A 7412 /// computable result can only be returned for loops with all exiting blocks 7413 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7414 /// is never skipped. This is a valid assumption as long as the loop exits via 7415 /// that test. For precise results, it is the caller's responsibility to specify 7416 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7417 const SCEV * 7418 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7419 SCEVUnionPredicate *Preds) const { 7420 // If any exits were not computable, the loop is not computable. 7421 if (!isComplete() || ExitNotTaken.empty()) 7422 return SE->getCouldNotCompute(); 7423 7424 const BasicBlock *Latch = L->getLoopLatch(); 7425 // All exiting blocks we have collected must dominate the only backedge. 7426 if (!Latch) 7427 return SE->getCouldNotCompute(); 7428 7429 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7430 // count is simply a minimum out of all these calculated exit counts. 7431 SmallVector<const SCEV *, 2> Ops; 7432 for (auto &ENT : ExitNotTaken) { 7433 const SCEV *BECount = ENT.ExactNotTaken; 7434 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7435 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7436 "We should only have known counts for exiting blocks that dominate " 7437 "latch!"); 7438 7439 Ops.push_back(BECount); 7440 7441 if (Preds && !ENT.hasAlwaysTruePredicate()) 7442 Preds->add(ENT.Predicate.get()); 7443 7444 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7445 "Predicate should be always true!"); 7446 } 7447 7448 return SE->getUMinFromMismatchedTypes(Ops); 7449 } 7450 7451 /// Get the exact not taken count for this loop exit. 7452 const SCEV * 7453 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7454 ScalarEvolution *SE) const { 7455 for (auto &ENT : ExitNotTaken) 7456 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7457 return ENT.ExactNotTaken; 7458 7459 return SE->getCouldNotCompute(); 7460 } 7461 7462 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7463 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7464 for (auto &ENT : ExitNotTaken) 7465 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7466 return ENT.MaxNotTaken; 7467 7468 return SE->getCouldNotCompute(); 7469 } 7470 7471 /// getConstantMax - Get the constant max backedge taken count for the loop. 7472 const SCEV * 7473 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7474 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7475 return !ENT.hasAlwaysTruePredicate(); 7476 }; 7477 7478 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7479 return SE->getCouldNotCompute(); 7480 7481 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7482 isa<SCEVConstant>(getConstantMax())) && 7483 "No point in having a non-constant max backedge taken count!"); 7484 return getConstantMax(); 7485 } 7486 7487 const SCEV * 7488 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7489 ScalarEvolution *SE) { 7490 if (!SymbolicMax) 7491 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7492 return SymbolicMax; 7493 } 7494 7495 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7496 ScalarEvolution *SE) const { 7497 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7498 return !ENT.hasAlwaysTruePredicate(); 7499 }; 7500 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7501 } 7502 7503 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7504 return Operands.contains(S); 7505 } 7506 7507 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7508 : ExactNotTaken(E), MaxNotTaken(E) { 7509 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7510 isa<SCEVConstant>(MaxNotTaken)) && 7511 "No point in having a non-constant max backedge taken count!"); 7512 } 7513 7514 ScalarEvolution::ExitLimit::ExitLimit( 7515 const SCEV *E, const SCEV *M, bool MaxOrZero, 7516 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7517 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7518 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7519 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7520 "Exact is not allowed to be less precise than Max"); 7521 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7522 isa<SCEVConstant>(MaxNotTaken)) && 7523 "No point in having a non-constant max backedge taken count!"); 7524 for (auto *PredSet : PredSetList) 7525 for (auto *P : *PredSet) 7526 addPredicate(P); 7527 } 7528 7529 ScalarEvolution::ExitLimit::ExitLimit( 7530 const SCEV *E, const SCEV *M, bool MaxOrZero, 7531 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7532 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7533 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7534 isa<SCEVConstant>(MaxNotTaken)) && 7535 "No point in having a non-constant max backedge taken count!"); 7536 } 7537 7538 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7539 bool MaxOrZero) 7540 : ExitLimit(E, M, MaxOrZero, None) { 7541 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7542 isa<SCEVConstant>(MaxNotTaken)) && 7543 "No point in having a non-constant max backedge taken count!"); 7544 } 7545 7546 class SCEVRecordOperands { 7547 SmallPtrSetImpl<const SCEV *> &Operands; 7548 7549 public: 7550 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7551 : Operands(Operands) {} 7552 bool follow(const SCEV *S) { 7553 Operands.insert(S); 7554 return true; 7555 } 7556 bool isDone() { return false; } 7557 }; 7558 7559 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7560 /// computable exit into a persistent ExitNotTakenInfo array. 7561 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7562 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7563 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7564 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7565 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7566 7567 ExitNotTaken.reserve(ExitCounts.size()); 7568 std::transform( 7569 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7570 [&](const EdgeExitInfo &EEI) { 7571 BasicBlock *ExitBB = EEI.first; 7572 const ExitLimit &EL = EEI.second; 7573 if (EL.Predicates.empty()) 7574 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7575 nullptr); 7576 7577 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7578 for (auto *Pred : EL.Predicates) 7579 Predicate->add(Pred); 7580 7581 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7582 std::move(Predicate)); 7583 }); 7584 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7585 isa<SCEVConstant>(ConstantMax)) && 7586 "No point in having a non-constant max backedge taken count!"); 7587 7588 SCEVRecordOperands RecordOperands(Operands); 7589 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7590 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7591 ST.visitAll(ConstantMax); 7592 for (auto &ENT : ExitNotTaken) 7593 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7594 ST.visitAll(ENT.ExactNotTaken); 7595 } 7596 7597 /// Compute the number of times the backedge of the specified loop will execute. 7598 ScalarEvolution::BackedgeTakenInfo 7599 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7600 bool AllowPredicates) { 7601 SmallVector<BasicBlock *, 8> ExitingBlocks; 7602 L->getExitingBlocks(ExitingBlocks); 7603 7604 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7605 7606 SmallVector<EdgeExitInfo, 4> ExitCounts; 7607 bool CouldComputeBECount = true; 7608 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7609 const SCEV *MustExitMaxBECount = nullptr; 7610 const SCEV *MayExitMaxBECount = nullptr; 7611 bool MustExitMaxOrZero = false; 7612 7613 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7614 // and compute maxBECount. 7615 // Do a union of all the predicates here. 7616 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7617 BasicBlock *ExitBB = ExitingBlocks[i]; 7618 7619 // We canonicalize untaken exits to br (constant), ignore them so that 7620 // proving an exit untaken doesn't negatively impact our ability to reason 7621 // about the loop as whole. 7622 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7623 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7624 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7625 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7626 continue; 7627 } 7628 7629 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7630 7631 assert((AllowPredicates || EL.Predicates.empty()) && 7632 "Predicated exit limit when predicates are not allowed!"); 7633 7634 // 1. For each exit that can be computed, add an entry to ExitCounts. 7635 // CouldComputeBECount is true only if all exits can be computed. 7636 if (EL.ExactNotTaken == getCouldNotCompute()) 7637 // We couldn't compute an exact value for this exit, so 7638 // we won't be able to compute an exact value for the loop. 7639 CouldComputeBECount = false; 7640 else 7641 ExitCounts.emplace_back(ExitBB, EL); 7642 7643 // 2. Derive the loop's MaxBECount from each exit's max number of 7644 // non-exiting iterations. Partition the loop exits into two kinds: 7645 // LoopMustExits and LoopMayExits. 7646 // 7647 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7648 // is a LoopMayExit. If any computable LoopMustExit is found, then 7649 // MaxBECount is the minimum EL.MaxNotTaken of computable 7650 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7651 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7652 // computable EL.MaxNotTaken. 7653 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7654 DT.dominates(ExitBB, Latch)) { 7655 if (!MustExitMaxBECount) { 7656 MustExitMaxBECount = EL.MaxNotTaken; 7657 MustExitMaxOrZero = EL.MaxOrZero; 7658 } else { 7659 MustExitMaxBECount = 7660 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7661 } 7662 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7663 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7664 MayExitMaxBECount = EL.MaxNotTaken; 7665 else { 7666 MayExitMaxBECount = 7667 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7668 } 7669 } 7670 } 7671 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7672 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7673 // The loop backedge will be taken the maximum or zero times if there's 7674 // a single exit that must be taken the maximum or zero times. 7675 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7676 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7677 MaxBECount, MaxOrZero); 7678 } 7679 7680 ScalarEvolution::ExitLimit 7681 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7682 bool AllowPredicates) { 7683 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7684 // If our exiting block does not dominate the latch, then its connection with 7685 // loop's exit limit may be far from trivial. 7686 const BasicBlock *Latch = L->getLoopLatch(); 7687 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7688 return getCouldNotCompute(); 7689 7690 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7691 Instruction *Term = ExitingBlock->getTerminator(); 7692 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7693 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7694 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7695 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7696 "It should have one successor in loop and one exit block!"); 7697 // Proceed to the next level to examine the exit condition expression. 7698 return computeExitLimitFromCond( 7699 L, BI->getCondition(), ExitIfTrue, 7700 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7701 } 7702 7703 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7704 // For switch, make sure that there is a single exit from the loop. 7705 BasicBlock *Exit = nullptr; 7706 for (auto *SBB : successors(ExitingBlock)) 7707 if (!L->contains(SBB)) { 7708 if (Exit) // Multiple exit successors. 7709 return getCouldNotCompute(); 7710 Exit = SBB; 7711 } 7712 assert(Exit && "Exiting block must have at least one exit"); 7713 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7714 /*ControlsExit=*/IsOnlyExit); 7715 } 7716 7717 return getCouldNotCompute(); 7718 } 7719 7720 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7721 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7722 bool ControlsExit, bool AllowPredicates) { 7723 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7724 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7725 ControlsExit, AllowPredicates); 7726 } 7727 7728 Optional<ScalarEvolution::ExitLimit> 7729 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7730 bool ExitIfTrue, bool ControlsExit, 7731 bool AllowPredicates) { 7732 (void)this->L; 7733 (void)this->ExitIfTrue; 7734 (void)this->AllowPredicates; 7735 7736 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7737 this->AllowPredicates == AllowPredicates && 7738 "Variance in assumed invariant key components!"); 7739 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7740 if (Itr == TripCountMap.end()) 7741 return None; 7742 return Itr->second; 7743 } 7744 7745 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7746 bool ExitIfTrue, 7747 bool ControlsExit, 7748 bool AllowPredicates, 7749 const ExitLimit &EL) { 7750 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7751 this->AllowPredicates == AllowPredicates && 7752 "Variance in assumed invariant key components!"); 7753 7754 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7755 assert(InsertResult.second && "Expected successful insertion!"); 7756 (void)InsertResult; 7757 (void)ExitIfTrue; 7758 } 7759 7760 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7761 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7762 bool ControlsExit, bool AllowPredicates) { 7763 7764 if (auto MaybeEL = 7765 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7766 return *MaybeEL; 7767 7768 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7769 ControlsExit, AllowPredicates); 7770 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7771 return EL; 7772 } 7773 7774 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7775 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7776 bool ControlsExit, bool AllowPredicates) { 7777 // Handle BinOp conditions (And, Or). 7778 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7779 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7780 return *LimitFromBinOp; 7781 7782 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7783 // Proceed to the next level to examine the icmp. 7784 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7785 ExitLimit EL = 7786 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7787 if (EL.hasFullInfo() || !AllowPredicates) 7788 return EL; 7789 7790 // Try again, but use SCEV predicates this time. 7791 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7792 /*AllowPredicates=*/true); 7793 } 7794 7795 // Check for a constant condition. These are normally stripped out by 7796 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7797 // preserve the CFG and is temporarily leaving constant conditions 7798 // in place. 7799 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7800 if (ExitIfTrue == !CI->getZExtValue()) 7801 // The backedge is always taken. 7802 return getCouldNotCompute(); 7803 else 7804 // The backedge is never taken. 7805 return getZero(CI->getType()); 7806 } 7807 7808 // If it's not an integer or pointer comparison then compute it the hard way. 7809 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7810 } 7811 7812 Optional<ScalarEvolution::ExitLimit> 7813 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7814 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7815 bool ControlsExit, bool AllowPredicates) { 7816 // Check if the controlling expression for this loop is an And or Or. 7817 Value *Op0, *Op1; 7818 bool IsAnd = false; 7819 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7820 IsAnd = true; 7821 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7822 IsAnd = false; 7823 else 7824 return None; 7825 7826 // EitherMayExit is true in these two cases: 7827 // br (and Op0 Op1), loop, exit 7828 // br (or Op0 Op1), exit, loop 7829 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7830 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7831 ControlsExit && !EitherMayExit, 7832 AllowPredicates); 7833 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7834 ControlsExit && !EitherMayExit, 7835 AllowPredicates); 7836 7837 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7838 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7839 if (isa<ConstantInt>(Op1)) 7840 return Op1 == NeutralElement ? EL0 : EL1; 7841 if (isa<ConstantInt>(Op0)) 7842 return Op0 == NeutralElement ? EL1 : EL0; 7843 7844 const SCEV *BECount = getCouldNotCompute(); 7845 const SCEV *MaxBECount = getCouldNotCompute(); 7846 if (EitherMayExit) { 7847 // Both conditions must be same for the loop to continue executing. 7848 // Choose the less conservative count. 7849 // If ExitCond is a short-circuit form (select), using 7850 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7851 // To see the detailed examples, please see 7852 // test/Analysis/ScalarEvolution/exit-count-select.ll 7853 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7854 if (!PoisonSafe) 7855 // Even if ExitCond is select, we can safely derive BECount using both 7856 // EL0 and EL1 in these cases: 7857 // (1) EL0.ExactNotTaken is non-zero 7858 // (2) EL1.ExactNotTaken is non-poison 7859 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7860 // it cannot be umin(0, ..)) 7861 // The PoisonSafe assignment below is simplified and the assertion after 7862 // BECount calculation fully guarantees the condition (3). 7863 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7864 isa<SCEVConstant>(EL1.ExactNotTaken); 7865 if (EL0.ExactNotTaken != getCouldNotCompute() && 7866 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7867 BECount = 7868 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7869 7870 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7871 // it should have been simplified to zero (see the condition (3) above) 7872 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7873 BECount->isZero()); 7874 } 7875 if (EL0.MaxNotTaken == getCouldNotCompute()) 7876 MaxBECount = EL1.MaxNotTaken; 7877 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7878 MaxBECount = EL0.MaxNotTaken; 7879 else 7880 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7881 } else { 7882 // Both conditions must be same at the same time for the loop to exit. 7883 // For now, be conservative. 7884 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7885 BECount = EL0.ExactNotTaken; 7886 } 7887 7888 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7889 // to be more aggressive when computing BECount than when computing 7890 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7891 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7892 // to not. 7893 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7894 !isa<SCEVCouldNotCompute>(BECount)) 7895 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7896 7897 return ExitLimit(BECount, MaxBECount, false, 7898 { &EL0.Predicates, &EL1.Predicates }); 7899 } 7900 7901 ScalarEvolution::ExitLimit 7902 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7903 ICmpInst *ExitCond, 7904 bool ExitIfTrue, 7905 bool ControlsExit, 7906 bool AllowPredicates) { 7907 // If the condition was exit on true, convert the condition to exit on false 7908 ICmpInst::Predicate Pred; 7909 if (!ExitIfTrue) 7910 Pred = ExitCond->getPredicate(); 7911 else 7912 Pred = ExitCond->getInversePredicate(); 7913 const ICmpInst::Predicate OriginalPred = Pred; 7914 7915 // Handle common loops like: for (X = "string"; *X; ++X) 7916 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7917 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7918 ExitLimit ItCnt = 7919 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7920 if (ItCnt.hasAnyInfo()) 7921 return ItCnt; 7922 } 7923 7924 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7925 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7926 7927 // Try to evaluate any dependencies out of the loop. 7928 LHS = getSCEVAtScope(LHS, L); 7929 RHS = getSCEVAtScope(RHS, L); 7930 7931 // At this point, we would like to compute how many iterations of the 7932 // loop the predicate will return true for these inputs. 7933 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7934 // If there is a loop-invariant, force it into the RHS. 7935 std::swap(LHS, RHS); 7936 Pred = ICmpInst::getSwappedPredicate(Pred); 7937 } 7938 7939 // Simplify the operands before analyzing them. 7940 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7941 7942 // If we have a comparison of a chrec against a constant, try to use value 7943 // ranges to answer this query. 7944 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7945 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7946 if (AddRec->getLoop() == L) { 7947 // Form the constant range. 7948 ConstantRange CompRange = 7949 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7950 7951 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7952 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7953 } 7954 7955 switch (Pred) { 7956 case ICmpInst::ICMP_NE: { // while (X != Y) 7957 // Convert to: while (X-Y != 0) 7958 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7959 AllowPredicates); 7960 if (EL.hasAnyInfo()) return EL; 7961 break; 7962 } 7963 case ICmpInst::ICMP_EQ: { // while (X == Y) 7964 // Convert to: while (X-Y == 0) 7965 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7966 if (EL.hasAnyInfo()) return EL; 7967 break; 7968 } 7969 case ICmpInst::ICMP_SLT: 7970 case ICmpInst::ICMP_ULT: { // while (X < Y) 7971 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7972 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7973 AllowPredicates); 7974 if (EL.hasAnyInfo()) return EL; 7975 break; 7976 } 7977 case ICmpInst::ICMP_SGT: 7978 case ICmpInst::ICMP_UGT: { // while (X > Y) 7979 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7980 ExitLimit EL = 7981 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7982 AllowPredicates); 7983 if (EL.hasAnyInfo()) return EL; 7984 break; 7985 } 7986 default: 7987 break; 7988 } 7989 7990 auto *ExhaustiveCount = 7991 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7992 7993 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7994 return ExhaustiveCount; 7995 7996 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7997 ExitCond->getOperand(1), L, OriginalPred); 7998 } 7999 8000 ScalarEvolution::ExitLimit 8001 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8002 SwitchInst *Switch, 8003 BasicBlock *ExitingBlock, 8004 bool ControlsExit) { 8005 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8006 8007 // Give up if the exit is the default dest of a switch. 8008 if (Switch->getDefaultDest() == ExitingBlock) 8009 return getCouldNotCompute(); 8010 8011 assert(L->contains(Switch->getDefaultDest()) && 8012 "Default case must not exit the loop!"); 8013 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8014 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8015 8016 // while (X != Y) --> while (X-Y != 0) 8017 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8018 if (EL.hasAnyInfo()) 8019 return EL; 8020 8021 return getCouldNotCompute(); 8022 } 8023 8024 static ConstantInt * 8025 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8026 ScalarEvolution &SE) { 8027 const SCEV *InVal = SE.getConstant(C); 8028 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8029 assert(isa<SCEVConstant>(Val) && 8030 "Evaluation of SCEV at constant didn't fold correctly?"); 8031 return cast<SCEVConstant>(Val)->getValue(); 8032 } 8033 8034 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8035 /// compute the backedge execution count. 8036 ScalarEvolution::ExitLimit 8037 ScalarEvolution::computeLoadConstantCompareExitLimit( 8038 LoadInst *LI, 8039 Constant *RHS, 8040 const Loop *L, 8041 ICmpInst::Predicate predicate) { 8042 if (LI->isVolatile()) return getCouldNotCompute(); 8043 8044 // Check to see if the loaded pointer is a getelementptr of a global. 8045 // TODO: Use SCEV instead of manually grubbing with GEPs. 8046 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8047 if (!GEP) return getCouldNotCompute(); 8048 8049 // Make sure that it is really a constant global we are gepping, with an 8050 // initializer, and make sure the first IDX is really 0. 8051 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8052 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8053 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8054 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8055 return getCouldNotCompute(); 8056 8057 // Okay, we allow one non-constant index into the GEP instruction. 8058 Value *VarIdx = nullptr; 8059 std::vector<Constant*> Indexes; 8060 unsigned VarIdxNum = 0; 8061 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8062 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8063 Indexes.push_back(CI); 8064 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8065 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8066 VarIdx = GEP->getOperand(i); 8067 VarIdxNum = i-2; 8068 Indexes.push_back(nullptr); 8069 } 8070 8071 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8072 if (!VarIdx) 8073 return getCouldNotCompute(); 8074 8075 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8076 // Check to see if X is a loop variant variable value now. 8077 const SCEV *Idx = getSCEV(VarIdx); 8078 Idx = getSCEVAtScope(Idx, L); 8079 8080 // We can only recognize very limited forms of loop index expressions, in 8081 // particular, only affine AddRec's like {C1,+,C2}<L>. 8082 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8083 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8084 isLoopInvariant(IdxExpr, L) || 8085 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8086 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8087 return getCouldNotCompute(); 8088 8089 unsigned MaxSteps = MaxBruteForceIterations; 8090 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8091 ConstantInt *ItCst = ConstantInt::get( 8092 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8093 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8094 8095 // Form the GEP offset. 8096 Indexes[VarIdxNum] = Val; 8097 8098 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8099 Indexes); 8100 if (!Result) break; // Cannot compute! 8101 8102 // Evaluate the condition for this iteration. 8103 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8104 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8105 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8106 ++NumArrayLenItCounts; 8107 return getConstant(ItCst); // Found terminating iteration! 8108 } 8109 } 8110 return getCouldNotCompute(); 8111 } 8112 8113 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8114 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8115 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8116 if (!RHS) 8117 return getCouldNotCompute(); 8118 8119 const BasicBlock *Latch = L->getLoopLatch(); 8120 if (!Latch) 8121 return getCouldNotCompute(); 8122 8123 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8124 if (!Predecessor) 8125 return getCouldNotCompute(); 8126 8127 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8128 // Return LHS in OutLHS and shift_opt in OutOpCode. 8129 auto MatchPositiveShift = 8130 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8131 8132 using namespace PatternMatch; 8133 8134 ConstantInt *ShiftAmt; 8135 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8136 OutOpCode = Instruction::LShr; 8137 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8138 OutOpCode = Instruction::AShr; 8139 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8140 OutOpCode = Instruction::Shl; 8141 else 8142 return false; 8143 8144 return ShiftAmt->getValue().isStrictlyPositive(); 8145 }; 8146 8147 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8148 // 8149 // loop: 8150 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8151 // %iv.shifted = lshr i32 %iv, <positive constant> 8152 // 8153 // Return true on a successful match. Return the corresponding PHI node (%iv 8154 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8155 auto MatchShiftRecurrence = 8156 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8157 Optional<Instruction::BinaryOps> PostShiftOpCode; 8158 8159 { 8160 Instruction::BinaryOps OpC; 8161 Value *V; 8162 8163 // If we encounter a shift instruction, "peel off" the shift operation, 8164 // and remember that we did so. Later when we inspect %iv's backedge 8165 // value, we will make sure that the backedge value uses the same 8166 // operation. 8167 // 8168 // Note: the peeled shift operation does not have to be the same 8169 // instruction as the one feeding into the PHI's backedge value. We only 8170 // really care about it being the same *kind* of shift instruction -- 8171 // that's all that is required for our later inferences to hold. 8172 if (MatchPositiveShift(LHS, V, OpC)) { 8173 PostShiftOpCode = OpC; 8174 LHS = V; 8175 } 8176 } 8177 8178 PNOut = dyn_cast<PHINode>(LHS); 8179 if (!PNOut || PNOut->getParent() != L->getHeader()) 8180 return false; 8181 8182 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8183 Value *OpLHS; 8184 8185 return 8186 // The backedge value for the PHI node must be a shift by a positive 8187 // amount 8188 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8189 8190 // of the PHI node itself 8191 OpLHS == PNOut && 8192 8193 // and the kind of shift should be match the kind of shift we peeled 8194 // off, if any. 8195 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8196 }; 8197 8198 PHINode *PN; 8199 Instruction::BinaryOps OpCode; 8200 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8201 return getCouldNotCompute(); 8202 8203 const DataLayout &DL = getDataLayout(); 8204 8205 // The key rationale for this optimization is that for some kinds of shift 8206 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8207 // within a finite number of iterations. If the condition guarding the 8208 // backedge (in the sense that the backedge is taken if the condition is true) 8209 // is false for the value the shift recurrence stabilizes to, then we know 8210 // that the backedge is taken only a finite number of times. 8211 8212 ConstantInt *StableValue = nullptr; 8213 switch (OpCode) { 8214 default: 8215 llvm_unreachable("Impossible case!"); 8216 8217 case Instruction::AShr: { 8218 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8219 // bitwidth(K) iterations. 8220 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8221 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8222 Predecessor->getTerminator(), &DT); 8223 auto *Ty = cast<IntegerType>(RHS->getType()); 8224 if (Known.isNonNegative()) 8225 StableValue = ConstantInt::get(Ty, 0); 8226 else if (Known.isNegative()) 8227 StableValue = ConstantInt::get(Ty, -1, true); 8228 else 8229 return getCouldNotCompute(); 8230 8231 break; 8232 } 8233 case Instruction::LShr: 8234 case Instruction::Shl: 8235 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8236 // stabilize to 0 in at most bitwidth(K) iterations. 8237 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8238 break; 8239 } 8240 8241 auto *Result = 8242 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8243 assert(Result->getType()->isIntegerTy(1) && 8244 "Otherwise cannot be an operand to a branch instruction"); 8245 8246 if (Result->isZeroValue()) { 8247 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8248 const SCEV *UpperBound = 8249 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8250 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8251 } 8252 8253 return getCouldNotCompute(); 8254 } 8255 8256 /// Return true if we can constant fold an instruction of the specified type, 8257 /// assuming that all operands were constants. 8258 static bool CanConstantFold(const Instruction *I) { 8259 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8260 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8261 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8262 return true; 8263 8264 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8265 if (const Function *F = CI->getCalledFunction()) 8266 return canConstantFoldCallTo(CI, F); 8267 return false; 8268 } 8269 8270 /// Determine whether this instruction can constant evolve within this loop 8271 /// assuming its operands can all constant evolve. 8272 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8273 // An instruction outside of the loop can't be derived from a loop PHI. 8274 if (!L->contains(I)) return false; 8275 8276 if (isa<PHINode>(I)) { 8277 // We don't currently keep track of the control flow needed to evaluate 8278 // PHIs, so we cannot handle PHIs inside of loops. 8279 return L->getHeader() == I->getParent(); 8280 } 8281 8282 // If we won't be able to constant fold this expression even if the operands 8283 // are constants, bail early. 8284 return CanConstantFold(I); 8285 } 8286 8287 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8288 /// recursing through each instruction operand until reaching a loop header phi. 8289 static PHINode * 8290 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8291 DenseMap<Instruction *, PHINode *> &PHIMap, 8292 unsigned Depth) { 8293 if (Depth > MaxConstantEvolvingDepth) 8294 return nullptr; 8295 8296 // Otherwise, we can evaluate this instruction if all of its operands are 8297 // constant or derived from a PHI node themselves. 8298 PHINode *PHI = nullptr; 8299 for (Value *Op : UseInst->operands()) { 8300 if (isa<Constant>(Op)) continue; 8301 8302 Instruction *OpInst = dyn_cast<Instruction>(Op); 8303 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8304 8305 PHINode *P = dyn_cast<PHINode>(OpInst); 8306 if (!P) 8307 // If this operand is already visited, reuse the prior result. 8308 // We may have P != PHI if this is the deepest point at which the 8309 // inconsistent paths meet. 8310 P = PHIMap.lookup(OpInst); 8311 if (!P) { 8312 // Recurse and memoize the results, whether a phi is found or not. 8313 // This recursive call invalidates pointers into PHIMap. 8314 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8315 PHIMap[OpInst] = P; 8316 } 8317 if (!P) 8318 return nullptr; // Not evolving from PHI 8319 if (PHI && PHI != P) 8320 return nullptr; // Evolving from multiple different PHIs. 8321 PHI = P; 8322 } 8323 // This is a expression evolving from a constant PHI! 8324 return PHI; 8325 } 8326 8327 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8328 /// in the loop that V is derived from. We allow arbitrary operations along the 8329 /// way, but the operands of an operation must either be constants or a value 8330 /// derived from a constant PHI. If this expression does not fit with these 8331 /// constraints, return null. 8332 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8333 Instruction *I = dyn_cast<Instruction>(V); 8334 if (!I || !canConstantEvolve(I, L)) return nullptr; 8335 8336 if (PHINode *PN = dyn_cast<PHINode>(I)) 8337 return PN; 8338 8339 // Record non-constant instructions contained by the loop. 8340 DenseMap<Instruction *, PHINode *> PHIMap; 8341 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8342 } 8343 8344 /// EvaluateExpression - Given an expression that passes the 8345 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8346 /// in the loop has the value PHIVal. If we can't fold this expression for some 8347 /// reason, return null. 8348 static Constant *EvaluateExpression(Value *V, const Loop *L, 8349 DenseMap<Instruction *, Constant *> &Vals, 8350 const DataLayout &DL, 8351 const TargetLibraryInfo *TLI) { 8352 // Convenient constant check, but redundant for recursive calls. 8353 if (Constant *C = dyn_cast<Constant>(V)) return C; 8354 Instruction *I = dyn_cast<Instruction>(V); 8355 if (!I) return nullptr; 8356 8357 if (Constant *C = Vals.lookup(I)) return C; 8358 8359 // An instruction inside the loop depends on a value outside the loop that we 8360 // weren't given a mapping for, or a value such as a call inside the loop. 8361 if (!canConstantEvolve(I, L)) return nullptr; 8362 8363 // An unmapped PHI can be due to a branch or another loop inside this loop, 8364 // or due to this not being the initial iteration through a loop where we 8365 // couldn't compute the evolution of this particular PHI last time. 8366 if (isa<PHINode>(I)) return nullptr; 8367 8368 std::vector<Constant*> Operands(I->getNumOperands()); 8369 8370 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8371 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8372 if (!Operand) { 8373 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8374 if (!Operands[i]) return nullptr; 8375 continue; 8376 } 8377 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8378 Vals[Operand] = C; 8379 if (!C) return nullptr; 8380 Operands[i] = C; 8381 } 8382 8383 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8384 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8385 Operands[1], DL, TLI); 8386 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8387 if (!LI->isVolatile()) 8388 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8389 } 8390 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8391 } 8392 8393 8394 // If every incoming value to PN except the one for BB is a specific Constant, 8395 // return that, else return nullptr. 8396 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8397 Constant *IncomingVal = nullptr; 8398 8399 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8400 if (PN->getIncomingBlock(i) == BB) 8401 continue; 8402 8403 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8404 if (!CurrentVal) 8405 return nullptr; 8406 8407 if (IncomingVal != CurrentVal) { 8408 if (IncomingVal) 8409 return nullptr; 8410 IncomingVal = CurrentVal; 8411 } 8412 } 8413 8414 return IncomingVal; 8415 } 8416 8417 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8418 /// in the header of its containing loop, we know the loop executes a 8419 /// constant number of times, and the PHI node is just a recurrence 8420 /// involving constants, fold it. 8421 Constant * 8422 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8423 const APInt &BEs, 8424 const Loop *L) { 8425 auto I = ConstantEvolutionLoopExitValue.find(PN); 8426 if (I != ConstantEvolutionLoopExitValue.end()) 8427 return I->second; 8428 8429 if (BEs.ugt(MaxBruteForceIterations)) 8430 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8431 8432 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8433 8434 DenseMap<Instruction *, Constant *> CurrentIterVals; 8435 BasicBlock *Header = L->getHeader(); 8436 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8437 8438 BasicBlock *Latch = L->getLoopLatch(); 8439 if (!Latch) 8440 return nullptr; 8441 8442 for (PHINode &PHI : Header->phis()) { 8443 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8444 CurrentIterVals[&PHI] = StartCST; 8445 } 8446 if (!CurrentIterVals.count(PN)) 8447 return RetVal = nullptr; 8448 8449 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8450 8451 // Execute the loop symbolically to determine the exit value. 8452 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8453 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8454 8455 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8456 unsigned IterationNum = 0; 8457 const DataLayout &DL = getDataLayout(); 8458 for (; ; ++IterationNum) { 8459 if (IterationNum == NumIterations) 8460 return RetVal = CurrentIterVals[PN]; // Got exit value! 8461 8462 // Compute the value of the PHIs for the next iteration. 8463 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8464 DenseMap<Instruction *, Constant *> NextIterVals; 8465 Constant *NextPHI = 8466 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8467 if (!NextPHI) 8468 return nullptr; // Couldn't evaluate! 8469 NextIterVals[PN] = NextPHI; 8470 8471 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8472 8473 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8474 // cease to be able to evaluate one of them or if they stop evolving, 8475 // because that doesn't necessarily prevent us from computing PN. 8476 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8477 for (const auto &I : CurrentIterVals) { 8478 PHINode *PHI = dyn_cast<PHINode>(I.first); 8479 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8480 PHIsToCompute.emplace_back(PHI, I.second); 8481 } 8482 // We use two distinct loops because EvaluateExpression may invalidate any 8483 // iterators into CurrentIterVals. 8484 for (const auto &I : PHIsToCompute) { 8485 PHINode *PHI = I.first; 8486 Constant *&NextPHI = NextIterVals[PHI]; 8487 if (!NextPHI) { // Not already computed. 8488 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8489 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8490 } 8491 if (NextPHI != I.second) 8492 StoppedEvolving = false; 8493 } 8494 8495 // If all entries in CurrentIterVals == NextIterVals then we can stop 8496 // iterating, the loop can't continue to change. 8497 if (StoppedEvolving) 8498 return RetVal = CurrentIterVals[PN]; 8499 8500 CurrentIterVals.swap(NextIterVals); 8501 } 8502 } 8503 8504 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8505 Value *Cond, 8506 bool ExitWhen) { 8507 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8508 if (!PN) return getCouldNotCompute(); 8509 8510 // If the loop is canonicalized, the PHI will have exactly two entries. 8511 // That's the only form we support here. 8512 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8513 8514 DenseMap<Instruction *, Constant *> CurrentIterVals; 8515 BasicBlock *Header = L->getHeader(); 8516 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8517 8518 BasicBlock *Latch = L->getLoopLatch(); 8519 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8520 8521 for (PHINode &PHI : Header->phis()) { 8522 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8523 CurrentIterVals[&PHI] = StartCST; 8524 } 8525 if (!CurrentIterVals.count(PN)) 8526 return getCouldNotCompute(); 8527 8528 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8529 // the loop symbolically to determine when the condition gets a value of 8530 // "ExitWhen". 8531 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8532 const DataLayout &DL = getDataLayout(); 8533 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8534 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8535 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8536 8537 // Couldn't symbolically evaluate. 8538 if (!CondVal) return getCouldNotCompute(); 8539 8540 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8541 ++NumBruteForceTripCountsComputed; 8542 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8543 } 8544 8545 // Update all the PHI nodes for the next iteration. 8546 DenseMap<Instruction *, Constant *> NextIterVals; 8547 8548 // Create a list of which PHIs we need to compute. We want to do this before 8549 // calling EvaluateExpression on them because that may invalidate iterators 8550 // into CurrentIterVals. 8551 SmallVector<PHINode *, 8> PHIsToCompute; 8552 for (const auto &I : CurrentIterVals) { 8553 PHINode *PHI = dyn_cast<PHINode>(I.first); 8554 if (!PHI || PHI->getParent() != Header) continue; 8555 PHIsToCompute.push_back(PHI); 8556 } 8557 for (PHINode *PHI : PHIsToCompute) { 8558 Constant *&NextPHI = NextIterVals[PHI]; 8559 if (NextPHI) continue; // Already computed! 8560 8561 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8562 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8563 } 8564 CurrentIterVals.swap(NextIterVals); 8565 } 8566 8567 // Too many iterations were needed to evaluate. 8568 return getCouldNotCompute(); 8569 } 8570 8571 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8572 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8573 ValuesAtScopes[V]; 8574 // Check to see if we've folded this expression at this loop before. 8575 for (auto &LS : Values) 8576 if (LS.first == L) 8577 return LS.second ? LS.second : V; 8578 8579 Values.emplace_back(L, nullptr); 8580 8581 // Otherwise compute it. 8582 const SCEV *C = computeSCEVAtScope(V, L); 8583 for (auto &LS : reverse(ValuesAtScopes[V])) 8584 if (LS.first == L) { 8585 LS.second = C; 8586 break; 8587 } 8588 return C; 8589 } 8590 8591 /// This builds up a Constant using the ConstantExpr interface. That way, we 8592 /// will return Constants for objects which aren't represented by a 8593 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8594 /// Returns NULL if the SCEV isn't representable as a Constant. 8595 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8596 switch (V->getSCEVType()) { 8597 case scCouldNotCompute: 8598 case scAddRecExpr: 8599 return nullptr; 8600 case scConstant: 8601 return cast<SCEVConstant>(V)->getValue(); 8602 case scUnknown: 8603 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8604 case scSignExtend: { 8605 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8606 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8607 return ConstantExpr::getSExt(CastOp, SS->getType()); 8608 return nullptr; 8609 } 8610 case scZeroExtend: { 8611 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8612 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8613 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8614 return nullptr; 8615 } 8616 case scPtrToInt: { 8617 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8618 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8619 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8620 8621 return nullptr; 8622 } 8623 case scTruncate: { 8624 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8625 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8626 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8627 return nullptr; 8628 } 8629 case scAddExpr: { 8630 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8631 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8632 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8633 unsigned AS = PTy->getAddressSpace(); 8634 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8635 C = ConstantExpr::getBitCast(C, DestPtrTy); 8636 } 8637 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8638 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8639 if (!C2) 8640 return nullptr; 8641 8642 // First pointer! 8643 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8644 unsigned AS = C2->getType()->getPointerAddressSpace(); 8645 std::swap(C, C2); 8646 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8647 // The offsets have been converted to bytes. We can add bytes to an 8648 // i8* by GEP with the byte count in the first index. 8649 C = ConstantExpr::getBitCast(C, DestPtrTy); 8650 } 8651 8652 // Don't bother trying to sum two pointers. We probably can't 8653 // statically compute a load that results from it anyway. 8654 if (C2->getType()->isPointerTy()) 8655 return nullptr; 8656 8657 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8658 if (PTy->getElementType()->isStructTy()) 8659 C2 = ConstantExpr::getIntegerCast( 8660 C2, Type::getInt32Ty(C->getContext()), true); 8661 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8662 } else 8663 C = ConstantExpr::getAdd(C, C2); 8664 } 8665 return C; 8666 } 8667 return nullptr; 8668 } 8669 case scMulExpr: { 8670 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8671 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8672 // Don't bother with pointers at all. 8673 if (C->getType()->isPointerTy()) 8674 return nullptr; 8675 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8676 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8677 if (!C2 || C2->getType()->isPointerTy()) 8678 return nullptr; 8679 C = ConstantExpr::getMul(C, C2); 8680 } 8681 return C; 8682 } 8683 return nullptr; 8684 } 8685 case scUDivExpr: { 8686 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8687 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8688 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8689 if (LHS->getType() == RHS->getType()) 8690 return ConstantExpr::getUDiv(LHS, RHS); 8691 return nullptr; 8692 } 8693 case scSMaxExpr: 8694 case scUMaxExpr: 8695 case scSMinExpr: 8696 case scUMinExpr: 8697 return nullptr; // TODO: smax, umax, smin, umax. 8698 } 8699 llvm_unreachable("Unknown SCEV kind!"); 8700 } 8701 8702 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8703 if (isa<SCEVConstant>(V)) return V; 8704 8705 // If this instruction is evolved from a constant-evolving PHI, compute the 8706 // exit value from the loop without using SCEVs. 8707 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8708 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8709 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8710 const Loop *CurrLoop = this->LI[I->getParent()]; 8711 // Looking for loop exit value. 8712 if (CurrLoop && CurrLoop->getParentLoop() == L && 8713 PN->getParent() == CurrLoop->getHeader()) { 8714 // Okay, there is no closed form solution for the PHI node. Check 8715 // to see if the loop that contains it has a known backedge-taken 8716 // count. If so, we may be able to force computation of the exit 8717 // value. 8718 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8719 // This trivial case can show up in some degenerate cases where 8720 // the incoming IR has not yet been fully simplified. 8721 if (BackedgeTakenCount->isZero()) { 8722 Value *InitValue = nullptr; 8723 bool MultipleInitValues = false; 8724 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8725 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8726 if (!InitValue) 8727 InitValue = PN->getIncomingValue(i); 8728 else if (InitValue != PN->getIncomingValue(i)) { 8729 MultipleInitValues = true; 8730 break; 8731 } 8732 } 8733 } 8734 if (!MultipleInitValues && InitValue) 8735 return getSCEV(InitValue); 8736 } 8737 // Do we have a loop invariant value flowing around the backedge 8738 // for a loop which must execute the backedge? 8739 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8740 isKnownPositive(BackedgeTakenCount) && 8741 PN->getNumIncomingValues() == 2) { 8742 8743 unsigned InLoopPred = 8744 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8745 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8746 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8747 return getSCEV(BackedgeVal); 8748 } 8749 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8750 // Okay, we know how many times the containing loop executes. If 8751 // this is a constant evolving PHI node, get the final value at 8752 // the specified iteration number. 8753 Constant *RV = getConstantEvolutionLoopExitValue( 8754 PN, BTCC->getAPInt(), CurrLoop); 8755 if (RV) return getSCEV(RV); 8756 } 8757 } 8758 8759 // If there is a single-input Phi, evaluate it at our scope. If we can 8760 // prove that this replacement does not break LCSSA form, use new value. 8761 if (PN->getNumOperands() == 1) { 8762 const SCEV *Input = getSCEV(PN->getOperand(0)); 8763 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8764 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8765 // for the simplest case just support constants. 8766 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8767 } 8768 } 8769 8770 // Okay, this is an expression that we cannot symbolically evaluate 8771 // into a SCEV. Check to see if it's possible to symbolically evaluate 8772 // the arguments into constants, and if so, try to constant propagate the 8773 // result. This is particularly useful for computing loop exit values. 8774 if (CanConstantFold(I)) { 8775 SmallVector<Constant *, 4> Operands; 8776 bool MadeImprovement = false; 8777 for (Value *Op : I->operands()) { 8778 if (Constant *C = dyn_cast<Constant>(Op)) { 8779 Operands.push_back(C); 8780 continue; 8781 } 8782 8783 // If any of the operands is non-constant and if they are 8784 // non-integer and non-pointer, don't even try to analyze them 8785 // with scev techniques. 8786 if (!isSCEVable(Op->getType())) 8787 return V; 8788 8789 const SCEV *OrigV = getSCEV(Op); 8790 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8791 MadeImprovement |= OrigV != OpV; 8792 8793 Constant *C = BuildConstantFromSCEV(OpV); 8794 if (!C) return V; 8795 if (C->getType() != Op->getType()) 8796 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8797 Op->getType(), 8798 false), 8799 C, Op->getType()); 8800 Operands.push_back(C); 8801 } 8802 8803 // Check to see if getSCEVAtScope actually made an improvement. 8804 if (MadeImprovement) { 8805 Constant *C = nullptr; 8806 const DataLayout &DL = getDataLayout(); 8807 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8808 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8809 Operands[1], DL, &TLI); 8810 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8811 if (!Load->isVolatile()) 8812 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8813 DL); 8814 } else 8815 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8816 if (!C) return V; 8817 return getSCEV(C); 8818 } 8819 } 8820 } 8821 8822 // This is some other type of SCEVUnknown, just return it. 8823 return V; 8824 } 8825 8826 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8827 // Avoid performing the look-up in the common case where the specified 8828 // expression has no loop-variant portions. 8829 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8830 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8831 if (OpAtScope != Comm->getOperand(i)) { 8832 // Okay, at least one of these operands is loop variant but might be 8833 // foldable. Build a new instance of the folded commutative expression. 8834 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8835 Comm->op_begin()+i); 8836 NewOps.push_back(OpAtScope); 8837 8838 for (++i; i != e; ++i) { 8839 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8840 NewOps.push_back(OpAtScope); 8841 } 8842 if (isa<SCEVAddExpr>(Comm)) 8843 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8844 if (isa<SCEVMulExpr>(Comm)) 8845 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8846 if (isa<SCEVMinMaxExpr>(Comm)) 8847 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8848 llvm_unreachable("Unknown commutative SCEV type!"); 8849 } 8850 } 8851 // If we got here, all operands are loop invariant. 8852 return Comm; 8853 } 8854 8855 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8856 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8857 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8858 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8859 return Div; // must be loop invariant 8860 return getUDivExpr(LHS, RHS); 8861 } 8862 8863 // If this is a loop recurrence for a loop that does not contain L, then we 8864 // are dealing with the final value computed by the loop. 8865 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8866 // First, attempt to evaluate each operand. 8867 // Avoid performing the look-up in the common case where the specified 8868 // expression has no loop-variant portions. 8869 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8870 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8871 if (OpAtScope == AddRec->getOperand(i)) 8872 continue; 8873 8874 // Okay, at least one of these operands is loop variant but might be 8875 // foldable. Build a new instance of the folded commutative expression. 8876 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8877 AddRec->op_begin()+i); 8878 NewOps.push_back(OpAtScope); 8879 for (++i; i != e; ++i) 8880 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8881 8882 const SCEV *FoldedRec = 8883 getAddRecExpr(NewOps, AddRec->getLoop(), 8884 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8885 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8886 // The addrec may be folded to a nonrecurrence, for example, if the 8887 // induction variable is multiplied by zero after constant folding. Go 8888 // ahead and return the folded value. 8889 if (!AddRec) 8890 return FoldedRec; 8891 break; 8892 } 8893 8894 // If the scope is outside the addrec's loop, evaluate it by using the 8895 // loop exit value of the addrec. 8896 if (!AddRec->getLoop()->contains(L)) { 8897 // To evaluate this recurrence, we need to know how many times the AddRec 8898 // loop iterates. Compute this now. 8899 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8900 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8901 8902 // Then, evaluate the AddRec. 8903 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8904 } 8905 8906 return AddRec; 8907 } 8908 8909 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8910 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8911 if (Op == Cast->getOperand()) 8912 return Cast; // must be loop invariant 8913 return getZeroExtendExpr(Op, Cast->getType()); 8914 } 8915 8916 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8917 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8918 if (Op == Cast->getOperand()) 8919 return Cast; // must be loop invariant 8920 return getSignExtendExpr(Op, Cast->getType()); 8921 } 8922 8923 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8924 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8925 if (Op == Cast->getOperand()) 8926 return Cast; // must be loop invariant 8927 return getTruncateExpr(Op, Cast->getType()); 8928 } 8929 8930 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8931 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8932 if (Op == Cast->getOperand()) 8933 return Cast; // must be loop invariant 8934 return getPtrToIntExpr(Op, Cast->getType()); 8935 } 8936 8937 llvm_unreachable("Unknown SCEV type!"); 8938 } 8939 8940 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8941 return getSCEVAtScope(getSCEV(V), L); 8942 } 8943 8944 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8945 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8946 return stripInjectiveFunctions(ZExt->getOperand()); 8947 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8948 return stripInjectiveFunctions(SExt->getOperand()); 8949 return S; 8950 } 8951 8952 /// Finds the minimum unsigned root of the following equation: 8953 /// 8954 /// A * X = B (mod N) 8955 /// 8956 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8957 /// A and B isn't important. 8958 /// 8959 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8960 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8961 ScalarEvolution &SE) { 8962 uint32_t BW = A.getBitWidth(); 8963 assert(BW == SE.getTypeSizeInBits(B->getType())); 8964 assert(A != 0 && "A must be non-zero."); 8965 8966 // 1. D = gcd(A, N) 8967 // 8968 // The gcd of A and N may have only one prime factor: 2. The number of 8969 // trailing zeros in A is its multiplicity 8970 uint32_t Mult2 = A.countTrailingZeros(); 8971 // D = 2^Mult2 8972 8973 // 2. Check if B is divisible by D. 8974 // 8975 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8976 // is not less than multiplicity of this prime factor for D. 8977 if (SE.GetMinTrailingZeros(B) < Mult2) 8978 return SE.getCouldNotCompute(); 8979 8980 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8981 // modulo (N / D). 8982 // 8983 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8984 // (N / D) in general. The inverse itself always fits into BW bits, though, 8985 // so we immediately truncate it. 8986 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8987 APInt Mod(BW + 1, 0); 8988 Mod.setBit(BW - Mult2); // Mod = N / D 8989 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8990 8991 // 4. Compute the minimum unsigned root of the equation: 8992 // I * (B / D) mod (N / D) 8993 // To simplify the computation, we factor out the divide by D: 8994 // (I * B mod N) / D 8995 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8996 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8997 } 8998 8999 /// For a given quadratic addrec, generate coefficients of the corresponding 9000 /// quadratic equation, multiplied by a common value to ensure that they are 9001 /// integers. 9002 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9003 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9004 /// were multiplied by, and BitWidth is the bit width of the original addrec 9005 /// coefficients. 9006 /// This function returns None if the addrec coefficients are not compile- 9007 /// time constants. 9008 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9009 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9010 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9011 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9012 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9013 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9014 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9015 << *AddRec << '\n'); 9016 9017 // We currently can only solve this if the coefficients are constants. 9018 if (!LC || !MC || !NC) { 9019 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9020 return None; 9021 } 9022 9023 APInt L = LC->getAPInt(); 9024 APInt M = MC->getAPInt(); 9025 APInt N = NC->getAPInt(); 9026 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9027 9028 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9029 unsigned NewWidth = BitWidth + 1; 9030 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9031 << BitWidth << '\n'); 9032 // The sign-extension (as opposed to a zero-extension) here matches the 9033 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9034 N = N.sext(NewWidth); 9035 M = M.sext(NewWidth); 9036 L = L.sext(NewWidth); 9037 9038 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9039 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9040 // L+M, L+2M+N, L+3M+3N, ... 9041 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9042 // 9043 // The equation Acc = 0 is then 9044 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9045 // In a quadratic form it becomes: 9046 // N n^2 + (2M-N) n + 2L = 0. 9047 9048 APInt A = N; 9049 APInt B = 2 * M - A; 9050 APInt C = 2 * L; 9051 APInt T = APInt(NewWidth, 2); 9052 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9053 << "x + " << C << ", coeff bw: " << NewWidth 9054 << ", multiplied by " << T << '\n'); 9055 return std::make_tuple(A, B, C, T, BitWidth); 9056 } 9057 9058 /// Helper function to compare optional APInts: 9059 /// (a) if X and Y both exist, return min(X, Y), 9060 /// (b) if neither X nor Y exist, return None, 9061 /// (c) if exactly one of X and Y exists, return that value. 9062 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9063 if (X.hasValue() && Y.hasValue()) { 9064 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9065 APInt XW = X->sextOrSelf(W); 9066 APInt YW = Y->sextOrSelf(W); 9067 return XW.slt(YW) ? *X : *Y; 9068 } 9069 if (!X.hasValue() && !Y.hasValue()) 9070 return None; 9071 return X.hasValue() ? *X : *Y; 9072 } 9073 9074 /// Helper function to truncate an optional APInt to a given BitWidth. 9075 /// When solving addrec-related equations, it is preferable to return a value 9076 /// that has the same bit width as the original addrec's coefficients. If the 9077 /// solution fits in the original bit width, truncate it (except for i1). 9078 /// Returning a value of a different bit width may inhibit some optimizations. 9079 /// 9080 /// In general, a solution to a quadratic equation generated from an addrec 9081 /// may require BW+1 bits, where BW is the bit width of the addrec's 9082 /// coefficients. The reason is that the coefficients of the quadratic 9083 /// equation are BW+1 bits wide (to avoid truncation when converting from 9084 /// the addrec to the equation). 9085 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9086 if (!X.hasValue()) 9087 return None; 9088 unsigned W = X->getBitWidth(); 9089 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9090 return X->trunc(BitWidth); 9091 return X; 9092 } 9093 9094 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9095 /// iterations. The values L, M, N are assumed to be signed, and they 9096 /// should all have the same bit widths. 9097 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9098 /// where BW is the bit width of the addrec's coefficients. 9099 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9100 /// returned as such, otherwise the bit width of the returned value may 9101 /// be greater than BW. 9102 /// 9103 /// This function returns None if 9104 /// (a) the addrec coefficients are not constant, or 9105 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9106 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9107 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9108 static Optional<APInt> 9109 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9110 APInt A, B, C, M; 9111 unsigned BitWidth; 9112 auto T = GetQuadraticEquation(AddRec); 9113 if (!T.hasValue()) 9114 return None; 9115 9116 std::tie(A, B, C, M, BitWidth) = *T; 9117 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9118 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9119 if (!X.hasValue()) 9120 return None; 9121 9122 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9123 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9124 if (!V->isZero()) 9125 return None; 9126 9127 return TruncIfPossible(X, BitWidth); 9128 } 9129 9130 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9131 /// iterations. The values M, N are assumed to be signed, and they 9132 /// should all have the same bit widths. 9133 /// Find the least n such that c(n) does not belong to the given range, 9134 /// while c(n-1) does. 9135 /// 9136 /// This function returns None if 9137 /// (a) the addrec coefficients are not constant, or 9138 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9139 /// bounds of the range. 9140 static Optional<APInt> 9141 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9142 const ConstantRange &Range, ScalarEvolution &SE) { 9143 assert(AddRec->getOperand(0)->isZero() && 9144 "Starting value of addrec should be 0"); 9145 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9146 << Range << ", addrec " << *AddRec << '\n'); 9147 // This case is handled in getNumIterationsInRange. Here we can assume that 9148 // we start in the range. 9149 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9150 "Addrec's initial value should be in range"); 9151 9152 APInt A, B, C, M; 9153 unsigned BitWidth; 9154 auto T = GetQuadraticEquation(AddRec); 9155 if (!T.hasValue()) 9156 return None; 9157 9158 // Be careful about the return value: there can be two reasons for not 9159 // returning an actual number. First, if no solutions to the equations 9160 // were found, and second, if the solutions don't leave the given range. 9161 // The first case means that the actual solution is "unknown", the second 9162 // means that it's known, but not valid. If the solution is unknown, we 9163 // cannot make any conclusions. 9164 // Return a pair: the optional solution and a flag indicating if the 9165 // solution was found. 9166 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9167 // Solve for signed overflow and unsigned overflow, pick the lower 9168 // solution. 9169 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9170 << Bound << " (before multiplying by " << M << ")\n"); 9171 Bound *= M; // The quadratic equation multiplier. 9172 9173 Optional<APInt> SO = None; 9174 if (BitWidth > 1) { 9175 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9176 "signed overflow\n"); 9177 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9178 } 9179 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9180 "unsigned overflow\n"); 9181 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9182 BitWidth+1); 9183 9184 auto LeavesRange = [&] (const APInt &X) { 9185 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9186 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9187 if (Range.contains(V0->getValue())) 9188 return false; 9189 // X should be at least 1, so X-1 is non-negative. 9190 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9191 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9192 if (Range.contains(V1->getValue())) 9193 return true; 9194 return false; 9195 }; 9196 9197 // If SolveQuadraticEquationWrap returns None, it means that there can 9198 // be a solution, but the function failed to find it. We cannot treat it 9199 // as "no solution". 9200 if (!SO.hasValue() || !UO.hasValue()) 9201 return { None, false }; 9202 9203 // Check the smaller value first to see if it leaves the range. 9204 // At this point, both SO and UO must have values. 9205 Optional<APInt> Min = MinOptional(SO, UO); 9206 if (LeavesRange(*Min)) 9207 return { Min, true }; 9208 Optional<APInt> Max = Min == SO ? UO : SO; 9209 if (LeavesRange(*Max)) 9210 return { Max, true }; 9211 9212 // Solutions were found, but were eliminated, hence the "true". 9213 return { None, true }; 9214 }; 9215 9216 std::tie(A, B, C, M, BitWidth) = *T; 9217 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9218 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9219 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9220 auto SL = SolveForBoundary(Lower); 9221 auto SU = SolveForBoundary(Upper); 9222 // If any of the solutions was unknown, no meaninigful conclusions can 9223 // be made. 9224 if (!SL.second || !SU.second) 9225 return None; 9226 9227 // Claim: The correct solution is not some value between Min and Max. 9228 // 9229 // Justification: Assuming that Min and Max are different values, one of 9230 // them is when the first signed overflow happens, the other is when the 9231 // first unsigned overflow happens. Crossing the range boundary is only 9232 // possible via an overflow (treating 0 as a special case of it, modeling 9233 // an overflow as crossing k*2^W for some k). 9234 // 9235 // The interesting case here is when Min was eliminated as an invalid 9236 // solution, but Max was not. The argument is that if there was another 9237 // overflow between Min and Max, it would also have been eliminated if 9238 // it was considered. 9239 // 9240 // For a given boundary, it is possible to have two overflows of the same 9241 // type (signed/unsigned) without having the other type in between: this 9242 // can happen when the vertex of the parabola is between the iterations 9243 // corresponding to the overflows. This is only possible when the two 9244 // overflows cross k*2^W for the same k. In such case, if the second one 9245 // left the range (and was the first one to do so), the first overflow 9246 // would have to enter the range, which would mean that either we had left 9247 // the range before or that we started outside of it. Both of these cases 9248 // are contradictions. 9249 // 9250 // Claim: In the case where SolveForBoundary returns None, the correct 9251 // solution is not some value between the Max for this boundary and the 9252 // Min of the other boundary. 9253 // 9254 // Justification: Assume that we had such Max_A and Min_B corresponding 9255 // to range boundaries A and B and such that Max_A < Min_B. If there was 9256 // a solution between Max_A and Min_B, it would have to be caused by an 9257 // overflow corresponding to either A or B. It cannot correspond to B, 9258 // since Min_B is the first occurrence of such an overflow. If it 9259 // corresponded to A, it would have to be either a signed or an unsigned 9260 // overflow that is larger than both eliminated overflows for A. But 9261 // between the eliminated overflows and this overflow, the values would 9262 // cover the entire value space, thus crossing the other boundary, which 9263 // is a contradiction. 9264 9265 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9266 } 9267 9268 ScalarEvolution::ExitLimit 9269 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9270 bool AllowPredicates) { 9271 9272 // This is only used for loops with a "x != y" exit test. The exit condition 9273 // is now expressed as a single expression, V = x-y. So the exit test is 9274 // effectively V != 0. We know and take advantage of the fact that this 9275 // expression only being used in a comparison by zero context. 9276 9277 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9278 // If the value is a constant 9279 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9280 // If the value is already zero, the branch will execute zero times. 9281 if (C->getValue()->isZero()) return C; 9282 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9283 } 9284 9285 const SCEVAddRecExpr *AddRec = 9286 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9287 9288 if (!AddRec && AllowPredicates) 9289 // Try to make this an AddRec using runtime tests, in the first X 9290 // iterations of this loop, where X is the SCEV expression found by the 9291 // algorithm below. 9292 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9293 9294 if (!AddRec || AddRec->getLoop() != L) 9295 return getCouldNotCompute(); 9296 9297 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9298 // the quadratic equation to solve it. 9299 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9300 // We can only use this value if the chrec ends up with an exact zero 9301 // value at this index. When solving for "X*X != 5", for example, we 9302 // should not accept a root of 2. 9303 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9304 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9305 return ExitLimit(R, R, false, Predicates); 9306 } 9307 return getCouldNotCompute(); 9308 } 9309 9310 // Otherwise we can only handle this if it is affine. 9311 if (!AddRec->isAffine()) 9312 return getCouldNotCompute(); 9313 9314 // If this is an affine expression, the execution count of this branch is 9315 // the minimum unsigned root of the following equation: 9316 // 9317 // Start + Step*N = 0 (mod 2^BW) 9318 // 9319 // equivalent to: 9320 // 9321 // Step*N = -Start (mod 2^BW) 9322 // 9323 // where BW is the common bit width of Start and Step. 9324 9325 // Get the initial value for the loop. 9326 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9327 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9328 9329 // For now we handle only constant steps. 9330 // 9331 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9332 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9333 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9334 // We have not yet seen any such cases. 9335 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9336 if (!StepC || StepC->getValue()->isZero()) 9337 return getCouldNotCompute(); 9338 9339 // For positive steps (counting up until unsigned overflow): 9340 // N = -Start/Step (as unsigned) 9341 // For negative steps (counting down to zero): 9342 // N = Start/-Step 9343 // First compute the unsigned distance from zero in the direction of Step. 9344 bool CountDown = StepC->getAPInt().isNegative(); 9345 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9346 9347 // Handle unitary steps, which cannot wraparound. 9348 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9349 // N = Distance (as unsigned) 9350 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9351 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9352 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9353 if (MaxBECountBase.ult(MaxBECount)) 9354 MaxBECount = MaxBECountBase; 9355 9356 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9357 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9358 // case, and see if we can improve the bound. 9359 // 9360 // Explicitly handling this here is necessary because getUnsignedRange 9361 // isn't context-sensitive; it doesn't know that we only care about the 9362 // range inside the loop. 9363 const SCEV *Zero = getZero(Distance->getType()); 9364 const SCEV *One = getOne(Distance->getType()); 9365 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9366 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9367 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9368 // as "unsigned_max(Distance + 1) - 1". 9369 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9370 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9371 } 9372 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9373 } 9374 9375 // If the condition controls loop exit (the loop exits only if the expression 9376 // is true) and the addition is no-wrap we can use unsigned divide to 9377 // compute the backedge count. In this case, the step may not divide the 9378 // distance, but we don't care because if the condition is "missed" the loop 9379 // will have undefined behavior due to wrapping. 9380 if (ControlsExit && AddRec->hasNoSelfWrap() && 9381 loopHasNoAbnormalExits(AddRec->getLoop())) { 9382 const SCEV *Exact = 9383 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9384 const SCEV *Max = getCouldNotCompute(); 9385 if (Exact != getCouldNotCompute()) { 9386 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9387 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9388 if (BaseMaxInt.ult(MaxInt)) 9389 Max = getConstant(BaseMaxInt); 9390 else 9391 Max = getConstant(MaxInt); 9392 } 9393 return ExitLimit(Exact, Max, false, Predicates); 9394 } 9395 9396 // Solve the general equation. 9397 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9398 getNegativeSCEV(Start), *this); 9399 const SCEV *M = E == getCouldNotCompute() 9400 ? E 9401 : getConstant(getUnsignedRangeMax(E)); 9402 return ExitLimit(E, M, false, Predicates); 9403 } 9404 9405 ScalarEvolution::ExitLimit 9406 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9407 // Loops that look like: while (X == 0) are very strange indeed. We don't 9408 // handle them yet except for the trivial case. This could be expanded in the 9409 // future as needed. 9410 9411 // If the value is a constant, check to see if it is known to be non-zero 9412 // already. If so, the backedge will execute zero times. 9413 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9414 if (!C->getValue()->isZero()) 9415 return getZero(C->getType()); 9416 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9417 } 9418 9419 // We could implement others, but I really doubt anyone writes loops like 9420 // this, and if they did, they would already be constant folded. 9421 return getCouldNotCompute(); 9422 } 9423 9424 std::pair<const BasicBlock *, const BasicBlock *> 9425 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9426 const { 9427 // If the block has a unique predecessor, then there is no path from the 9428 // predecessor to the block that does not go through the direct edge 9429 // from the predecessor to the block. 9430 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9431 return {Pred, BB}; 9432 9433 // A loop's header is defined to be a block that dominates the loop. 9434 // If the header has a unique predecessor outside the loop, it must be 9435 // a block that has exactly one successor that can reach the loop. 9436 if (const Loop *L = LI.getLoopFor(BB)) 9437 return {L->getLoopPredecessor(), L->getHeader()}; 9438 9439 return {nullptr, nullptr}; 9440 } 9441 9442 /// SCEV structural equivalence is usually sufficient for testing whether two 9443 /// expressions are equal, however for the purposes of looking for a condition 9444 /// guarding a loop, it can be useful to be a little more general, since a 9445 /// front-end may have replicated the controlling expression. 9446 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9447 // Quick check to see if they are the same SCEV. 9448 if (A == B) return true; 9449 9450 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9451 // Not all instructions that are "identical" compute the same value. For 9452 // instance, two distinct alloca instructions allocating the same type are 9453 // identical and do not read memory; but compute distinct values. 9454 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9455 }; 9456 9457 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9458 // two different instructions with the same value. Check for this case. 9459 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9460 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9461 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9462 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9463 if (ComputesEqualValues(AI, BI)) 9464 return true; 9465 9466 // Otherwise assume they may have a different value. 9467 return false; 9468 } 9469 9470 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9471 const SCEV *&LHS, const SCEV *&RHS, 9472 unsigned Depth) { 9473 bool Changed = false; 9474 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9475 // '0 != 0'. 9476 auto TrivialCase = [&](bool TriviallyTrue) { 9477 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9478 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9479 return true; 9480 }; 9481 // If we hit the max recursion limit bail out. 9482 if (Depth >= 3) 9483 return false; 9484 9485 // Canonicalize a constant to the right side. 9486 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9487 // Check for both operands constant. 9488 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9489 if (ConstantExpr::getICmp(Pred, 9490 LHSC->getValue(), 9491 RHSC->getValue())->isNullValue()) 9492 return TrivialCase(false); 9493 else 9494 return TrivialCase(true); 9495 } 9496 // Otherwise swap the operands to put the constant on the right. 9497 std::swap(LHS, RHS); 9498 Pred = ICmpInst::getSwappedPredicate(Pred); 9499 Changed = true; 9500 } 9501 9502 // If we're comparing an addrec with a value which is loop-invariant in the 9503 // addrec's loop, put the addrec on the left. Also make a dominance check, 9504 // as both operands could be addrecs loop-invariant in each other's loop. 9505 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9506 const Loop *L = AR->getLoop(); 9507 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9508 std::swap(LHS, RHS); 9509 Pred = ICmpInst::getSwappedPredicate(Pred); 9510 Changed = true; 9511 } 9512 } 9513 9514 // If there's a constant operand, canonicalize comparisons with boundary 9515 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9516 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9517 const APInt &RA = RC->getAPInt(); 9518 9519 bool SimplifiedByConstantRange = false; 9520 9521 if (!ICmpInst::isEquality(Pred)) { 9522 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9523 if (ExactCR.isFullSet()) 9524 return TrivialCase(true); 9525 else if (ExactCR.isEmptySet()) 9526 return TrivialCase(false); 9527 9528 APInt NewRHS; 9529 CmpInst::Predicate NewPred; 9530 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9531 ICmpInst::isEquality(NewPred)) { 9532 // We were able to convert an inequality to an equality. 9533 Pred = NewPred; 9534 RHS = getConstant(NewRHS); 9535 Changed = SimplifiedByConstantRange = true; 9536 } 9537 } 9538 9539 if (!SimplifiedByConstantRange) { 9540 switch (Pred) { 9541 default: 9542 break; 9543 case ICmpInst::ICMP_EQ: 9544 case ICmpInst::ICMP_NE: 9545 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9546 if (!RA) 9547 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9548 if (const SCEVMulExpr *ME = 9549 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9550 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9551 ME->getOperand(0)->isAllOnesValue()) { 9552 RHS = AE->getOperand(1); 9553 LHS = ME->getOperand(1); 9554 Changed = true; 9555 } 9556 break; 9557 9558 9559 // The "Should have been caught earlier!" messages refer to the fact 9560 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9561 // should have fired on the corresponding cases, and canonicalized the 9562 // check to trivial case. 9563 9564 case ICmpInst::ICMP_UGE: 9565 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9566 Pred = ICmpInst::ICMP_UGT; 9567 RHS = getConstant(RA - 1); 9568 Changed = true; 9569 break; 9570 case ICmpInst::ICMP_ULE: 9571 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9572 Pred = ICmpInst::ICMP_ULT; 9573 RHS = getConstant(RA + 1); 9574 Changed = true; 9575 break; 9576 case ICmpInst::ICMP_SGE: 9577 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9578 Pred = ICmpInst::ICMP_SGT; 9579 RHS = getConstant(RA - 1); 9580 Changed = true; 9581 break; 9582 case ICmpInst::ICMP_SLE: 9583 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9584 Pred = ICmpInst::ICMP_SLT; 9585 RHS = getConstant(RA + 1); 9586 Changed = true; 9587 break; 9588 } 9589 } 9590 } 9591 9592 // Check for obvious equality. 9593 if (HasSameValue(LHS, RHS)) { 9594 if (ICmpInst::isTrueWhenEqual(Pred)) 9595 return TrivialCase(true); 9596 if (ICmpInst::isFalseWhenEqual(Pred)) 9597 return TrivialCase(false); 9598 } 9599 9600 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9601 // adding or subtracting 1 from one of the operands. 9602 switch (Pred) { 9603 case ICmpInst::ICMP_SLE: 9604 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9605 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9606 SCEV::FlagNSW); 9607 Pred = ICmpInst::ICMP_SLT; 9608 Changed = true; 9609 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9610 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9611 SCEV::FlagNSW); 9612 Pred = ICmpInst::ICMP_SLT; 9613 Changed = true; 9614 } 9615 break; 9616 case ICmpInst::ICMP_SGE: 9617 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9618 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9619 SCEV::FlagNSW); 9620 Pred = ICmpInst::ICMP_SGT; 9621 Changed = true; 9622 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9623 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9624 SCEV::FlagNSW); 9625 Pred = ICmpInst::ICMP_SGT; 9626 Changed = true; 9627 } 9628 break; 9629 case ICmpInst::ICMP_ULE: 9630 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9631 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9632 SCEV::FlagNUW); 9633 Pred = ICmpInst::ICMP_ULT; 9634 Changed = true; 9635 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9636 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9637 Pred = ICmpInst::ICMP_ULT; 9638 Changed = true; 9639 } 9640 break; 9641 case ICmpInst::ICMP_UGE: 9642 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9643 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9644 Pred = ICmpInst::ICMP_UGT; 9645 Changed = true; 9646 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9647 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9648 SCEV::FlagNUW); 9649 Pred = ICmpInst::ICMP_UGT; 9650 Changed = true; 9651 } 9652 break; 9653 default: 9654 break; 9655 } 9656 9657 // TODO: More simplifications are possible here. 9658 9659 // Recursively simplify until we either hit a recursion limit or nothing 9660 // changes. 9661 if (Changed) 9662 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9663 9664 return Changed; 9665 } 9666 9667 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9668 return getSignedRangeMax(S).isNegative(); 9669 } 9670 9671 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9672 return getSignedRangeMin(S).isStrictlyPositive(); 9673 } 9674 9675 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9676 return !getSignedRangeMin(S).isNegative(); 9677 } 9678 9679 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9680 return !getSignedRangeMax(S).isStrictlyPositive(); 9681 } 9682 9683 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9684 return isKnownNegative(S) || isKnownPositive(S); 9685 } 9686 9687 std::pair<const SCEV *, const SCEV *> 9688 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9689 // Compute SCEV on entry of loop L. 9690 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9691 if (Start == getCouldNotCompute()) 9692 return { Start, Start }; 9693 // Compute post increment SCEV for loop L. 9694 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9695 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9696 return { Start, PostInc }; 9697 } 9698 9699 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9700 const SCEV *LHS, const SCEV *RHS) { 9701 // First collect all loops. 9702 SmallPtrSet<const Loop *, 8> LoopsUsed; 9703 getUsedLoops(LHS, LoopsUsed); 9704 getUsedLoops(RHS, LoopsUsed); 9705 9706 if (LoopsUsed.empty()) 9707 return false; 9708 9709 // Domination relationship must be a linear order on collected loops. 9710 #ifndef NDEBUG 9711 for (auto *L1 : LoopsUsed) 9712 for (auto *L2 : LoopsUsed) 9713 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9714 DT.dominates(L2->getHeader(), L1->getHeader())) && 9715 "Domination relationship is not a linear order"); 9716 #endif 9717 9718 const Loop *MDL = 9719 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9720 [&](const Loop *L1, const Loop *L2) { 9721 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9722 }); 9723 9724 // Get init and post increment value for LHS. 9725 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9726 // if LHS contains unknown non-invariant SCEV then bail out. 9727 if (SplitLHS.first == getCouldNotCompute()) 9728 return false; 9729 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9730 // Get init and post increment value for RHS. 9731 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9732 // if RHS contains unknown non-invariant SCEV then bail out. 9733 if (SplitRHS.first == getCouldNotCompute()) 9734 return false; 9735 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9736 // It is possible that init SCEV contains an invariant load but it does 9737 // not dominate MDL and is not available at MDL loop entry, so we should 9738 // check it here. 9739 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9740 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9741 return false; 9742 9743 // It seems backedge guard check is faster than entry one so in some cases 9744 // it can speed up whole estimation by short circuit 9745 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9746 SplitRHS.second) && 9747 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9748 } 9749 9750 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9751 const SCEV *LHS, const SCEV *RHS) { 9752 // Canonicalize the inputs first. 9753 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9754 9755 if (isKnownViaInduction(Pred, LHS, RHS)) 9756 return true; 9757 9758 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9759 return true; 9760 9761 // Otherwise see what can be done with some simple reasoning. 9762 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9763 } 9764 9765 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9766 const SCEV *LHS, 9767 const SCEV *RHS) { 9768 if (isKnownPredicate(Pred, LHS, RHS)) 9769 return true; 9770 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9771 return false; 9772 return None; 9773 } 9774 9775 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9776 const SCEV *LHS, const SCEV *RHS, 9777 const Instruction *Context) { 9778 // TODO: Analyze guards and assumes from Context's block. 9779 return isKnownPredicate(Pred, LHS, RHS) || 9780 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9781 } 9782 9783 Optional<bool> 9784 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9785 const SCEV *RHS, 9786 const Instruction *Context) { 9787 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9788 if (KnownWithoutContext) 9789 return KnownWithoutContext; 9790 9791 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9792 return true; 9793 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9794 ICmpInst::getInversePredicate(Pred), 9795 LHS, RHS)) 9796 return false; 9797 return None; 9798 } 9799 9800 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9801 const SCEVAddRecExpr *LHS, 9802 const SCEV *RHS) { 9803 const Loop *L = LHS->getLoop(); 9804 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9805 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9806 } 9807 9808 Optional<ScalarEvolution::MonotonicPredicateType> 9809 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9810 ICmpInst::Predicate Pred) { 9811 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9812 9813 #ifndef NDEBUG 9814 // Verify an invariant: inverting the predicate should turn a monotonically 9815 // increasing change to a monotonically decreasing one, and vice versa. 9816 if (Result) { 9817 auto ResultSwapped = 9818 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9819 9820 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9821 assert(ResultSwapped.getValue() != Result.getValue() && 9822 "monotonicity should flip as we flip the predicate"); 9823 } 9824 #endif 9825 9826 return Result; 9827 } 9828 9829 Optional<ScalarEvolution::MonotonicPredicateType> 9830 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9831 ICmpInst::Predicate Pred) { 9832 // A zero step value for LHS means the induction variable is essentially a 9833 // loop invariant value. We don't really depend on the predicate actually 9834 // flipping from false to true (for increasing predicates, and the other way 9835 // around for decreasing predicates), all we care about is that *if* the 9836 // predicate changes then it only changes from false to true. 9837 // 9838 // A zero step value in itself is not very useful, but there may be places 9839 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9840 // as general as possible. 9841 9842 // Only handle LE/LT/GE/GT predicates. 9843 if (!ICmpInst::isRelational(Pred)) 9844 return None; 9845 9846 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9847 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9848 "Should be greater or less!"); 9849 9850 // Check that AR does not wrap. 9851 if (ICmpInst::isUnsigned(Pred)) { 9852 if (!LHS->hasNoUnsignedWrap()) 9853 return None; 9854 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9855 } else { 9856 assert(ICmpInst::isSigned(Pred) && 9857 "Relational predicate is either signed or unsigned!"); 9858 if (!LHS->hasNoSignedWrap()) 9859 return None; 9860 9861 const SCEV *Step = LHS->getStepRecurrence(*this); 9862 9863 if (isKnownNonNegative(Step)) 9864 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9865 9866 if (isKnownNonPositive(Step)) 9867 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9868 9869 return None; 9870 } 9871 } 9872 9873 Optional<ScalarEvolution::LoopInvariantPredicate> 9874 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9875 const SCEV *LHS, const SCEV *RHS, 9876 const Loop *L) { 9877 9878 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9879 if (!isLoopInvariant(RHS, L)) { 9880 if (!isLoopInvariant(LHS, L)) 9881 return None; 9882 9883 std::swap(LHS, RHS); 9884 Pred = ICmpInst::getSwappedPredicate(Pred); 9885 } 9886 9887 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9888 if (!ArLHS || ArLHS->getLoop() != L) 9889 return None; 9890 9891 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9892 if (!MonotonicType) 9893 return None; 9894 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9895 // true as the loop iterates, and the backedge is control dependent on 9896 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9897 // 9898 // * if the predicate was false in the first iteration then the predicate 9899 // is never evaluated again, since the loop exits without taking the 9900 // backedge. 9901 // * if the predicate was true in the first iteration then it will 9902 // continue to be true for all future iterations since it is 9903 // monotonically increasing. 9904 // 9905 // For both the above possibilities, we can replace the loop varying 9906 // predicate with its value on the first iteration of the loop (which is 9907 // loop invariant). 9908 // 9909 // A similar reasoning applies for a monotonically decreasing predicate, by 9910 // replacing true with false and false with true in the above two bullets. 9911 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9912 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9913 9914 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9915 return None; 9916 9917 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9918 } 9919 9920 Optional<ScalarEvolution::LoopInvariantPredicate> 9921 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9922 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9923 const Instruction *Context, const SCEV *MaxIter) { 9924 // Try to prove the following set of facts: 9925 // - The predicate is monotonic in the iteration space. 9926 // - If the check does not fail on the 1st iteration: 9927 // - No overflow will happen during first MaxIter iterations; 9928 // - It will not fail on the MaxIter'th iteration. 9929 // If the check does fail on the 1st iteration, we leave the loop and no 9930 // other checks matter. 9931 9932 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9933 if (!isLoopInvariant(RHS, L)) { 9934 if (!isLoopInvariant(LHS, L)) 9935 return None; 9936 9937 std::swap(LHS, RHS); 9938 Pred = ICmpInst::getSwappedPredicate(Pred); 9939 } 9940 9941 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9942 if (!AR || AR->getLoop() != L) 9943 return None; 9944 9945 // The predicate must be relational (i.e. <, <=, >=, >). 9946 if (!ICmpInst::isRelational(Pred)) 9947 return None; 9948 9949 // TODO: Support steps other than +/- 1. 9950 const SCEV *Step = AR->getStepRecurrence(*this); 9951 auto *One = getOne(Step->getType()); 9952 auto *MinusOne = getNegativeSCEV(One); 9953 if (Step != One && Step != MinusOne) 9954 return None; 9955 9956 // Type mismatch here means that MaxIter is potentially larger than max 9957 // unsigned value in start type, which mean we cannot prove no wrap for the 9958 // indvar. 9959 if (AR->getType() != MaxIter->getType()) 9960 return None; 9961 9962 // Value of IV on suggested last iteration. 9963 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9964 // Does it still meet the requirement? 9965 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 9966 return None; 9967 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 9968 // not exceed max unsigned value of this type), this effectively proves 9969 // that there is no wrap during the iteration. To prove that there is no 9970 // signed/unsigned wrap, we need to check that 9971 // Start <= Last for step = 1 or Start >= Last for step = -1. 9972 ICmpInst::Predicate NoOverflowPred = 9973 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 9974 if (Step == MinusOne) 9975 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 9976 const SCEV *Start = AR->getStart(); 9977 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 9978 return None; 9979 9980 // Everything is fine. 9981 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 9982 } 9983 9984 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9985 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9986 if (HasSameValue(LHS, RHS)) 9987 return ICmpInst::isTrueWhenEqual(Pred); 9988 9989 // This code is split out from isKnownPredicate because it is called from 9990 // within isLoopEntryGuardedByCond. 9991 9992 auto CheckRanges = [&](const ConstantRange &RangeLHS, 9993 const ConstantRange &RangeRHS) { 9994 return RangeLHS.icmp(Pred, RangeRHS); 9995 }; 9996 9997 // The check at the top of the function catches the case where the values are 9998 // known to be equal. 9999 if (Pred == CmpInst::ICMP_EQ) 10000 return false; 10001 10002 if (Pred == CmpInst::ICMP_NE) 10003 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10004 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 10005 isKnownNonZero(getMinusSCEV(LHS, RHS)); 10006 10007 if (CmpInst::isSigned(Pred)) 10008 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10009 10010 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10011 } 10012 10013 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10014 const SCEV *LHS, 10015 const SCEV *RHS) { 10016 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 10017 // Return Y via OutY. 10018 auto MatchBinaryAddToConst = 10019 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 10020 SCEV::NoWrapFlags ExpectedFlags) { 10021 const SCEV *NonConstOp, *ConstOp; 10022 SCEV::NoWrapFlags FlagsPresent; 10023 10024 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 10025 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 10026 return false; 10027 10028 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 10029 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 10030 }; 10031 10032 APInt C; 10033 10034 switch (Pred) { 10035 default: 10036 break; 10037 10038 case ICmpInst::ICMP_SGE: 10039 std::swap(LHS, RHS); 10040 LLVM_FALLTHROUGH; 10041 case ICmpInst::ICMP_SLE: 10042 // X s<= (X + C)<nsw> if C >= 0 10043 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 10044 return true; 10045 10046 // (X + C)<nsw> s<= X if C <= 0 10047 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 10048 !C.isStrictlyPositive()) 10049 return true; 10050 break; 10051 10052 case ICmpInst::ICMP_SGT: 10053 std::swap(LHS, RHS); 10054 LLVM_FALLTHROUGH; 10055 case ICmpInst::ICMP_SLT: 10056 // X s< (X + C)<nsw> if C > 0 10057 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 10058 C.isStrictlyPositive()) 10059 return true; 10060 10061 // (X + C)<nsw> s< X if C < 0 10062 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 10063 return true; 10064 break; 10065 10066 case ICmpInst::ICMP_UGE: 10067 std::swap(LHS, RHS); 10068 LLVM_FALLTHROUGH; 10069 case ICmpInst::ICMP_ULE: 10070 // X u<= (X + C)<nuw> for any C 10071 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 10072 return true; 10073 break; 10074 10075 case ICmpInst::ICMP_UGT: 10076 std::swap(LHS, RHS); 10077 LLVM_FALLTHROUGH; 10078 case ICmpInst::ICMP_ULT: 10079 // X u< (X + C)<nuw> if C != 0 10080 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 10081 return true; 10082 break; 10083 } 10084 10085 return false; 10086 } 10087 10088 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10089 const SCEV *LHS, 10090 const SCEV *RHS) { 10091 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10092 return false; 10093 10094 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10095 // the stack can result in exponential time complexity. 10096 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10097 10098 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10099 // 10100 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10101 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10102 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10103 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10104 // use isKnownPredicate later if needed. 10105 return isKnownNonNegative(RHS) && 10106 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10107 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10108 } 10109 10110 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10111 ICmpInst::Predicate Pred, 10112 const SCEV *LHS, const SCEV *RHS) { 10113 // No need to even try if we know the module has no guards. 10114 if (!HasGuards) 10115 return false; 10116 10117 return any_of(*BB, [&](const Instruction &I) { 10118 using namespace llvm::PatternMatch; 10119 10120 Value *Condition; 10121 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10122 m_Value(Condition))) && 10123 isImpliedCond(Pred, LHS, RHS, Condition, false); 10124 }); 10125 } 10126 10127 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10128 /// protected by a conditional between LHS and RHS. This is used to 10129 /// to eliminate casts. 10130 bool 10131 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10132 ICmpInst::Predicate Pred, 10133 const SCEV *LHS, const SCEV *RHS) { 10134 // Interpret a null as meaning no loop, where there is obviously no guard 10135 // (interprocedural conditions notwithstanding). 10136 if (!L) return true; 10137 10138 if (VerifyIR) 10139 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10140 "This cannot be done on broken IR!"); 10141 10142 10143 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10144 return true; 10145 10146 BasicBlock *Latch = L->getLoopLatch(); 10147 if (!Latch) 10148 return false; 10149 10150 BranchInst *LoopContinuePredicate = 10151 dyn_cast<BranchInst>(Latch->getTerminator()); 10152 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10153 isImpliedCond(Pred, LHS, RHS, 10154 LoopContinuePredicate->getCondition(), 10155 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10156 return true; 10157 10158 // We don't want more than one activation of the following loops on the stack 10159 // -- that can lead to O(n!) time complexity. 10160 if (WalkingBEDominatingConds) 10161 return false; 10162 10163 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10164 10165 // See if we can exploit a trip count to prove the predicate. 10166 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10167 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10168 if (LatchBECount != getCouldNotCompute()) { 10169 // We know that Latch branches back to the loop header exactly 10170 // LatchBECount times. This means the backdege condition at Latch is 10171 // equivalent to "{0,+,1} u< LatchBECount". 10172 Type *Ty = LatchBECount->getType(); 10173 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10174 const SCEV *LoopCounter = 10175 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10176 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10177 LatchBECount)) 10178 return true; 10179 } 10180 10181 // Check conditions due to any @llvm.assume intrinsics. 10182 for (auto &AssumeVH : AC.assumptions()) { 10183 if (!AssumeVH) 10184 continue; 10185 auto *CI = cast<CallInst>(AssumeVH); 10186 if (!DT.dominates(CI, Latch->getTerminator())) 10187 continue; 10188 10189 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10190 return true; 10191 } 10192 10193 // If the loop is not reachable from the entry block, we risk running into an 10194 // infinite loop as we walk up into the dom tree. These loops do not matter 10195 // anyway, so we just return a conservative answer when we see them. 10196 if (!DT.isReachableFromEntry(L->getHeader())) 10197 return false; 10198 10199 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10200 return true; 10201 10202 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10203 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10204 assert(DTN && "should reach the loop header before reaching the root!"); 10205 10206 BasicBlock *BB = DTN->getBlock(); 10207 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10208 return true; 10209 10210 BasicBlock *PBB = BB->getSinglePredecessor(); 10211 if (!PBB) 10212 continue; 10213 10214 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10215 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10216 continue; 10217 10218 Value *Condition = ContinuePredicate->getCondition(); 10219 10220 // If we have an edge `E` within the loop body that dominates the only 10221 // latch, the condition guarding `E` also guards the backedge. This 10222 // reasoning works only for loops with a single latch. 10223 10224 BasicBlockEdge DominatingEdge(PBB, BB); 10225 if (DominatingEdge.isSingleEdge()) { 10226 // We're constructively (and conservatively) enumerating edges within the 10227 // loop body that dominate the latch. The dominator tree better agree 10228 // with us on this: 10229 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10230 10231 if (isImpliedCond(Pred, LHS, RHS, Condition, 10232 BB != ContinuePredicate->getSuccessor(0))) 10233 return true; 10234 } 10235 } 10236 10237 return false; 10238 } 10239 10240 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10241 ICmpInst::Predicate Pred, 10242 const SCEV *LHS, 10243 const SCEV *RHS) { 10244 if (VerifyIR) 10245 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10246 "This cannot be done on broken IR!"); 10247 10248 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10249 // the facts (a >= b && a != b) separately. A typical situation is when the 10250 // non-strict comparison is known from ranges and non-equality is known from 10251 // dominating predicates. If we are proving strict comparison, we always try 10252 // to prove non-equality and non-strict comparison separately. 10253 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10254 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10255 bool ProvedNonStrictComparison = false; 10256 bool ProvedNonEquality = false; 10257 10258 auto SplitAndProve = 10259 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10260 if (!ProvedNonStrictComparison) 10261 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10262 if (!ProvedNonEquality) 10263 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10264 if (ProvedNonStrictComparison && ProvedNonEquality) 10265 return true; 10266 return false; 10267 }; 10268 10269 if (ProvingStrictComparison) { 10270 auto ProofFn = [&](ICmpInst::Predicate P) { 10271 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10272 }; 10273 if (SplitAndProve(ProofFn)) 10274 return true; 10275 } 10276 10277 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10278 auto ProveViaGuard = [&](const BasicBlock *Block) { 10279 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10280 return true; 10281 if (ProvingStrictComparison) { 10282 auto ProofFn = [&](ICmpInst::Predicate P) { 10283 return isImpliedViaGuard(Block, P, LHS, RHS); 10284 }; 10285 if (SplitAndProve(ProofFn)) 10286 return true; 10287 } 10288 return false; 10289 }; 10290 10291 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10292 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10293 const Instruction *Context = &BB->front(); 10294 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10295 return true; 10296 if (ProvingStrictComparison) { 10297 auto ProofFn = [&](ICmpInst::Predicate P) { 10298 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10299 }; 10300 if (SplitAndProve(ProofFn)) 10301 return true; 10302 } 10303 return false; 10304 }; 10305 10306 // Starting at the block's predecessor, climb up the predecessor chain, as long 10307 // as there are predecessors that can be found that have unique successors 10308 // leading to the original block. 10309 const Loop *ContainingLoop = LI.getLoopFor(BB); 10310 const BasicBlock *PredBB; 10311 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10312 PredBB = ContainingLoop->getLoopPredecessor(); 10313 else 10314 PredBB = BB->getSinglePredecessor(); 10315 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10316 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10317 if (ProveViaGuard(Pair.first)) 10318 return true; 10319 10320 const BranchInst *LoopEntryPredicate = 10321 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10322 if (!LoopEntryPredicate || 10323 LoopEntryPredicate->isUnconditional()) 10324 continue; 10325 10326 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10327 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10328 return true; 10329 } 10330 10331 // Check conditions due to any @llvm.assume intrinsics. 10332 for (auto &AssumeVH : AC.assumptions()) { 10333 if (!AssumeVH) 10334 continue; 10335 auto *CI = cast<CallInst>(AssumeVH); 10336 if (!DT.dominates(CI, BB)) 10337 continue; 10338 10339 if (ProveViaCond(CI->getArgOperand(0), false)) 10340 return true; 10341 } 10342 10343 return false; 10344 } 10345 10346 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10347 ICmpInst::Predicate Pred, 10348 const SCEV *LHS, 10349 const SCEV *RHS) { 10350 // Interpret a null as meaning no loop, where there is obviously no guard 10351 // (interprocedural conditions notwithstanding). 10352 if (!L) 10353 return false; 10354 10355 // Both LHS and RHS must be available at loop entry. 10356 assert(isAvailableAtLoopEntry(LHS, L) && 10357 "LHS is not available at Loop Entry"); 10358 assert(isAvailableAtLoopEntry(RHS, L) && 10359 "RHS is not available at Loop Entry"); 10360 10361 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10362 return true; 10363 10364 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10365 } 10366 10367 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10368 const SCEV *RHS, 10369 const Value *FoundCondValue, bool Inverse, 10370 const Instruction *Context) { 10371 // False conditions implies anything. Do not bother analyzing it further. 10372 if (FoundCondValue == 10373 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10374 return true; 10375 10376 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10377 return false; 10378 10379 auto ClearOnExit = 10380 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10381 10382 // Recursively handle And and Or conditions. 10383 const Value *Op0, *Op1; 10384 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10385 if (!Inverse) 10386 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10387 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10388 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10389 if (Inverse) 10390 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10391 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10392 } 10393 10394 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10395 if (!ICI) return false; 10396 10397 // Now that we found a conditional branch that dominates the loop or controls 10398 // the loop latch. Check to see if it is the comparison we are looking for. 10399 ICmpInst::Predicate FoundPred; 10400 if (Inverse) 10401 FoundPred = ICI->getInversePredicate(); 10402 else 10403 FoundPred = ICI->getPredicate(); 10404 10405 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10406 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10407 10408 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10409 } 10410 10411 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10412 const SCEV *RHS, 10413 ICmpInst::Predicate FoundPred, 10414 const SCEV *FoundLHS, const SCEV *FoundRHS, 10415 const Instruction *Context) { 10416 // Balance the types. 10417 if (getTypeSizeInBits(LHS->getType()) < 10418 getTypeSizeInBits(FoundLHS->getType())) { 10419 // For unsigned and equality predicates, try to prove that both found 10420 // operands fit into narrow unsigned range. If so, try to prove facts in 10421 // narrow types. 10422 if (!CmpInst::isSigned(FoundPred)) { 10423 auto *NarrowType = LHS->getType(); 10424 auto *WideType = FoundLHS->getType(); 10425 auto BitWidth = getTypeSizeInBits(NarrowType); 10426 const SCEV *MaxValue = getZeroExtendExpr( 10427 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10428 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10429 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10430 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10431 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10432 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10433 TruncFoundRHS, Context)) 10434 return true; 10435 } 10436 } 10437 10438 if (CmpInst::isSigned(Pred)) { 10439 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10440 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10441 } else { 10442 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10443 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10444 } 10445 } else if (getTypeSizeInBits(LHS->getType()) > 10446 getTypeSizeInBits(FoundLHS->getType())) { 10447 if (CmpInst::isSigned(FoundPred)) { 10448 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10449 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10450 } else { 10451 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10452 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10453 } 10454 } 10455 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10456 FoundRHS, Context); 10457 } 10458 10459 bool ScalarEvolution::isImpliedCondBalancedTypes( 10460 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10461 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10462 const Instruction *Context) { 10463 assert(getTypeSizeInBits(LHS->getType()) == 10464 getTypeSizeInBits(FoundLHS->getType()) && 10465 "Types should be balanced!"); 10466 // Canonicalize the query to match the way instcombine will have 10467 // canonicalized the comparison. 10468 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10469 if (LHS == RHS) 10470 return CmpInst::isTrueWhenEqual(Pred); 10471 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10472 if (FoundLHS == FoundRHS) 10473 return CmpInst::isFalseWhenEqual(FoundPred); 10474 10475 // Check to see if we can make the LHS or RHS match. 10476 if (LHS == FoundRHS || RHS == FoundLHS) { 10477 if (isa<SCEVConstant>(RHS)) { 10478 std::swap(FoundLHS, FoundRHS); 10479 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10480 } else { 10481 std::swap(LHS, RHS); 10482 Pred = ICmpInst::getSwappedPredicate(Pred); 10483 } 10484 } 10485 10486 // Check whether the found predicate is the same as the desired predicate. 10487 if (FoundPred == Pred) 10488 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10489 10490 // Check whether swapping the found predicate makes it the same as the 10491 // desired predicate. 10492 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10493 // We can write the implication 10494 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10495 // using one of the following ways: 10496 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10497 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10498 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10499 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10500 // Forms 1. and 2. require swapping the operands of one condition. Don't 10501 // do this if it would break canonical constant/addrec ordering. 10502 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10503 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10504 Context); 10505 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10506 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10507 10508 // There's no clear preference between forms 3. and 4., try both. 10509 return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10510 FoundLHS, FoundRHS, Context) || 10511 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10512 getNotSCEV(FoundRHS), Context); 10513 } 10514 10515 // Unsigned comparison is the same as signed comparison when both the operands 10516 // are non-negative. 10517 if (CmpInst::isUnsigned(FoundPred) && 10518 CmpInst::getSignedPredicate(FoundPred) == Pred && 10519 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10520 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10521 10522 // Check if we can make progress by sharpening ranges. 10523 if (FoundPred == ICmpInst::ICMP_NE && 10524 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10525 10526 const SCEVConstant *C = nullptr; 10527 const SCEV *V = nullptr; 10528 10529 if (isa<SCEVConstant>(FoundLHS)) { 10530 C = cast<SCEVConstant>(FoundLHS); 10531 V = FoundRHS; 10532 } else { 10533 C = cast<SCEVConstant>(FoundRHS); 10534 V = FoundLHS; 10535 } 10536 10537 // The guarding predicate tells us that C != V. If the known range 10538 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10539 // range we consider has to correspond to same signedness as the 10540 // predicate we're interested in folding. 10541 10542 APInt Min = ICmpInst::isSigned(Pred) ? 10543 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10544 10545 if (Min == C->getAPInt()) { 10546 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10547 // This is true even if (Min + 1) wraps around -- in case of 10548 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10549 10550 APInt SharperMin = Min + 1; 10551 10552 switch (Pred) { 10553 case ICmpInst::ICMP_SGE: 10554 case ICmpInst::ICMP_UGE: 10555 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10556 // RHS, we're done. 10557 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10558 Context)) 10559 return true; 10560 LLVM_FALLTHROUGH; 10561 10562 case ICmpInst::ICMP_SGT: 10563 case ICmpInst::ICMP_UGT: 10564 // We know from the range information that (V `Pred` Min || 10565 // V == Min). We know from the guarding condition that !(V 10566 // == Min). This gives us 10567 // 10568 // V `Pred` Min || V == Min && !(V == Min) 10569 // => V `Pred` Min 10570 // 10571 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10572 10573 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10574 Context)) 10575 return true; 10576 break; 10577 10578 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10579 case ICmpInst::ICMP_SLE: 10580 case ICmpInst::ICMP_ULE: 10581 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10582 LHS, V, getConstant(SharperMin), Context)) 10583 return true; 10584 LLVM_FALLTHROUGH; 10585 10586 case ICmpInst::ICMP_SLT: 10587 case ICmpInst::ICMP_ULT: 10588 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10589 LHS, V, getConstant(Min), Context)) 10590 return true; 10591 break; 10592 10593 default: 10594 // No change 10595 break; 10596 } 10597 } 10598 } 10599 10600 // Check whether the actual condition is beyond sufficient. 10601 if (FoundPred == ICmpInst::ICMP_EQ) 10602 if (ICmpInst::isTrueWhenEqual(Pred)) 10603 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10604 return true; 10605 if (Pred == ICmpInst::ICMP_NE) 10606 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10607 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10608 Context)) 10609 return true; 10610 10611 // Otherwise assume the worst. 10612 return false; 10613 } 10614 10615 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10616 const SCEV *&L, const SCEV *&R, 10617 SCEV::NoWrapFlags &Flags) { 10618 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10619 if (!AE || AE->getNumOperands() != 2) 10620 return false; 10621 10622 L = AE->getOperand(0); 10623 R = AE->getOperand(1); 10624 Flags = AE->getNoWrapFlags(); 10625 return true; 10626 } 10627 10628 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10629 const SCEV *Less) { 10630 // We avoid subtracting expressions here because this function is usually 10631 // fairly deep in the call stack (i.e. is called many times). 10632 10633 // X - X = 0. 10634 if (More == Less) 10635 return APInt(getTypeSizeInBits(More->getType()), 0); 10636 10637 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10638 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10639 const auto *MAR = cast<SCEVAddRecExpr>(More); 10640 10641 if (LAR->getLoop() != MAR->getLoop()) 10642 return None; 10643 10644 // We look at affine expressions only; not for correctness but to keep 10645 // getStepRecurrence cheap. 10646 if (!LAR->isAffine() || !MAR->isAffine()) 10647 return None; 10648 10649 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10650 return None; 10651 10652 Less = LAR->getStart(); 10653 More = MAR->getStart(); 10654 10655 // fall through 10656 } 10657 10658 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10659 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10660 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10661 return M - L; 10662 } 10663 10664 SCEV::NoWrapFlags Flags; 10665 const SCEV *LLess = nullptr, *RLess = nullptr; 10666 const SCEV *LMore = nullptr, *RMore = nullptr; 10667 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10668 // Compare (X + C1) vs X. 10669 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10670 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10671 if (RLess == More) 10672 return -(C1->getAPInt()); 10673 10674 // Compare X vs (X + C2). 10675 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10676 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10677 if (RMore == Less) 10678 return C2->getAPInt(); 10679 10680 // Compare (X + C1) vs (X + C2). 10681 if (C1 && C2 && RLess == RMore) 10682 return C2->getAPInt() - C1->getAPInt(); 10683 10684 return None; 10685 } 10686 10687 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10688 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10689 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10690 // Try to recognize the following pattern: 10691 // 10692 // FoundRHS = ... 10693 // ... 10694 // loop: 10695 // FoundLHS = {Start,+,W} 10696 // context_bb: // Basic block from the same loop 10697 // known(Pred, FoundLHS, FoundRHS) 10698 // 10699 // If some predicate is known in the context of a loop, it is also known on 10700 // each iteration of this loop, including the first iteration. Therefore, in 10701 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10702 // prove the original pred using this fact. 10703 if (!Context) 10704 return false; 10705 const BasicBlock *ContextBB = Context->getParent(); 10706 // Make sure AR varies in the context block. 10707 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10708 const Loop *L = AR->getLoop(); 10709 // Make sure that context belongs to the loop and executes on 1st iteration 10710 // (if it ever executes at all). 10711 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10712 return false; 10713 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10714 return false; 10715 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10716 } 10717 10718 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10719 const Loop *L = AR->getLoop(); 10720 // Make sure that context belongs to the loop and executes on 1st iteration 10721 // (if it ever executes at all). 10722 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10723 return false; 10724 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10725 return false; 10726 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10727 } 10728 10729 return false; 10730 } 10731 10732 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10733 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10734 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10735 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10736 return false; 10737 10738 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10739 if (!AddRecLHS) 10740 return false; 10741 10742 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10743 if (!AddRecFoundLHS) 10744 return false; 10745 10746 // We'd like to let SCEV reason about control dependencies, so we constrain 10747 // both the inequalities to be about add recurrences on the same loop. This 10748 // way we can use isLoopEntryGuardedByCond later. 10749 10750 const Loop *L = AddRecFoundLHS->getLoop(); 10751 if (L != AddRecLHS->getLoop()) 10752 return false; 10753 10754 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10755 // 10756 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10757 // ... (2) 10758 // 10759 // Informal proof for (2), assuming (1) [*]: 10760 // 10761 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10762 // 10763 // Then 10764 // 10765 // FoundLHS s< FoundRHS s< INT_MIN - C 10766 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10767 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10768 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10769 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10770 // <=> FoundLHS + C s< FoundRHS + C 10771 // 10772 // [*]: (1) can be proved by ruling out overflow. 10773 // 10774 // [**]: This can be proved by analyzing all the four possibilities: 10775 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10776 // (A s>= 0, B s>= 0). 10777 // 10778 // Note: 10779 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10780 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10781 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10782 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10783 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10784 // C)". 10785 10786 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10787 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10788 if (!LDiff || !RDiff || *LDiff != *RDiff) 10789 return false; 10790 10791 if (LDiff->isMinValue()) 10792 return true; 10793 10794 APInt FoundRHSLimit; 10795 10796 if (Pred == CmpInst::ICMP_ULT) { 10797 FoundRHSLimit = -(*RDiff); 10798 } else { 10799 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10800 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10801 } 10802 10803 // Try to prove (1) or (2), as needed. 10804 return isAvailableAtLoopEntry(FoundRHS, L) && 10805 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10806 getConstant(FoundRHSLimit)); 10807 } 10808 10809 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10810 const SCEV *LHS, const SCEV *RHS, 10811 const SCEV *FoundLHS, 10812 const SCEV *FoundRHS, unsigned Depth) { 10813 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10814 10815 auto ClearOnExit = make_scope_exit([&]() { 10816 if (LPhi) { 10817 bool Erased = PendingMerges.erase(LPhi); 10818 assert(Erased && "Failed to erase LPhi!"); 10819 (void)Erased; 10820 } 10821 if (RPhi) { 10822 bool Erased = PendingMerges.erase(RPhi); 10823 assert(Erased && "Failed to erase RPhi!"); 10824 (void)Erased; 10825 } 10826 }); 10827 10828 // Find respective Phis and check that they are not being pending. 10829 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10830 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10831 if (!PendingMerges.insert(Phi).second) 10832 return false; 10833 LPhi = Phi; 10834 } 10835 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10836 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10837 // If we detect a loop of Phi nodes being processed by this method, for 10838 // example: 10839 // 10840 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10841 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10842 // 10843 // we don't want to deal with a case that complex, so return conservative 10844 // answer false. 10845 if (!PendingMerges.insert(Phi).second) 10846 return false; 10847 RPhi = Phi; 10848 } 10849 10850 // If none of LHS, RHS is a Phi, nothing to do here. 10851 if (!LPhi && !RPhi) 10852 return false; 10853 10854 // If there is a SCEVUnknown Phi we are interested in, make it left. 10855 if (!LPhi) { 10856 std::swap(LHS, RHS); 10857 std::swap(FoundLHS, FoundRHS); 10858 std::swap(LPhi, RPhi); 10859 Pred = ICmpInst::getSwappedPredicate(Pred); 10860 } 10861 10862 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10863 const BasicBlock *LBB = LPhi->getParent(); 10864 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10865 10866 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10867 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10868 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10869 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10870 }; 10871 10872 if (RPhi && RPhi->getParent() == LBB) { 10873 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10874 // If we compare two Phis from the same block, and for each entry block 10875 // the predicate is true for incoming values from this block, then the 10876 // predicate is also true for the Phis. 10877 for (const BasicBlock *IncBB : predecessors(LBB)) { 10878 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10879 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10880 if (!ProvedEasily(L, R)) 10881 return false; 10882 } 10883 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10884 // Case two: RHS is also a Phi from the same basic block, and it is an 10885 // AddRec. It means that there is a loop which has both AddRec and Unknown 10886 // PHIs, for it we can compare incoming values of AddRec from above the loop 10887 // and latch with their respective incoming values of LPhi. 10888 // TODO: Generalize to handle loops with many inputs in a header. 10889 if (LPhi->getNumIncomingValues() != 2) return false; 10890 10891 auto *RLoop = RAR->getLoop(); 10892 auto *Predecessor = RLoop->getLoopPredecessor(); 10893 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10894 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10895 if (!ProvedEasily(L1, RAR->getStart())) 10896 return false; 10897 auto *Latch = RLoop->getLoopLatch(); 10898 assert(Latch && "Loop with AddRec with no latch?"); 10899 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10900 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10901 return false; 10902 } else { 10903 // In all other cases go over inputs of LHS and compare each of them to RHS, 10904 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10905 // At this point RHS is either a non-Phi, or it is a Phi from some block 10906 // different from LBB. 10907 for (const BasicBlock *IncBB : predecessors(LBB)) { 10908 // Check that RHS is available in this block. 10909 if (!dominates(RHS, IncBB)) 10910 return false; 10911 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10912 // Make sure L does not refer to a value from a potentially previous 10913 // iteration of a loop. 10914 if (!properlyDominates(L, IncBB)) 10915 return false; 10916 if (!ProvedEasily(L, RHS)) 10917 return false; 10918 } 10919 } 10920 return true; 10921 } 10922 10923 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10924 const SCEV *LHS, const SCEV *RHS, 10925 const SCEV *FoundLHS, 10926 const SCEV *FoundRHS, 10927 const Instruction *Context) { 10928 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10929 return true; 10930 10931 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10932 return true; 10933 10934 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10935 Context)) 10936 return true; 10937 10938 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10939 FoundLHS, FoundRHS); 10940 } 10941 10942 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10943 template <typename MinMaxExprType> 10944 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10945 const SCEV *Candidate) { 10946 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10947 if (!MinMaxExpr) 10948 return false; 10949 10950 return is_contained(MinMaxExpr->operands(), Candidate); 10951 } 10952 10953 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10954 ICmpInst::Predicate Pred, 10955 const SCEV *LHS, const SCEV *RHS) { 10956 // If both sides are affine addrecs for the same loop, with equal 10957 // steps, and we know the recurrences don't wrap, then we only 10958 // need to check the predicate on the starting values. 10959 10960 if (!ICmpInst::isRelational(Pred)) 10961 return false; 10962 10963 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10964 if (!LAR) 10965 return false; 10966 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10967 if (!RAR) 10968 return false; 10969 if (LAR->getLoop() != RAR->getLoop()) 10970 return false; 10971 if (!LAR->isAffine() || !RAR->isAffine()) 10972 return false; 10973 10974 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10975 return false; 10976 10977 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10978 SCEV::FlagNSW : SCEV::FlagNUW; 10979 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10980 return false; 10981 10982 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10983 } 10984 10985 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10986 /// expression? 10987 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10988 ICmpInst::Predicate Pred, 10989 const SCEV *LHS, const SCEV *RHS) { 10990 switch (Pred) { 10991 default: 10992 return false; 10993 10994 case ICmpInst::ICMP_SGE: 10995 std::swap(LHS, RHS); 10996 LLVM_FALLTHROUGH; 10997 case ICmpInst::ICMP_SLE: 10998 return 10999 // min(A, ...) <= A 11000 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11001 // A <= max(A, ...) 11002 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11003 11004 case ICmpInst::ICMP_UGE: 11005 std::swap(LHS, RHS); 11006 LLVM_FALLTHROUGH; 11007 case ICmpInst::ICMP_ULE: 11008 return 11009 // min(A, ...) <= A 11010 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11011 // A <= max(A, ...) 11012 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11013 } 11014 11015 llvm_unreachable("covered switch fell through?!"); 11016 } 11017 11018 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11019 const SCEV *LHS, const SCEV *RHS, 11020 const SCEV *FoundLHS, 11021 const SCEV *FoundRHS, 11022 unsigned Depth) { 11023 assert(getTypeSizeInBits(LHS->getType()) == 11024 getTypeSizeInBits(RHS->getType()) && 11025 "LHS and RHS have different sizes?"); 11026 assert(getTypeSizeInBits(FoundLHS->getType()) == 11027 getTypeSizeInBits(FoundRHS->getType()) && 11028 "FoundLHS and FoundRHS have different sizes?"); 11029 // We want to avoid hurting the compile time with analysis of too big trees. 11030 if (Depth > MaxSCEVOperationsImplicationDepth) 11031 return false; 11032 11033 // We only want to work with GT comparison so far. 11034 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11035 Pred = CmpInst::getSwappedPredicate(Pred); 11036 std::swap(LHS, RHS); 11037 std::swap(FoundLHS, FoundRHS); 11038 } 11039 11040 // For unsigned, try to reduce it to corresponding signed comparison. 11041 if (Pred == ICmpInst::ICMP_UGT) 11042 // We can replace unsigned predicate with its signed counterpart if all 11043 // involved values are non-negative. 11044 // TODO: We could have better support for unsigned. 11045 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11046 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11047 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11048 // use this fact to prove that LHS and RHS are non-negative. 11049 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11050 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11051 FoundRHS) && 11052 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11053 FoundRHS)) 11054 Pred = ICmpInst::ICMP_SGT; 11055 } 11056 11057 if (Pred != ICmpInst::ICMP_SGT) 11058 return false; 11059 11060 auto GetOpFromSExt = [&](const SCEV *S) { 11061 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11062 return Ext->getOperand(); 11063 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11064 // the constant in some cases. 11065 return S; 11066 }; 11067 11068 // Acquire values from extensions. 11069 auto *OrigLHS = LHS; 11070 auto *OrigFoundLHS = FoundLHS; 11071 LHS = GetOpFromSExt(LHS); 11072 FoundLHS = GetOpFromSExt(FoundLHS); 11073 11074 // Is the SGT predicate can be proved trivially or using the found context. 11075 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11076 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11077 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11078 FoundRHS, Depth + 1); 11079 }; 11080 11081 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11082 // We want to avoid creation of any new non-constant SCEV. Since we are 11083 // going to compare the operands to RHS, we should be certain that we don't 11084 // need any size extensions for this. So let's decline all cases when the 11085 // sizes of types of LHS and RHS do not match. 11086 // TODO: Maybe try to get RHS from sext to catch more cases? 11087 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11088 return false; 11089 11090 // Should not overflow. 11091 if (!LHSAddExpr->hasNoSignedWrap()) 11092 return false; 11093 11094 auto *LL = LHSAddExpr->getOperand(0); 11095 auto *LR = LHSAddExpr->getOperand(1); 11096 auto *MinusOne = getMinusOne(RHS->getType()); 11097 11098 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11099 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11100 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11101 }; 11102 // Try to prove the following rule: 11103 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11104 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11105 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11106 return true; 11107 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11108 Value *LL, *LR; 11109 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11110 11111 using namespace llvm::PatternMatch; 11112 11113 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11114 // Rules for division. 11115 // We are going to perform some comparisons with Denominator and its 11116 // derivative expressions. In general case, creating a SCEV for it may 11117 // lead to a complex analysis of the entire graph, and in particular it 11118 // can request trip count recalculation for the same loop. This would 11119 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11120 // this, we only want to create SCEVs that are constants in this section. 11121 // So we bail if Denominator is not a constant. 11122 if (!isa<ConstantInt>(LR)) 11123 return false; 11124 11125 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11126 11127 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11128 // then a SCEV for the numerator already exists and matches with FoundLHS. 11129 auto *Numerator = getExistingSCEV(LL); 11130 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11131 return false; 11132 11133 // Make sure that the numerator matches with FoundLHS and the denominator 11134 // is positive. 11135 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11136 return false; 11137 11138 auto *DTy = Denominator->getType(); 11139 auto *FRHSTy = FoundRHS->getType(); 11140 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11141 // One of types is a pointer and another one is not. We cannot extend 11142 // them properly to a wider type, so let us just reject this case. 11143 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11144 // to avoid this check. 11145 return false; 11146 11147 // Given that: 11148 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11149 auto *WTy = getWiderType(DTy, FRHSTy); 11150 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11151 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11152 11153 // Try to prove the following rule: 11154 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11155 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11156 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11157 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11158 if (isKnownNonPositive(RHS) && 11159 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11160 return true; 11161 11162 // Try to prove the following rule: 11163 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11164 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11165 // If we divide it by Denominator > 2, then: 11166 // 1. If FoundLHS is negative, then the result is 0. 11167 // 2. If FoundLHS is non-negative, then the result is non-negative. 11168 // Anyways, the result is non-negative. 11169 auto *MinusOne = getMinusOne(WTy); 11170 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11171 if (isKnownNegative(RHS) && 11172 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11173 return true; 11174 } 11175 } 11176 11177 // If our expression contained SCEVUnknown Phis, and we split it down and now 11178 // need to prove something for them, try to prove the predicate for every 11179 // possible incoming values of those Phis. 11180 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11181 return true; 11182 11183 return false; 11184 } 11185 11186 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11187 const SCEV *LHS, const SCEV *RHS) { 11188 // zext x u<= sext x, sext x s<= zext x 11189 switch (Pred) { 11190 case ICmpInst::ICMP_SGE: 11191 std::swap(LHS, RHS); 11192 LLVM_FALLTHROUGH; 11193 case ICmpInst::ICMP_SLE: { 11194 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11195 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11196 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11197 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11198 return true; 11199 break; 11200 } 11201 case ICmpInst::ICMP_UGE: 11202 std::swap(LHS, RHS); 11203 LLVM_FALLTHROUGH; 11204 case ICmpInst::ICMP_ULE: { 11205 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11206 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11207 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11208 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11209 return true; 11210 break; 11211 } 11212 default: 11213 break; 11214 }; 11215 return false; 11216 } 11217 11218 bool 11219 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11220 const SCEV *LHS, const SCEV *RHS) { 11221 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11222 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11223 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11224 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11225 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11226 } 11227 11228 bool 11229 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11230 const SCEV *LHS, const SCEV *RHS, 11231 const SCEV *FoundLHS, 11232 const SCEV *FoundRHS) { 11233 switch (Pred) { 11234 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11235 case ICmpInst::ICMP_EQ: 11236 case ICmpInst::ICMP_NE: 11237 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11238 return true; 11239 break; 11240 case ICmpInst::ICMP_SLT: 11241 case ICmpInst::ICMP_SLE: 11242 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11243 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11244 return true; 11245 break; 11246 case ICmpInst::ICMP_SGT: 11247 case ICmpInst::ICMP_SGE: 11248 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11249 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11250 return true; 11251 break; 11252 case ICmpInst::ICMP_ULT: 11253 case ICmpInst::ICMP_ULE: 11254 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11255 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11256 return true; 11257 break; 11258 case ICmpInst::ICMP_UGT: 11259 case ICmpInst::ICMP_UGE: 11260 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11261 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11262 return true; 11263 break; 11264 } 11265 11266 // Maybe it can be proved via operations? 11267 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11268 return true; 11269 11270 return false; 11271 } 11272 11273 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11274 const SCEV *LHS, 11275 const SCEV *RHS, 11276 const SCEV *FoundLHS, 11277 const SCEV *FoundRHS) { 11278 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11279 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11280 // reduce the compile time impact of this optimization. 11281 return false; 11282 11283 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11284 if (!Addend) 11285 return false; 11286 11287 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11288 11289 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11290 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11291 ConstantRange FoundLHSRange = 11292 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 11293 11294 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11295 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11296 11297 // We can also compute the range of values for `LHS` that satisfy the 11298 // consequent, "`LHS` `Pred` `RHS`": 11299 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11300 // The antecedent implies the consequent if every value of `LHS` that 11301 // satisfies the antecedent also satisfies the consequent. 11302 return LHSRange.icmp(Pred, ConstRHS); 11303 } 11304 11305 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11306 bool IsSigned) { 11307 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11308 11309 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11310 const SCEV *One = getOne(Stride->getType()); 11311 11312 if (IsSigned) { 11313 APInt MaxRHS = getSignedRangeMax(RHS); 11314 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11315 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11316 11317 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11318 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11319 } 11320 11321 APInt MaxRHS = getUnsignedRangeMax(RHS); 11322 APInt MaxValue = APInt::getMaxValue(BitWidth); 11323 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11324 11325 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11326 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11327 } 11328 11329 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11330 bool IsSigned) { 11331 11332 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11333 const SCEV *One = getOne(Stride->getType()); 11334 11335 if (IsSigned) { 11336 APInt MinRHS = getSignedRangeMin(RHS); 11337 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11338 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11339 11340 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11341 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11342 } 11343 11344 APInt MinRHS = getUnsignedRangeMin(RHS); 11345 APInt MinValue = APInt::getMinValue(BitWidth); 11346 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11347 11348 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11349 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11350 } 11351 11352 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, 11353 const SCEV *Step) { 11354 const SCEV *One = getOne(Step->getType()); 11355 Delta = getAddExpr(Delta, getMinusSCEV(Step, One)); 11356 return getUDivExpr(Delta, Step); 11357 } 11358 11359 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11360 const SCEV *Stride, 11361 const SCEV *End, 11362 unsigned BitWidth, 11363 bool IsSigned) { 11364 11365 assert(!isKnownNonPositive(Stride) && 11366 "Stride is expected strictly positive!"); 11367 // Calculate the maximum backedge count based on the range of values 11368 // permitted by Start, End, and Stride. 11369 const SCEV *MaxBECount; 11370 APInt MinStart = 11371 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11372 11373 APInt StrideForMaxBECount = 11374 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11375 11376 // We already know that the stride is positive, so we paper over conservatism 11377 // in our range computation by forcing StrideForMaxBECount to be at least one. 11378 // In theory this is unnecessary, but we expect MaxBECount to be a 11379 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11380 // is nothing to constant fold it to). 11381 APInt One(BitWidth, 1, IsSigned); 11382 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11383 11384 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11385 : APInt::getMaxValue(BitWidth); 11386 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11387 11388 // Although End can be a MAX expression we estimate MaxEnd considering only 11389 // the case End = RHS of the loop termination condition. This is safe because 11390 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11391 // taken count. 11392 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11393 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11394 11395 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11396 getConstant(StrideForMaxBECount) /* Step */); 11397 11398 return MaxBECount; 11399 } 11400 11401 ScalarEvolution::ExitLimit 11402 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11403 const Loop *L, bool IsSigned, 11404 bool ControlsExit, bool AllowPredicates) { 11405 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11406 11407 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11408 bool PredicatedIV = false; 11409 11410 if (!IV && AllowPredicates) { 11411 // Try to make this an AddRec using runtime tests, in the first X 11412 // iterations of this loop, where X is the SCEV expression found by the 11413 // algorithm below. 11414 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11415 PredicatedIV = true; 11416 } 11417 11418 // Avoid weird loops 11419 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11420 return getCouldNotCompute(); 11421 11422 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11423 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11424 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11425 11426 const SCEV *Stride = IV->getStepRecurrence(*this); 11427 11428 bool PositiveStride = isKnownPositive(Stride); 11429 11430 // Avoid negative or zero stride values. 11431 if (!PositiveStride) { 11432 // We can compute the correct backedge taken count for loops with unknown 11433 // strides if we can prove that the loop is not an infinite loop with side 11434 // effects. Here's the loop structure we are trying to handle - 11435 // 11436 // i = start 11437 // do { 11438 // A[i] = i; 11439 // i += s; 11440 // } while (i < end); 11441 // 11442 // The backedge taken count for such loops is evaluated as - 11443 // (max(end, start + stride) - start - 1) /u stride 11444 // 11445 // The additional preconditions that we need to check to prove correctness 11446 // of the above formula is as follows - 11447 // 11448 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11449 // NoWrap flag). 11450 // b) loop is single exit with no side effects. 11451 // 11452 // 11453 // Precondition a) implies that if the stride is negative, this is a single 11454 // trip loop. The backedge taken count formula reduces to zero in this case. 11455 // 11456 // Precondition b) implies that the unknown stride cannot be zero otherwise 11457 // we have UB. 11458 // 11459 // The positive stride case is the same as isKnownPositive(Stride) returning 11460 // true (original behavior of the function). 11461 // 11462 // We want to make sure that the stride is truly unknown as there are edge 11463 // cases where ScalarEvolution propagates no wrap flags to the 11464 // post-increment/decrement IV even though the increment/decrement operation 11465 // itself is wrapping. The computed backedge taken count may be wrong in 11466 // such cases. This is prevented by checking that the stride is not known to 11467 // be either positive or non-positive. For example, no wrap flags are 11468 // propagated to the post-increment IV of this loop with a trip count of 2 - 11469 // 11470 // unsigned char i; 11471 // for(i=127; i<128; i+=129) 11472 // A[i] = i; 11473 // 11474 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11475 !loopIsFiniteByAssumption(L)) 11476 return getCouldNotCompute(); 11477 } else if (!Stride->isOne() && !NoWrap) { 11478 auto isUBOnWrap = [&]() { 11479 // Can we prove this loop *must* be UB if overflow of IV occurs? 11480 // Reasoning goes as follows: 11481 // * Suppose the IV did self wrap. 11482 // * If Stride evenly divides the iteration space, then once wrap 11483 // occurs, the loop must revisit the same values. 11484 // * We know that RHS is invariant, and that none of those values 11485 // caused this exit to be taken previously. Thus, this exit is 11486 // dynamically dead. 11487 // * If this is the sole exit, then a dead exit implies the loop 11488 // must be infinite if there are no abnormal exits. 11489 // * If the loop were infinite, then it must either not be mustprogress 11490 // or have side effects. Otherwise, it must be UB. 11491 // * It can't (by assumption), be UB so we have contradicted our 11492 // premise and can conclude the IV did not in fact self-wrap. 11493 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11494 // follows trivially from the fact that every (un)signed-wrapped, but 11495 // not self-wrapped value must be LT than the last value before 11496 // (un)signed wrap. Since we know that last value didn't exit, nor 11497 // will any smaller one. 11498 11499 if (!isLoopInvariant(RHS, L)) 11500 return false; 11501 11502 auto *StrideC = dyn_cast<SCEVConstant>(Stride); 11503 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11504 return false; 11505 11506 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11507 return false; 11508 11509 return loopIsFiniteByAssumption(L); 11510 }; 11511 11512 // Avoid proven overflow cases: this will ensure that the backedge taken 11513 // count will not generate any unsigned overflow. Relaxed no-overflow 11514 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11515 // undefined behaviors like the case of C language. 11516 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11517 return getCouldNotCompute(); 11518 } 11519 11520 const SCEV *Start = IV->getStart(); 11521 const SCEV *End = RHS; 11522 // When the RHS is not invariant, we do not know the end bound of the loop and 11523 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11524 // calculate the MaxBECount, given the start, stride and max value for the end 11525 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11526 // checked above). 11527 if (!isLoopInvariant(RHS, L)) { 11528 const SCEV *MaxBECount = computeMaxBECountForLT( 11529 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11530 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11531 false /*MaxOrZero*/, Predicates); 11532 } 11533 // If the backedge is taken at least once, then it will be taken 11534 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11535 // is the LHS value of the less-than comparison the first time it is evaluated 11536 // and End is the RHS. 11537 const SCEV *BECountIfBackedgeTaken = 11538 computeBECount(getMinusSCEV(End, Start), Stride); 11539 // If the loop entry is guarded by the result of the backedge test of the 11540 // first loop iteration, then we know the backedge will be taken at least 11541 // once and so the backedge taken count is as above. If not then we use the 11542 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11543 // as if the backedge is taken at least once max(End,Start) is End and so the 11544 // result is as above, and if not max(End,Start) is Start so we get a backedge 11545 // count of zero. 11546 const SCEV *BECount; 11547 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11548 BECount = BECountIfBackedgeTaken; 11549 else { 11550 // If we know that RHS >= Start in the context of loop, then we know that 11551 // max(RHS, Start) = RHS at this point. 11552 if (isLoopEntryGuardedByCond( 11553 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11554 End = RHS; 11555 else 11556 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11557 BECount = computeBECount(getMinusSCEV(End, Start), Stride); 11558 } 11559 11560 const SCEV *MaxBECount; 11561 bool MaxOrZero = false; 11562 if (isa<SCEVConstant>(BECount)) 11563 MaxBECount = BECount; 11564 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11565 // If we know exactly how many times the backedge will be taken if it's 11566 // taken at least once, then the backedge count will either be that or 11567 // zero. 11568 MaxBECount = BECountIfBackedgeTaken; 11569 MaxOrZero = true; 11570 } else { 11571 MaxBECount = computeMaxBECountForLT( 11572 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11573 } 11574 11575 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11576 !isa<SCEVCouldNotCompute>(BECount)) 11577 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11578 11579 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11580 } 11581 11582 ScalarEvolution::ExitLimit 11583 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11584 const Loop *L, bool IsSigned, 11585 bool ControlsExit, bool AllowPredicates) { 11586 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11587 // We handle only IV > Invariant 11588 if (!isLoopInvariant(RHS, L)) 11589 return getCouldNotCompute(); 11590 11591 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11592 if (!IV && AllowPredicates) 11593 // Try to make this an AddRec using runtime tests, in the first X 11594 // iterations of this loop, where X is the SCEV expression found by the 11595 // algorithm below. 11596 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11597 11598 // Avoid weird loops 11599 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11600 return getCouldNotCompute(); 11601 11602 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11603 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11604 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11605 11606 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11607 11608 // Avoid negative or zero stride values 11609 if (!isKnownPositive(Stride)) 11610 return getCouldNotCompute(); 11611 11612 // Avoid proven overflow cases: this will ensure that the backedge taken count 11613 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11614 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11615 // behaviors like the case of C language. 11616 if (!Stride->isOne() && !NoWrap) 11617 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 11618 return getCouldNotCompute(); 11619 11620 const SCEV *Start = IV->getStart(); 11621 const SCEV *End = RHS; 11622 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11623 // If we know that Start >= RHS in the context of loop, then we know that 11624 // min(RHS, Start) = RHS at this point. 11625 if (isLoopEntryGuardedByCond( 11626 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11627 End = RHS; 11628 else 11629 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11630 } 11631 11632 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride); 11633 11634 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11635 : getUnsignedRangeMax(Start); 11636 11637 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11638 : getUnsignedRangeMin(Stride); 11639 11640 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11641 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11642 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11643 11644 // Although End can be a MIN expression we estimate MinEnd considering only 11645 // the case End = RHS. This is safe because in the other case (Start - End) 11646 // is zero, leading to a zero maximum backedge taken count. 11647 APInt MinEnd = 11648 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11649 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11650 11651 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11652 ? BECount 11653 : computeBECount(getConstant(MaxStart - MinEnd), 11654 getConstant(MinStride)); 11655 11656 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11657 MaxBECount = BECount; 11658 11659 return ExitLimit(BECount, MaxBECount, false, Predicates); 11660 } 11661 11662 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11663 ScalarEvolution &SE) const { 11664 if (Range.isFullSet()) // Infinite loop. 11665 return SE.getCouldNotCompute(); 11666 11667 // If the start is a non-zero constant, shift the range to simplify things. 11668 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11669 if (!SC->getValue()->isZero()) { 11670 SmallVector<const SCEV *, 4> Operands(operands()); 11671 Operands[0] = SE.getZero(SC->getType()); 11672 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11673 getNoWrapFlags(FlagNW)); 11674 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11675 return ShiftedAddRec->getNumIterationsInRange( 11676 Range.subtract(SC->getAPInt()), SE); 11677 // This is strange and shouldn't happen. 11678 return SE.getCouldNotCompute(); 11679 } 11680 11681 // The only time we can solve this is when we have all constant indices. 11682 // Otherwise, we cannot determine the overflow conditions. 11683 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11684 return SE.getCouldNotCompute(); 11685 11686 // Okay at this point we know that all elements of the chrec are constants and 11687 // that the start element is zero. 11688 11689 // First check to see if the range contains zero. If not, the first 11690 // iteration exits. 11691 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11692 if (!Range.contains(APInt(BitWidth, 0))) 11693 return SE.getZero(getType()); 11694 11695 if (isAffine()) { 11696 // If this is an affine expression then we have this situation: 11697 // Solve {0,+,A} in Range === Ax in Range 11698 11699 // We know that zero is in the range. If A is positive then we know that 11700 // the upper value of the range must be the first possible exit value. 11701 // If A is negative then the lower of the range is the last possible loop 11702 // value. Also note that we already checked for a full range. 11703 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11704 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11705 11706 // The exit value should be (End+A)/A. 11707 APInt ExitVal = (End + A).udiv(A); 11708 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11709 11710 // Evaluate at the exit value. If we really did fall out of the valid 11711 // range, then we computed our trip count, otherwise wrap around or other 11712 // things must have happened. 11713 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11714 if (Range.contains(Val->getValue())) 11715 return SE.getCouldNotCompute(); // Something strange happened 11716 11717 // Ensure that the previous value is in the range. This is a sanity check. 11718 assert(Range.contains( 11719 EvaluateConstantChrecAtConstant(this, 11720 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11721 "Linear scev computation is off in a bad way!"); 11722 return SE.getConstant(ExitValue); 11723 } 11724 11725 if (isQuadratic()) { 11726 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11727 return SE.getConstant(S.getValue()); 11728 } 11729 11730 return SE.getCouldNotCompute(); 11731 } 11732 11733 const SCEVAddRecExpr * 11734 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11735 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11736 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11737 // but in this case we cannot guarantee that the value returned will be an 11738 // AddRec because SCEV does not have a fixed point where it stops 11739 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11740 // may happen if we reach arithmetic depth limit while simplifying. So we 11741 // construct the returned value explicitly. 11742 SmallVector<const SCEV *, 3> Ops; 11743 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11744 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11745 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11746 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11747 // We know that the last operand is not a constant zero (otherwise it would 11748 // have been popped out earlier). This guarantees us that if the result has 11749 // the same last operand, then it will also not be popped out, meaning that 11750 // the returned value will be an AddRec. 11751 const SCEV *Last = getOperand(getNumOperands() - 1); 11752 assert(!Last->isZero() && "Recurrency with zero step?"); 11753 Ops.push_back(Last); 11754 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11755 SCEV::FlagAnyWrap)); 11756 } 11757 11758 // Return true when S contains at least an undef value. 11759 static inline bool containsUndefs(const SCEV *S) { 11760 return SCEVExprContains(S, [](const SCEV *S) { 11761 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11762 return isa<UndefValue>(SU->getValue()); 11763 return false; 11764 }); 11765 } 11766 11767 namespace { 11768 11769 // Collect all steps of SCEV expressions. 11770 struct SCEVCollectStrides { 11771 ScalarEvolution &SE; 11772 SmallVectorImpl<const SCEV *> &Strides; 11773 11774 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11775 : SE(SE), Strides(S) {} 11776 11777 bool follow(const SCEV *S) { 11778 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11779 Strides.push_back(AR->getStepRecurrence(SE)); 11780 return true; 11781 } 11782 11783 bool isDone() const { return false; } 11784 }; 11785 11786 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11787 struct SCEVCollectTerms { 11788 SmallVectorImpl<const SCEV *> &Terms; 11789 11790 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11791 11792 bool follow(const SCEV *S) { 11793 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11794 isa<SCEVSignExtendExpr>(S)) { 11795 if (!containsUndefs(S)) 11796 Terms.push_back(S); 11797 11798 // Stop recursion: once we collected a term, do not walk its operands. 11799 return false; 11800 } 11801 11802 // Keep looking. 11803 return true; 11804 } 11805 11806 bool isDone() const { return false; } 11807 }; 11808 11809 // Check if a SCEV contains an AddRecExpr. 11810 struct SCEVHasAddRec { 11811 bool &ContainsAddRec; 11812 11813 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11814 ContainsAddRec = false; 11815 } 11816 11817 bool follow(const SCEV *S) { 11818 if (isa<SCEVAddRecExpr>(S)) { 11819 ContainsAddRec = true; 11820 11821 // Stop recursion: once we collected a term, do not walk its operands. 11822 return false; 11823 } 11824 11825 // Keep looking. 11826 return true; 11827 } 11828 11829 bool isDone() const { return false; } 11830 }; 11831 11832 // Find factors that are multiplied with an expression that (possibly as a 11833 // subexpression) contains an AddRecExpr. In the expression: 11834 // 11835 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11836 // 11837 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11838 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11839 // parameters as they form a product with an induction variable. 11840 // 11841 // This collector expects all array size parameters to be in the same MulExpr. 11842 // It might be necessary to later add support for collecting parameters that are 11843 // spread over different nested MulExpr. 11844 struct SCEVCollectAddRecMultiplies { 11845 SmallVectorImpl<const SCEV *> &Terms; 11846 ScalarEvolution &SE; 11847 11848 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11849 : Terms(T), SE(SE) {} 11850 11851 bool follow(const SCEV *S) { 11852 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11853 bool HasAddRec = false; 11854 SmallVector<const SCEV *, 0> Operands; 11855 for (auto Op : Mul->operands()) { 11856 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11857 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11858 Operands.push_back(Op); 11859 } else if (Unknown) { 11860 HasAddRec = true; 11861 } else { 11862 bool ContainsAddRec = false; 11863 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11864 visitAll(Op, ContiansAddRec); 11865 HasAddRec |= ContainsAddRec; 11866 } 11867 } 11868 if (Operands.size() == 0) 11869 return true; 11870 11871 if (!HasAddRec) 11872 return false; 11873 11874 Terms.push_back(SE.getMulExpr(Operands)); 11875 // Stop recursion: once we collected a term, do not walk its operands. 11876 return false; 11877 } 11878 11879 // Keep looking. 11880 return true; 11881 } 11882 11883 bool isDone() const { return false; } 11884 }; 11885 11886 } // end anonymous namespace 11887 11888 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11889 /// two places: 11890 /// 1) The strides of AddRec expressions. 11891 /// 2) Unknowns that are multiplied with AddRec expressions. 11892 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11893 SmallVectorImpl<const SCEV *> &Terms) { 11894 SmallVector<const SCEV *, 4> Strides; 11895 SCEVCollectStrides StrideCollector(*this, Strides); 11896 visitAll(Expr, StrideCollector); 11897 11898 LLVM_DEBUG({ 11899 dbgs() << "Strides:\n"; 11900 for (const SCEV *S : Strides) 11901 dbgs() << *S << "\n"; 11902 }); 11903 11904 for (const SCEV *S : Strides) { 11905 SCEVCollectTerms TermCollector(Terms); 11906 visitAll(S, TermCollector); 11907 } 11908 11909 LLVM_DEBUG({ 11910 dbgs() << "Terms:\n"; 11911 for (const SCEV *T : Terms) 11912 dbgs() << *T << "\n"; 11913 }); 11914 11915 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11916 visitAll(Expr, MulCollector); 11917 } 11918 11919 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11920 SmallVectorImpl<const SCEV *> &Terms, 11921 SmallVectorImpl<const SCEV *> &Sizes) { 11922 int Last = Terms.size() - 1; 11923 const SCEV *Step = Terms[Last]; 11924 11925 // End of recursion. 11926 if (Last == 0) { 11927 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11928 SmallVector<const SCEV *, 2> Qs; 11929 for (const SCEV *Op : M->operands()) 11930 if (!isa<SCEVConstant>(Op)) 11931 Qs.push_back(Op); 11932 11933 Step = SE.getMulExpr(Qs); 11934 } 11935 11936 Sizes.push_back(Step); 11937 return true; 11938 } 11939 11940 for (const SCEV *&Term : Terms) { 11941 // Normalize the terms before the next call to findArrayDimensionsRec. 11942 const SCEV *Q, *R; 11943 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11944 11945 // Bail out when GCD does not evenly divide one of the terms. 11946 if (!R->isZero()) 11947 return false; 11948 11949 Term = Q; 11950 } 11951 11952 // Remove all SCEVConstants. 11953 erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }); 11954 11955 if (Terms.size() > 0) 11956 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11957 return false; 11958 11959 Sizes.push_back(Step); 11960 return true; 11961 } 11962 11963 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11964 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11965 for (const SCEV *T : Terms) 11966 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11967 return true; 11968 11969 return false; 11970 } 11971 11972 // Return the number of product terms in S. 11973 static inline int numberOfTerms(const SCEV *S) { 11974 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11975 return Expr->getNumOperands(); 11976 return 1; 11977 } 11978 11979 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11980 if (isa<SCEVConstant>(T)) 11981 return nullptr; 11982 11983 if (isa<SCEVUnknown>(T)) 11984 return T; 11985 11986 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11987 SmallVector<const SCEV *, 2> Factors; 11988 for (const SCEV *Op : M->operands()) 11989 if (!isa<SCEVConstant>(Op)) 11990 Factors.push_back(Op); 11991 11992 return SE.getMulExpr(Factors); 11993 } 11994 11995 return T; 11996 } 11997 11998 /// Return the size of an element read or written by Inst. 11999 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12000 Type *Ty; 12001 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12002 Ty = Store->getValueOperand()->getType(); 12003 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12004 Ty = Load->getType(); 12005 else 12006 return nullptr; 12007 12008 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12009 return getSizeOfExpr(ETy, Ty); 12010 } 12011 12012 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 12013 SmallVectorImpl<const SCEV *> &Sizes, 12014 const SCEV *ElementSize) { 12015 if (Terms.size() < 1 || !ElementSize) 12016 return; 12017 12018 // Early return when Terms do not contain parameters: we do not delinearize 12019 // non parametric SCEVs. 12020 if (!containsParameters(Terms)) 12021 return; 12022 12023 LLVM_DEBUG({ 12024 dbgs() << "Terms:\n"; 12025 for (const SCEV *T : Terms) 12026 dbgs() << *T << "\n"; 12027 }); 12028 12029 // Remove duplicates. 12030 array_pod_sort(Terms.begin(), Terms.end()); 12031 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 12032 12033 // Put larger terms first. 12034 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 12035 return numberOfTerms(LHS) > numberOfTerms(RHS); 12036 }); 12037 12038 // Try to divide all terms by the element size. If term is not divisible by 12039 // element size, proceed with the original term. 12040 for (const SCEV *&Term : Terms) { 12041 const SCEV *Q, *R; 12042 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 12043 if (!Q->isZero()) 12044 Term = Q; 12045 } 12046 12047 SmallVector<const SCEV *, 4> NewTerms; 12048 12049 // Remove constant factors. 12050 for (const SCEV *T : Terms) 12051 if (const SCEV *NewT = removeConstantFactors(*this, T)) 12052 NewTerms.push_back(NewT); 12053 12054 LLVM_DEBUG({ 12055 dbgs() << "Terms after sorting:\n"; 12056 for (const SCEV *T : NewTerms) 12057 dbgs() << *T << "\n"; 12058 }); 12059 12060 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 12061 Sizes.clear(); 12062 return; 12063 } 12064 12065 // The last element to be pushed into Sizes is the size of an element. 12066 Sizes.push_back(ElementSize); 12067 12068 LLVM_DEBUG({ 12069 dbgs() << "Sizes:\n"; 12070 for (const SCEV *S : Sizes) 12071 dbgs() << *S << "\n"; 12072 }); 12073 } 12074 12075 void ScalarEvolution::computeAccessFunctions( 12076 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 12077 SmallVectorImpl<const SCEV *> &Sizes) { 12078 // Early exit in case this SCEV is not an affine multivariate function. 12079 if (Sizes.empty()) 12080 return; 12081 12082 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 12083 if (!AR->isAffine()) 12084 return; 12085 12086 const SCEV *Res = Expr; 12087 int Last = Sizes.size() - 1; 12088 for (int i = Last; i >= 0; i--) { 12089 const SCEV *Q, *R; 12090 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 12091 12092 LLVM_DEBUG({ 12093 dbgs() << "Res: " << *Res << "\n"; 12094 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 12095 dbgs() << "Res divided by Sizes[i]:\n"; 12096 dbgs() << "Quotient: " << *Q << "\n"; 12097 dbgs() << "Remainder: " << *R << "\n"; 12098 }); 12099 12100 Res = Q; 12101 12102 // Do not record the last subscript corresponding to the size of elements in 12103 // the array. 12104 if (i == Last) { 12105 12106 // Bail out if the remainder is too complex. 12107 if (isa<SCEVAddRecExpr>(R)) { 12108 Subscripts.clear(); 12109 Sizes.clear(); 12110 return; 12111 } 12112 12113 continue; 12114 } 12115 12116 // Record the access function for the current subscript. 12117 Subscripts.push_back(R); 12118 } 12119 12120 // Also push in last position the remainder of the last division: it will be 12121 // the access function of the innermost dimension. 12122 Subscripts.push_back(Res); 12123 12124 std::reverse(Subscripts.begin(), Subscripts.end()); 12125 12126 LLVM_DEBUG({ 12127 dbgs() << "Subscripts:\n"; 12128 for (const SCEV *S : Subscripts) 12129 dbgs() << *S << "\n"; 12130 }); 12131 } 12132 12133 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 12134 /// sizes of an array access. Returns the remainder of the delinearization that 12135 /// is the offset start of the array. The SCEV->delinearize algorithm computes 12136 /// the multiples of SCEV coefficients: that is a pattern matching of sub 12137 /// expressions in the stride and base of a SCEV corresponding to the 12138 /// computation of a GCD (greatest common divisor) of base and stride. When 12139 /// SCEV->delinearize fails, it returns the SCEV unchanged. 12140 /// 12141 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 12142 /// 12143 /// void foo(long n, long m, long o, double A[n][m][o]) { 12144 /// 12145 /// for (long i = 0; i < n; i++) 12146 /// for (long j = 0; j < m; j++) 12147 /// for (long k = 0; k < o; k++) 12148 /// A[i][j][k] = 1.0; 12149 /// } 12150 /// 12151 /// the delinearization input is the following AddRec SCEV: 12152 /// 12153 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 12154 /// 12155 /// From this SCEV, we are able to say that the base offset of the access is %A 12156 /// because it appears as an offset that does not divide any of the strides in 12157 /// the loops: 12158 /// 12159 /// CHECK: Base offset: %A 12160 /// 12161 /// and then SCEV->delinearize determines the size of some of the dimensions of 12162 /// the array as these are the multiples by which the strides are happening: 12163 /// 12164 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 12165 /// 12166 /// Note that the outermost dimension remains of UnknownSize because there are 12167 /// no strides that would help identifying the size of the last dimension: when 12168 /// the array has been statically allocated, one could compute the size of that 12169 /// dimension by dividing the overall size of the array by the size of the known 12170 /// dimensions: %m * %o * 8. 12171 /// 12172 /// Finally delinearize provides the access functions for the array reference 12173 /// that does correspond to A[i][j][k] of the above C testcase: 12174 /// 12175 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 12176 /// 12177 /// The testcases are checking the output of a function pass: 12178 /// DelinearizationPass that walks through all loads and stores of a function 12179 /// asking for the SCEV of the memory access with respect to all enclosing 12180 /// loops, calling SCEV->delinearize on that and printing the results. 12181 void ScalarEvolution::delinearize(const SCEV *Expr, 12182 SmallVectorImpl<const SCEV *> &Subscripts, 12183 SmallVectorImpl<const SCEV *> &Sizes, 12184 const SCEV *ElementSize) { 12185 // First step: collect parametric terms. 12186 SmallVector<const SCEV *, 4> Terms; 12187 collectParametricTerms(Expr, Terms); 12188 12189 if (Terms.empty()) 12190 return; 12191 12192 // Second step: find subscript sizes. 12193 findArrayDimensions(Terms, Sizes, ElementSize); 12194 12195 if (Sizes.empty()) 12196 return; 12197 12198 // Third step: compute the access functions for each subscript. 12199 computeAccessFunctions(Expr, Subscripts, Sizes); 12200 12201 if (Subscripts.empty()) 12202 return; 12203 12204 LLVM_DEBUG({ 12205 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 12206 dbgs() << "ArrayDecl[UnknownSize]"; 12207 for (const SCEV *S : Sizes) 12208 dbgs() << "[" << *S << "]"; 12209 12210 dbgs() << "\nArrayRef"; 12211 for (const SCEV *S : Subscripts) 12212 dbgs() << "[" << *S << "]"; 12213 dbgs() << "\n"; 12214 }); 12215 } 12216 12217 bool ScalarEvolution::getIndexExpressionsFromGEP( 12218 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 12219 SmallVectorImpl<int> &Sizes) { 12220 assert(Subscripts.empty() && Sizes.empty() && 12221 "Expected output lists to be empty on entry to this function."); 12222 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 12223 Type *Ty = GEP->getPointerOperandType(); 12224 bool DroppedFirstDim = false; 12225 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 12226 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 12227 if (i == 1) { 12228 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 12229 Ty = PtrTy->getElementType(); 12230 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 12231 Ty = ArrayTy->getElementType(); 12232 } else { 12233 Subscripts.clear(); 12234 Sizes.clear(); 12235 return false; 12236 } 12237 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 12238 if (Const->getValue()->isZero()) { 12239 DroppedFirstDim = true; 12240 continue; 12241 } 12242 Subscripts.push_back(Expr); 12243 continue; 12244 } 12245 12246 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 12247 if (!ArrayTy) { 12248 Subscripts.clear(); 12249 Sizes.clear(); 12250 return false; 12251 } 12252 12253 Subscripts.push_back(Expr); 12254 if (!(DroppedFirstDim && i == 2)) 12255 Sizes.push_back(ArrayTy->getNumElements()); 12256 12257 Ty = ArrayTy->getElementType(); 12258 } 12259 return !Subscripts.empty(); 12260 } 12261 12262 //===----------------------------------------------------------------------===// 12263 // SCEVCallbackVH Class Implementation 12264 //===----------------------------------------------------------------------===// 12265 12266 void ScalarEvolution::SCEVCallbackVH::deleted() { 12267 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12268 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12269 SE->ConstantEvolutionLoopExitValue.erase(PN); 12270 SE->eraseValueFromMap(getValPtr()); 12271 // this now dangles! 12272 } 12273 12274 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12275 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12276 12277 // Forget all the expressions associated with users of the old value, 12278 // so that future queries will recompute the expressions using the new 12279 // value. 12280 Value *Old = getValPtr(); 12281 SmallVector<User *, 16> Worklist(Old->users()); 12282 SmallPtrSet<User *, 8> Visited; 12283 while (!Worklist.empty()) { 12284 User *U = Worklist.pop_back_val(); 12285 // Deleting the Old value will cause this to dangle. Postpone 12286 // that until everything else is done. 12287 if (U == Old) 12288 continue; 12289 if (!Visited.insert(U).second) 12290 continue; 12291 if (PHINode *PN = dyn_cast<PHINode>(U)) 12292 SE->ConstantEvolutionLoopExitValue.erase(PN); 12293 SE->eraseValueFromMap(U); 12294 llvm::append_range(Worklist, U->users()); 12295 } 12296 // Delete the Old value. 12297 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12298 SE->ConstantEvolutionLoopExitValue.erase(PN); 12299 SE->eraseValueFromMap(Old); 12300 // this now dangles! 12301 } 12302 12303 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12304 : CallbackVH(V), SE(se) {} 12305 12306 //===----------------------------------------------------------------------===// 12307 // ScalarEvolution Class Implementation 12308 //===----------------------------------------------------------------------===// 12309 12310 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12311 AssumptionCache &AC, DominatorTree &DT, 12312 LoopInfo &LI) 12313 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12314 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12315 LoopDispositions(64), BlockDispositions(64) { 12316 // To use guards for proving predicates, we need to scan every instruction in 12317 // relevant basic blocks, and not just terminators. Doing this is a waste of 12318 // time if the IR does not actually contain any calls to 12319 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12320 // 12321 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12322 // to _add_ guards to the module when there weren't any before, and wants 12323 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12324 // efficient in lieu of being smart in that rather obscure case. 12325 12326 auto *GuardDecl = F.getParent()->getFunction( 12327 Intrinsic::getName(Intrinsic::experimental_guard)); 12328 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12329 } 12330 12331 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12332 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12333 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12334 ValueExprMap(std::move(Arg.ValueExprMap)), 12335 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12336 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12337 PendingMerges(std::move(Arg.PendingMerges)), 12338 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12339 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12340 PredicatedBackedgeTakenCounts( 12341 std::move(Arg.PredicatedBackedgeTakenCounts)), 12342 ConstantEvolutionLoopExitValue( 12343 std::move(Arg.ConstantEvolutionLoopExitValue)), 12344 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12345 LoopDispositions(std::move(Arg.LoopDispositions)), 12346 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12347 BlockDispositions(std::move(Arg.BlockDispositions)), 12348 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12349 SignedRanges(std::move(Arg.SignedRanges)), 12350 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12351 UniquePreds(std::move(Arg.UniquePreds)), 12352 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12353 LoopUsers(std::move(Arg.LoopUsers)), 12354 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12355 FirstUnknown(Arg.FirstUnknown) { 12356 Arg.FirstUnknown = nullptr; 12357 } 12358 12359 ScalarEvolution::~ScalarEvolution() { 12360 // Iterate through all the SCEVUnknown instances and call their 12361 // destructors, so that they release their references to their values. 12362 for (SCEVUnknown *U = FirstUnknown; U;) { 12363 SCEVUnknown *Tmp = U; 12364 U = U->Next; 12365 Tmp->~SCEVUnknown(); 12366 } 12367 FirstUnknown = nullptr; 12368 12369 ExprValueMap.clear(); 12370 ValueExprMap.clear(); 12371 HasRecMap.clear(); 12372 BackedgeTakenCounts.clear(); 12373 PredicatedBackedgeTakenCounts.clear(); 12374 12375 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12376 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12377 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12378 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12379 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12380 } 12381 12382 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12383 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12384 } 12385 12386 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12387 const Loop *L) { 12388 // Print all inner loops first 12389 for (Loop *I : *L) 12390 PrintLoopInfo(OS, SE, I); 12391 12392 OS << "Loop "; 12393 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12394 OS << ": "; 12395 12396 SmallVector<BasicBlock *, 8> ExitingBlocks; 12397 L->getExitingBlocks(ExitingBlocks); 12398 if (ExitingBlocks.size() != 1) 12399 OS << "<multiple exits> "; 12400 12401 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12402 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12403 else 12404 OS << "Unpredictable backedge-taken count.\n"; 12405 12406 if (ExitingBlocks.size() > 1) 12407 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12408 OS << " exit count for " << ExitingBlock->getName() << ": " 12409 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12410 } 12411 12412 OS << "Loop "; 12413 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12414 OS << ": "; 12415 12416 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12417 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12418 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12419 OS << ", actual taken count either this or zero."; 12420 } else { 12421 OS << "Unpredictable max backedge-taken count. "; 12422 } 12423 12424 OS << "\n" 12425 "Loop "; 12426 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12427 OS << ": "; 12428 12429 SCEVUnionPredicate Pred; 12430 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12431 if (!isa<SCEVCouldNotCompute>(PBT)) { 12432 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12433 OS << " Predicates:\n"; 12434 Pred.print(OS, 4); 12435 } else { 12436 OS << "Unpredictable predicated backedge-taken count. "; 12437 } 12438 OS << "\n"; 12439 12440 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12441 OS << "Loop "; 12442 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12443 OS << ": "; 12444 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12445 } 12446 } 12447 12448 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12449 switch (LD) { 12450 case ScalarEvolution::LoopVariant: 12451 return "Variant"; 12452 case ScalarEvolution::LoopInvariant: 12453 return "Invariant"; 12454 case ScalarEvolution::LoopComputable: 12455 return "Computable"; 12456 } 12457 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12458 } 12459 12460 void ScalarEvolution::print(raw_ostream &OS) const { 12461 // ScalarEvolution's implementation of the print method is to print 12462 // out SCEV values of all instructions that are interesting. Doing 12463 // this potentially causes it to create new SCEV objects though, 12464 // which technically conflicts with the const qualifier. This isn't 12465 // observable from outside the class though, so casting away the 12466 // const isn't dangerous. 12467 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12468 12469 if (ClassifyExpressions) { 12470 OS << "Classifying expressions for: "; 12471 F.printAsOperand(OS, /*PrintType=*/false); 12472 OS << "\n"; 12473 for (Instruction &I : instructions(F)) 12474 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12475 OS << I << '\n'; 12476 OS << " --> "; 12477 const SCEV *SV = SE.getSCEV(&I); 12478 SV->print(OS); 12479 if (!isa<SCEVCouldNotCompute>(SV)) { 12480 OS << " U: "; 12481 SE.getUnsignedRange(SV).print(OS); 12482 OS << " S: "; 12483 SE.getSignedRange(SV).print(OS); 12484 } 12485 12486 const Loop *L = LI.getLoopFor(I.getParent()); 12487 12488 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12489 if (AtUse != SV) { 12490 OS << " --> "; 12491 AtUse->print(OS); 12492 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12493 OS << " U: "; 12494 SE.getUnsignedRange(AtUse).print(OS); 12495 OS << " S: "; 12496 SE.getSignedRange(AtUse).print(OS); 12497 } 12498 } 12499 12500 if (L) { 12501 OS << "\t\t" "Exits: "; 12502 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12503 if (!SE.isLoopInvariant(ExitValue, L)) { 12504 OS << "<<Unknown>>"; 12505 } else { 12506 OS << *ExitValue; 12507 } 12508 12509 bool First = true; 12510 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12511 if (First) { 12512 OS << "\t\t" "LoopDispositions: { "; 12513 First = false; 12514 } else { 12515 OS << ", "; 12516 } 12517 12518 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12519 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12520 } 12521 12522 for (auto *InnerL : depth_first(L)) { 12523 if (InnerL == L) 12524 continue; 12525 if (First) { 12526 OS << "\t\t" "LoopDispositions: { "; 12527 First = false; 12528 } else { 12529 OS << ", "; 12530 } 12531 12532 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12533 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12534 } 12535 12536 OS << " }"; 12537 } 12538 12539 OS << "\n"; 12540 } 12541 } 12542 12543 OS << "Determining loop execution counts for: "; 12544 F.printAsOperand(OS, /*PrintType=*/false); 12545 OS << "\n"; 12546 for (Loop *I : LI) 12547 PrintLoopInfo(OS, &SE, I); 12548 } 12549 12550 ScalarEvolution::LoopDisposition 12551 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12552 auto &Values = LoopDispositions[S]; 12553 for (auto &V : Values) { 12554 if (V.getPointer() == L) 12555 return V.getInt(); 12556 } 12557 Values.emplace_back(L, LoopVariant); 12558 LoopDisposition D = computeLoopDisposition(S, L); 12559 auto &Values2 = LoopDispositions[S]; 12560 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12561 if (V.getPointer() == L) { 12562 V.setInt(D); 12563 break; 12564 } 12565 } 12566 return D; 12567 } 12568 12569 ScalarEvolution::LoopDisposition 12570 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12571 switch (S->getSCEVType()) { 12572 case scConstant: 12573 return LoopInvariant; 12574 case scPtrToInt: 12575 case scTruncate: 12576 case scZeroExtend: 12577 case scSignExtend: 12578 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12579 case scAddRecExpr: { 12580 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12581 12582 // If L is the addrec's loop, it's computable. 12583 if (AR->getLoop() == L) 12584 return LoopComputable; 12585 12586 // Add recurrences are never invariant in the function-body (null loop). 12587 if (!L) 12588 return LoopVariant; 12589 12590 // Everything that is not defined at loop entry is variant. 12591 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12592 return LoopVariant; 12593 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12594 " dominate the contained loop's header?"); 12595 12596 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12597 if (AR->getLoop()->contains(L)) 12598 return LoopInvariant; 12599 12600 // This recurrence is variant w.r.t. L if any of its operands 12601 // are variant. 12602 for (auto *Op : AR->operands()) 12603 if (!isLoopInvariant(Op, L)) 12604 return LoopVariant; 12605 12606 // Otherwise it's loop-invariant. 12607 return LoopInvariant; 12608 } 12609 case scAddExpr: 12610 case scMulExpr: 12611 case scUMaxExpr: 12612 case scSMaxExpr: 12613 case scUMinExpr: 12614 case scSMinExpr: { 12615 bool HasVarying = false; 12616 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12617 LoopDisposition D = getLoopDisposition(Op, L); 12618 if (D == LoopVariant) 12619 return LoopVariant; 12620 if (D == LoopComputable) 12621 HasVarying = true; 12622 } 12623 return HasVarying ? LoopComputable : LoopInvariant; 12624 } 12625 case scUDivExpr: { 12626 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12627 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12628 if (LD == LoopVariant) 12629 return LoopVariant; 12630 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12631 if (RD == LoopVariant) 12632 return LoopVariant; 12633 return (LD == LoopInvariant && RD == LoopInvariant) ? 12634 LoopInvariant : LoopComputable; 12635 } 12636 case scUnknown: 12637 // All non-instruction values are loop invariant. All instructions are loop 12638 // invariant if they are not contained in the specified loop. 12639 // Instructions are never considered invariant in the function body 12640 // (null loop) because they are defined within the "loop". 12641 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12642 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12643 return LoopInvariant; 12644 case scCouldNotCompute: 12645 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12646 } 12647 llvm_unreachable("Unknown SCEV kind!"); 12648 } 12649 12650 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12651 return getLoopDisposition(S, L) == LoopInvariant; 12652 } 12653 12654 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12655 return getLoopDisposition(S, L) == LoopComputable; 12656 } 12657 12658 ScalarEvolution::BlockDisposition 12659 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12660 auto &Values = BlockDispositions[S]; 12661 for (auto &V : Values) { 12662 if (V.getPointer() == BB) 12663 return V.getInt(); 12664 } 12665 Values.emplace_back(BB, DoesNotDominateBlock); 12666 BlockDisposition D = computeBlockDisposition(S, BB); 12667 auto &Values2 = BlockDispositions[S]; 12668 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12669 if (V.getPointer() == BB) { 12670 V.setInt(D); 12671 break; 12672 } 12673 } 12674 return D; 12675 } 12676 12677 ScalarEvolution::BlockDisposition 12678 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12679 switch (S->getSCEVType()) { 12680 case scConstant: 12681 return ProperlyDominatesBlock; 12682 case scPtrToInt: 12683 case scTruncate: 12684 case scZeroExtend: 12685 case scSignExtend: 12686 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12687 case scAddRecExpr: { 12688 // This uses a "dominates" query instead of "properly dominates" query 12689 // to test for proper dominance too, because the instruction which 12690 // produces the addrec's value is a PHI, and a PHI effectively properly 12691 // dominates its entire containing block. 12692 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12693 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12694 return DoesNotDominateBlock; 12695 12696 // Fall through into SCEVNAryExpr handling. 12697 LLVM_FALLTHROUGH; 12698 } 12699 case scAddExpr: 12700 case scMulExpr: 12701 case scUMaxExpr: 12702 case scSMaxExpr: 12703 case scUMinExpr: 12704 case scSMinExpr: { 12705 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12706 bool Proper = true; 12707 for (const SCEV *NAryOp : NAry->operands()) { 12708 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12709 if (D == DoesNotDominateBlock) 12710 return DoesNotDominateBlock; 12711 if (D == DominatesBlock) 12712 Proper = false; 12713 } 12714 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12715 } 12716 case scUDivExpr: { 12717 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12718 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12719 BlockDisposition LD = getBlockDisposition(LHS, BB); 12720 if (LD == DoesNotDominateBlock) 12721 return DoesNotDominateBlock; 12722 BlockDisposition RD = getBlockDisposition(RHS, BB); 12723 if (RD == DoesNotDominateBlock) 12724 return DoesNotDominateBlock; 12725 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12726 ProperlyDominatesBlock : DominatesBlock; 12727 } 12728 case scUnknown: 12729 if (Instruction *I = 12730 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12731 if (I->getParent() == BB) 12732 return DominatesBlock; 12733 if (DT.properlyDominates(I->getParent(), BB)) 12734 return ProperlyDominatesBlock; 12735 return DoesNotDominateBlock; 12736 } 12737 return ProperlyDominatesBlock; 12738 case scCouldNotCompute: 12739 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12740 } 12741 llvm_unreachable("Unknown SCEV kind!"); 12742 } 12743 12744 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12745 return getBlockDisposition(S, BB) >= DominatesBlock; 12746 } 12747 12748 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12749 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12750 } 12751 12752 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12753 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12754 } 12755 12756 void 12757 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12758 ValuesAtScopes.erase(S); 12759 LoopDispositions.erase(S); 12760 BlockDispositions.erase(S); 12761 UnsignedRanges.erase(S); 12762 SignedRanges.erase(S); 12763 ExprValueMap.erase(S); 12764 HasRecMap.erase(S); 12765 MinTrailingZerosCache.erase(S); 12766 12767 for (auto I = PredicatedSCEVRewrites.begin(); 12768 I != PredicatedSCEVRewrites.end();) { 12769 std::pair<const SCEV *, const Loop *> Entry = I->first; 12770 if (Entry.first == S) 12771 PredicatedSCEVRewrites.erase(I++); 12772 else 12773 ++I; 12774 } 12775 12776 auto RemoveSCEVFromBackedgeMap = 12777 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12778 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12779 BackedgeTakenInfo &BEInfo = I->second; 12780 if (BEInfo.hasOperand(S)) 12781 Map.erase(I++); 12782 else 12783 ++I; 12784 } 12785 }; 12786 12787 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12788 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12789 } 12790 12791 void 12792 ScalarEvolution::getUsedLoops(const SCEV *S, 12793 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12794 struct FindUsedLoops { 12795 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12796 : LoopsUsed(LoopsUsed) {} 12797 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12798 bool follow(const SCEV *S) { 12799 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12800 LoopsUsed.insert(AR->getLoop()); 12801 return true; 12802 } 12803 12804 bool isDone() const { return false; } 12805 }; 12806 12807 FindUsedLoops F(LoopsUsed); 12808 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12809 } 12810 12811 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12812 SmallPtrSet<const Loop *, 8> LoopsUsed; 12813 getUsedLoops(S, LoopsUsed); 12814 for (auto *L : LoopsUsed) 12815 LoopUsers[L].push_back(S); 12816 } 12817 12818 void ScalarEvolution::verify() const { 12819 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12820 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12821 12822 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12823 12824 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12825 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12826 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12827 12828 const SCEV *visitConstant(const SCEVConstant *Constant) { 12829 return SE.getConstant(Constant->getAPInt()); 12830 } 12831 12832 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12833 return SE.getUnknown(Expr->getValue()); 12834 } 12835 12836 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12837 return SE.getCouldNotCompute(); 12838 } 12839 }; 12840 12841 SCEVMapper SCM(SE2); 12842 12843 while (!LoopStack.empty()) { 12844 auto *L = LoopStack.pop_back_val(); 12845 llvm::append_range(LoopStack, *L); 12846 12847 auto *CurBECount = SCM.visit( 12848 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12849 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12850 12851 if (CurBECount == SE2.getCouldNotCompute() || 12852 NewBECount == SE2.getCouldNotCompute()) { 12853 // NB! This situation is legal, but is very suspicious -- whatever pass 12854 // change the loop to make a trip count go from could not compute to 12855 // computable or vice-versa *should have* invalidated SCEV. However, we 12856 // choose not to assert here (for now) since we don't want false 12857 // positives. 12858 continue; 12859 } 12860 12861 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12862 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12863 // not propagate undef aggressively). This means we can (and do) fail 12864 // verification in cases where a transform makes the trip count of a loop 12865 // go from "undef" to "undef+1" (say). The transform is fine, since in 12866 // both cases the loop iterates "undef" times, but SCEV thinks we 12867 // increased the trip count of the loop by 1 incorrectly. 12868 continue; 12869 } 12870 12871 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12872 SE.getTypeSizeInBits(NewBECount->getType())) 12873 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12874 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12875 SE.getTypeSizeInBits(NewBECount->getType())) 12876 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12877 12878 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12879 12880 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12881 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12882 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12883 dbgs() << "Old: " << *CurBECount << "\n"; 12884 dbgs() << "New: " << *NewBECount << "\n"; 12885 dbgs() << "Delta: " << *Delta << "\n"; 12886 std::abort(); 12887 } 12888 } 12889 12890 // Collect all valid loops currently in LoopInfo. 12891 SmallPtrSet<Loop *, 32> ValidLoops; 12892 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12893 while (!Worklist.empty()) { 12894 Loop *L = Worklist.pop_back_val(); 12895 if (ValidLoops.contains(L)) 12896 continue; 12897 ValidLoops.insert(L); 12898 Worklist.append(L->begin(), L->end()); 12899 } 12900 // Check for SCEV expressions referencing invalid/deleted loops. 12901 for (auto &KV : ValueExprMap) { 12902 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12903 if (!AR) 12904 continue; 12905 assert(ValidLoops.contains(AR->getLoop()) && 12906 "AddRec references invalid loop"); 12907 } 12908 } 12909 12910 bool ScalarEvolution::invalidate( 12911 Function &F, const PreservedAnalyses &PA, 12912 FunctionAnalysisManager::Invalidator &Inv) { 12913 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12914 // of its dependencies is invalidated. 12915 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12916 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12917 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12918 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12919 Inv.invalidate<LoopAnalysis>(F, PA); 12920 } 12921 12922 AnalysisKey ScalarEvolutionAnalysis::Key; 12923 12924 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12925 FunctionAnalysisManager &AM) { 12926 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12927 AM.getResult<AssumptionAnalysis>(F), 12928 AM.getResult<DominatorTreeAnalysis>(F), 12929 AM.getResult<LoopAnalysis>(F)); 12930 } 12931 12932 PreservedAnalyses 12933 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12934 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12935 return PreservedAnalyses::all(); 12936 } 12937 12938 PreservedAnalyses 12939 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12940 // For compatibility with opt's -analyze feature under legacy pass manager 12941 // which was not ported to NPM. This keeps tests using 12942 // update_analyze_test_checks.py working. 12943 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12944 << F.getName() << "':\n"; 12945 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12946 return PreservedAnalyses::all(); 12947 } 12948 12949 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12950 "Scalar Evolution Analysis", false, true) 12951 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12952 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12953 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12954 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12955 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12956 "Scalar Evolution Analysis", false, true) 12957 12958 char ScalarEvolutionWrapperPass::ID = 0; 12959 12960 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12961 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12962 } 12963 12964 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12965 SE.reset(new ScalarEvolution( 12966 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12967 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12968 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12969 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12970 return false; 12971 } 12972 12973 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12974 12975 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12976 SE->print(OS); 12977 } 12978 12979 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12980 if (!VerifySCEV) 12981 return; 12982 12983 SE->verify(); 12984 } 12985 12986 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12987 AU.setPreservesAll(); 12988 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12989 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12990 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12991 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12992 } 12993 12994 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12995 const SCEV *RHS) { 12996 FoldingSetNodeID ID; 12997 assert(LHS->getType() == RHS->getType() && 12998 "Type mismatch between LHS and RHS"); 12999 // Unique this node based on the arguments 13000 ID.AddInteger(SCEVPredicate::P_Equal); 13001 ID.AddPointer(LHS); 13002 ID.AddPointer(RHS); 13003 void *IP = nullptr; 13004 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13005 return S; 13006 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13007 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13008 UniquePreds.InsertNode(Eq, IP); 13009 return Eq; 13010 } 13011 13012 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13013 const SCEVAddRecExpr *AR, 13014 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13015 FoldingSetNodeID ID; 13016 // Unique this node based on the arguments 13017 ID.AddInteger(SCEVPredicate::P_Wrap); 13018 ID.AddPointer(AR); 13019 ID.AddInteger(AddedFlags); 13020 void *IP = nullptr; 13021 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13022 return S; 13023 auto *OF = new (SCEVAllocator) 13024 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13025 UniquePreds.InsertNode(OF, IP); 13026 return OF; 13027 } 13028 13029 namespace { 13030 13031 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13032 public: 13033 13034 /// Rewrites \p S in the context of a loop L and the SCEV predication 13035 /// infrastructure. 13036 /// 13037 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13038 /// equivalences present in \p Pred. 13039 /// 13040 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13041 /// \p NewPreds such that the result will be an AddRecExpr. 13042 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13043 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13044 SCEVUnionPredicate *Pred) { 13045 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13046 return Rewriter.visit(S); 13047 } 13048 13049 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13050 if (Pred) { 13051 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13052 for (auto *Pred : ExprPreds) 13053 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13054 if (IPred->getLHS() == Expr) 13055 return IPred->getRHS(); 13056 } 13057 return convertToAddRecWithPreds(Expr); 13058 } 13059 13060 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13061 const SCEV *Operand = visit(Expr->getOperand()); 13062 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13063 if (AR && AR->getLoop() == L && AR->isAffine()) { 13064 // This couldn't be folded because the operand didn't have the nuw 13065 // flag. Add the nusw flag as an assumption that we could make. 13066 const SCEV *Step = AR->getStepRecurrence(SE); 13067 Type *Ty = Expr->getType(); 13068 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13069 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13070 SE.getSignExtendExpr(Step, Ty), L, 13071 AR->getNoWrapFlags()); 13072 } 13073 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13074 } 13075 13076 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13077 const SCEV *Operand = visit(Expr->getOperand()); 13078 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13079 if (AR && AR->getLoop() == L && AR->isAffine()) { 13080 // This couldn't be folded because the operand didn't have the nsw 13081 // flag. Add the nssw flag as an assumption that we could make. 13082 const SCEV *Step = AR->getStepRecurrence(SE); 13083 Type *Ty = Expr->getType(); 13084 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13085 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13086 SE.getSignExtendExpr(Step, Ty), L, 13087 AR->getNoWrapFlags()); 13088 } 13089 return SE.getSignExtendExpr(Operand, Expr->getType()); 13090 } 13091 13092 private: 13093 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13094 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13095 SCEVUnionPredicate *Pred) 13096 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13097 13098 bool addOverflowAssumption(const SCEVPredicate *P) { 13099 if (!NewPreds) { 13100 // Check if we've already made this assumption. 13101 return Pred && Pred->implies(P); 13102 } 13103 NewPreds->insert(P); 13104 return true; 13105 } 13106 13107 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13108 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13109 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13110 return addOverflowAssumption(A); 13111 } 13112 13113 // If \p Expr represents a PHINode, we try to see if it can be represented 13114 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13115 // to add this predicate as a runtime overflow check, we return the AddRec. 13116 // If \p Expr does not meet these conditions (is not a PHI node, or we 13117 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13118 // return \p Expr. 13119 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13120 if (!isa<PHINode>(Expr->getValue())) 13121 return Expr; 13122 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13123 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13124 if (!PredicatedRewrite) 13125 return Expr; 13126 for (auto *P : PredicatedRewrite->second){ 13127 // Wrap predicates from outer loops are not supported. 13128 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13129 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13130 if (L != AR->getLoop()) 13131 return Expr; 13132 } 13133 if (!addOverflowAssumption(P)) 13134 return Expr; 13135 } 13136 return PredicatedRewrite->first; 13137 } 13138 13139 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13140 SCEVUnionPredicate *Pred; 13141 const Loop *L; 13142 }; 13143 13144 } // end anonymous namespace 13145 13146 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13147 SCEVUnionPredicate &Preds) { 13148 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13149 } 13150 13151 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13152 const SCEV *S, const Loop *L, 13153 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13154 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13155 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13156 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13157 13158 if (!AddRec) 13159 return nullptr; 13160 13161 // Since the transformation was successful, we can now transfer the SCEV 13162 // predicates. 13163 for (auto *P : TransformPreds) 13164 Preds.insert(P); 13165 13166 return AddRec; 13167 } 13168 13169 /// SCEV predicates 13170 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13171 SCEVPredicateKind Kind) 13172 : FastID(ID), Kind(Kind) {} 13173 13174 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13175 const SCEV *LHS, const SCEV *RHS) 13176 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13177 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13178 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13179 } 13180 13181 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13182 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13183 13184 if (!Op) 13185 return false; 13186 13187 return Op->LHS == LHS && Op->RHS == RHS; 13188 } 13189 13190 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13191 13192 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13193 13194 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13195 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13196 } 13197 13198 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13199 const SCEVAddRecExpr *AR, 13200 IncrementWrapFlags Flags) 13201 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13202 13203 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13204 13205 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13206 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13207 13208 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13209 } 13210 13211 bool SCEVWrapPredicate::isAlwaysTrue() const { 13212 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13213 IncrementWrapFlags IFlags = Flags; 13214 13215 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13216 IFlags = clearFlags(IFlags, IncrementNSSW); 13217 13218 return IFlags == IncrementAnyWrap; 13219 } 13220 13221 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13222 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13223 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13224 OS << "<nusw>"; 13225 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13226 OS << "<nssw>"; 13227 OS << "\n"; 13228 } 13229 13230 SCEVWrapPredicate::IncrementWrapFlags 13231 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13232 ScalarEvolution &SE) { 13233 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13234 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13235 13236 // We can safely transfer the NSW flag as NSSW. 13237 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13238 ImpliedFlags = IncrementNSSW; 13239 13240 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13241 // If the increment is positive, the SCEV NUW flag will also imply the 13242 // WrapPredicate NUSW flag. 13243 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13244 if (Step->getValue()->getValue().isNonNegative()) 13245 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13246 } 13247 13248 return ImpliedFlags; 13249 } 13250 13251 /// Union predicates don't get cached so create a dummy set ID for it. 13252 SCEVUnionPredicate::SCEVUnionPredicate() 13253 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13254 13255 bool SCEVUnionPredicate::isAlwaysTrue() const { 13256 return all_of(Preds, 13257 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13258 } 13259 13260 ArrayRef<const SCEVPredicate *> 13261 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13262 auto I = SCEVToPreds.find(Expr); 13263 if (I == SCEVToPreds.end()) 13264 return ArrayRef<const SCEVPredicate *>(); 13265 return I->second; 13266 } 13267 13268 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13269 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13270 return all_of(Set->Preds, 13271 [this](const SCEVPredicate *I) { return this->implies(I); }); 13272 13273 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13274 if (ScevPredsIt == SCEVToPreds.end()) 13275 return false; 13276 auto &SCEVPreds = ScevPredsIt->second; 13277 13278 return any_of(SCEVPreds, 13279 [N](const SCEVPredicate *I) { return I->implies(N); }); 13280 } 13281 13282 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13283 13284 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13285 for (auto Pred : Preds) 13286 Pred->print(OS, Depth); 13287 } 13288 13289 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13290 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13291 for (auto Pred : Set->Preds) 13292 add(Pred); 13293 return; 13294 } 13295 13296 if (implies(N)) 13297 return; 13298 13299 const SCEV *Key = N->getExpr(); 13300 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13301 " associated expression!"); 13302 13303 SCEVToPreds[Key].push_back(N); 13304 Preds.push_back(N); 13305 } 13306 13307 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13308 Loop &L) 13309 : SE(SE), L(L) {} 13310 13311 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13312 const SCEV *Expr = SE.getSCEV(V); 13313 RewriteEntry &Entry = RewriteMap[Expr]; 13314 13315 // If we already have an entry and the version matches, return it. 13316 if (Entry.second && Generation == Entry.first) 13317 return Entry.second; 13318 13319 // We found an entry but it's stale. Rewrite the stale entry 13320 // according to the current predicate. 13321 if (Entry.second) 13322 Expr = Entry.second; 13323 13324 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13325 Entry = {Generation, NewSCEV}; 13326 13327 return NewSCEV; 13328 } 13329 13330 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13331 if (!BackedgeCount) { 13332 SCEVUnionPredicate BackedgePred; 13333 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13334 addPredicate(BackedgePred); 13335 } 13336 return BackedgeCount; 13337 } 13338 13339 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13340 if (Preds.implies(&Pred)) 13341 return; 13342 Preds.add(&Pred); 13343 updateGeneration(); 13344 } 13345 13346 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13347 return Preds; 13348 } 13349 13350 void PredicatedScalarEvolution::updateGeneration() { 13351 // If the generation number wrapped recompute everything. 13352 if (++Generation == 0) { 13353 for (auto &II : RewriteMap) { 13354 const SCEV *Rewritten = II.second.second; 13355 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13356 } 13357 } 13358 } 13359 13360 void PredicatedScalarEvolution::setNoOverflow( 13361 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13362 const SCEV *Expr = getSCEV(V); 13363 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13364 13365 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13366 13367 // Clear the statically implied flags. 13368 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13369 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13370 13371 auto II = FlagsMap.insert({V, Flags}); 13372 if (!II.second) 13373 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13374 } 13375 13376 bool PredicatedScalarEvolution::hasNoOverflow( 13377 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13378 const SCEV *Expr = getSCEV(V); 13379 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13380 13381 Flags = SCEVWrapPredicate::clearFlags( 13382 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13383 13384 auto II = FlagsMap.find(V); 13385 13386 if (II != FlagsMap.end()) 13387 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13388 13389 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13390 } 13391 13392 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13393 const SCEV *Expr = this->getSCEV(V); 13394 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13395 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13396 13397 if (!New) 13398 return nullptr; 13399 13400 for (auto *P : NewPreds) 13401 Preds.add(P); 13402 13403 updateGeneration(); 13404 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13405 return New; 13406 } 13407 13408 PredicatedScalarEvolution::PredicatedScalarEvolution( 13409 const PredicatedScalarEvolution &Init) 13410 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13411 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13412 for (auto I : Init.FlagsMap) 13413 FlagsMap.insert(I); 13414 } 13415 13416 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13417 // For each block. 13418 for (auto *BB : L.getBlocks()) 13419 for (auto &I : *BB) { 13420 if (!SE.isSCEVable(I.getType())) 13421 continue; 13422 13423 auto *Expr = SE.getSCEV(&I); 13424 auto II = RewriteMap.find(Expr); 13425 13426 if (II == RewriteMap.end()) 13427 continue; 13428 13429 // Don't print things that are not interesting. 13430 if (II->second.second == Expr) 13431 continue; 13432 13433 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13434 OS.indent(Depth + 2) << *Expr << "\n"; 13435 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13436 } 13437 } 13438 13439 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13440 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13441 // for URem with constant power-of-2 second operands. 13442 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13443 // 4, A / B becomes X / 8). 13444 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13445 const SCEV *&RHS) { 13446 // Try to match 'zext (trunc A to iB) to iY', which is used 13447 // for URem with constant power-of-2 second operands. Make sure the size of 13448 // the operand A matches the size of the whole expressions. 13449 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13450 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13451 LHS = Trunc->getOperand(); 13452 // Bail out if the type of the LHS is larger than the type of the 13453 // expression for now. 13454 if (getTypeSizeInBits(LHS->getType()) > 13455 getTypeSizeInBits(Expr->getType())) 13456 return false; 13457 if (LHS->getType() != Expr->getType()) 13458 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13459 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13460 << getTypeSizeInBits(Trunc->getType())); 13461 return true; 13462 } 13463 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13464 if (Add == nullptr || Add->getNumOperands() != 2) 13465 return false; 13466 13467 const SCEV *A = Add->getOperand(1); 13468 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13469 13470 if (Mul == nullptr) 13471 return false; 13472 13473 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13474 // (SomeExpr + (-(SomeExpr / B) * B)). 13475 if (Expr == getURemExpr(A, B)) { 13476 LHS = A; 13477 RHS = B; 13478 return true; 13479 } 13480 return false; 13481 }; 13482 13483 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13484 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13485 return MatchURemWithDivisor(Mul->getOperand(1)) || 13486 MatchURemWithDivisor(Mul->getOperand(2)); 13487 13488 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13489 if (Mul->getNumOperands() == 2) 13490 return MatchURemWithDivisor(Mul->getOperand(1)) || 13491 MatchURemWithDivisor(Mul->getOperand(0)) || 13492 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13493 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13494 return false; 13495 } 13496 13497 const SCEV * 13498 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13499 SmallVector<BasicBlock*, 16> ExitingBlocks; 13500 L->getExitingBlocks(ExitingBlocks); 13501 13502 // Form an expression for the maximum exit count possible for this loop. We 13503 // merge the max and exact information to approximate a version of 13504 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13505 SmallVector<const SCEV*, 4> ExitCounts; 13506 for (BasicBlock *ExitingBB : ExitingBlocks) { 13507 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13508 if (isa<SCEVCouldNotCompute>(ExitCount)) 13509 ExitCount = getExitCount(L, ExitingBB, 13510 ScalarEvolution::ConstantMaximum); 13511 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13512 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13513 "We should only have known counts for exiting blocks that " 13514 "dominate latch!"); 13515 ExitCounts.push_back(ExitCount); 13516 } 13517 } 13518 if (ExitCounts.empty()) 13519 return getCouldNotCompute(); 13520 return getUMinFromMismatchedTypes(ExitCounts); 13521 } 13522 13523 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13524 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13525 /// we cannot guarantee that the replacement is loop invariant in the loop of 13526 /// the AddRec. 13527 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13528 ValueToSCEVMapTy ⤅ 13529 13530 public: 13531 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13532 : SCEVRewriteVisitor(SE), Map(M) {} 13533 13534 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13535 13536 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13537 auto I = Map.find(Expr->getValue()); 13538 if (I == Map.end()) 13539 return Expr; 13540 return I->second; 13541 } 13542 }; 13543 13544 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13545 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13546 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13547 // If we have LHS == 0, check if LHS is computing a property of some unknown 13548 // SCEV %v which we can rewrite %v to express explicitly. 13549 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13550 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13551 RHSC->getValue()->isNullValue()) { 13552 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13553 // explicitly express that. 13554 const SCEV *URemLHS = nullptr; 13555 const SCEV *URemRHS = nullptr; 13556 if (matchURem(LHS, URemLHS, URemRHS)) { 13557 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13558 Value *V = LHSUnknown->getValue(); 13559 auto Multiple = 13560 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13561 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13562 RewriteMap[V] = Multiple; 13563 return; 13564 } 13565 } 13566 } 13567 13568 if (!isa<SCEVUnknown>(LHS)) { 13569 std::swap(LHS, RHS); 13570 Predicate = CmpInst::getSwappedPredicate(Predicate); 13571 } 13572 13573 // For now, limit to conditions that provide information about unknown 13574 // expressions. 13575 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13576 if (!LHSUnknown) 13577 return; 13578 13579 // Check whether LHS has already been rewritten. In that case we want to 13580 // chain further rewrites onto the already rewritten value. 13581 auto I = RewriteMap.find(LHSUnknown->getValue()); 13582 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13583 13584 // TODO: use information from more predicates. 13585 switch (Predicate) { 13586 case CmpInst::ICMP_ULT: 13587 if (!containsAddRecurrence(RHS)) 13588 RewriteMap[LHSUnknown->getValue()] = getUMinExpr( 13589 RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13590 break; 13591 case CmpInst::ICMP_ULE: 13592 if (!containsAddRecurrence(RHS)) 13593 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(RewrittenLHS, RHS); 13594 break; 13595 case CmpInst::ICMP_UGT: 13596 if (!containsAddRecurrence(RHS)) 13597 RewriteMap[LHSUnknown->getValue()] = 13598 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13599 break; 13600 case CmpInst::ICMP_UGE: 13601 if (!containsAddRecurrence(RHS)) 13602 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(RewrittenLHS, RHS); 13603 break; 13604 case CmpInst::ICMP_EQ: 13605 if (isa<SCEVConstant>(RHS)) 13606 RewriteMap[LHSUnknown->getValue()] = RHS; 13607 break; 13608 case CmpInst::ICMP_NE: 13609 if (isa<SCEVConstant>(RHS) && 13610 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13611 RewriteMap[LHSUnknown->getValue()] = 13612 getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13613 break; 13614 default: 13615 break; 13616 } 13617 }; 13618 // Starting at the loop predecessor, climb up the predecessor chain, as long 13619 // as there are predecessors that can be found that have unique successors 13620 // leading to the original header. 13621 // TODO: share this logic with isLoopEntryGuardedByCond. 13622 ValueToSCEVMapTy RewriteMap; 13623 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13624 L->getLoopPredecessor(), L->getHeader()); 13625 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13626 13627 const BranchInst *LoopEntryPredicate = 13628 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13629 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13630 continue; 13631 13632 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13633 SmallVector<Value *, 8> Worklist; 13634 SmallPtrSet<Value *, 8> Visited; 13635 Worklist.push_back(LoopEntryPredicate->getCondition()); 13636 while (!Worklist.empty()) { 13637 Value *Cond = Worklist.pop_back_val(); 13638 if (!Visited.insert(Cond).second) 13639 continue; 13640 13641 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13642 auto Predicate = 13643 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13644 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13645 getSCEV(Cmp->getOperand(1)), RewriteMap); 13646 continue; 13647 } 13648 13649 Value *L, *R; 13650 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13651 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13652 Worklist.push_back(L); 13653 Worklist.push_back(R); 13654 } 13655 } 13656 } 13657 13658 // Also collect information from assumptions dominating the loop. 13659 for (auto &AssumeVH : AC.assumptions()) { 13660 if (!AssumeVH) 13661 continue; 13662 auto *AssumeI = cast<CallInst>(AssumeVH); 13663 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13664 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13665 continue; 13666 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13667 getSCEV(Cmp->getOperand(1)), RewriteMap); 13668 } 13669 13670 if (RewriteMap.empty()) 13671 return Expr; 13672 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13673 return Rewriter.visit(Expr); 13674 } 13675